// Admin Dashboard JavaScript
const API_URL = 'api_handler.php';
let currentBookingStatus = 'all';

// Tab Navigation
document.querySelectorAll('.menu-link').forEach(link => {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        const tabName = this.getAttribute('data-tab');
        
        document.querySelectorAll('.menu-link').forEach(el => el.classList.remove('active'));
        this.classList.add('active');
        
        const titles = {
            'dashboard': 'Dashboard',
            'profile': 'My Profile',
            'staff': 'Staff Management',
            'assignments': 'Task Assignments',
            'reservations': 'Manage Reservations',
            'customers': 'Customer Management',
            'services': 'Service Management',
            'team': 'Team Management',
            'blog': 'Blog Management',
            'gallery': 'Gallery Management',
            'contact': 'Contact Messages',
            'feedback': 'Customer Feedback'
        };
        document.getElementById('pageTitle').textContent = titles[tabName] || 'Dashboard';
        
        document.querySelectorAll('.tab-content').forEach(tab => {
            tab.classList.remove('active');
        });
        
        const targetTab = document.getElementById(tabName);
        if (targetTab) {
            targetTab.classList.add('active');
            
            // Load data when tab is clicked
            if (tabName === 'dashboard') {
                loadDashboardStats();
                loadRecentBookings();
            } else if (tabName === 'reservations') {
                loadBookings('all');
            } else if (tabName === 'customers') {
                loadCustomers();
            } else if (tabName === 'services') {
                loadServices();
            } else if (tabName === 'team') {
                loadTeam();
            } else if (tabName === 'blog') {
                loadBlog();
            } else if (tabName === 'gallery') {
                loadGallery();
            } else if (tabName === 'contact') {
                loadContactMessages();
            } else if (tabName === 'feedback') {
                loadFeedback();
            } else if (tabName === 'profile') {
                loadProfile();
            } else if (tabName === 'staff') {
                loadStaff();
            } else if (tabName === 'assignments') {
                loadAssignments('all');
                loadStaffForAssignment();
            }
        }
        
        if (window.innerWidth <= 768) {
            document.getElementById('sidebar').classList.remove('active');
        }
    });
});

// Toggle Sidebar on Mobile
if (document.getElementById('toggleBtn')) {
    document.getElementById('toggleBtn').addEventListener('click', function() {
        document.getElementById('sidebar').classList.toggle('active');
    });
}

function updateToggleButton() {
    const toggleBtn = document.getElementById('toggleBtn');
    if (window.innerWidth <= 768) {
        toggleBtn.style.display = 'inline-block';
    } else {
        toggleBtn.style.display = 'none';
        document.getElementById('sidebar').classList.remove('active');
    }
}

window.addEventListener('resize', updateToggleButton);
updateToggleButton();

document.addEventListener('click', function(event) {
    const sidebar = document.getElementById('sidebar');
    const toggleBtn = document.getElementById('toggleBtn');
    
    if (window.innerWidth <= 768 && 
        !sidebar.contains(event.target) && 
        !toggleBtn.contains(event.target) &&
        sidebar.classList.contains('active')) {
        sidebar.classList.remove('active');
    }
});

// Load Dashboard Stats
function loadDashboardStats() {
    fetch(`${API_URL}?action=get_bookings`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const bookings = data.data;
                const pending = bookings.filter(b => b.status === 'pending').length;
                const confirmed = bookings.filter(b => b.status === 'confirmed').length;
                const completed = bookings.filter(b => b.status === 'completed').length;
                const total = bookings.length;
                const revenue = bookings.reduce((sum, b) => {
                    const amount = parseFloat(b.total_amount || b.price || 0);
                    return sum + (isNaN(amount) ? 0 : amount);
                }, 0);

                document.getElementById('dashboardStats').innerHTML = `
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px;">
                        <div style="background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); color: white; padding: 25px; border-radius: 12px; text-align: center;">
                            <div style="font-size: 32px; font-weight: 700; margin-bottom: 5px;">${total}</div>
                            <div>Total Reservations</div>
                        </div>
                        <div style="background: linear-gradient(135deg, var(--warning), #f59e0b); color: white; padding: 25px; border-radius: 12px; text-align: center;">
                            <div style="font-size: 32px; font-weight: 700; margin-bottom: 5px;">${pending}</div>
                            <div>Pending</div>
                        </div>
                        <div style="background: linear-gradient(135deg, var(--info), #1d4ed8); color: white; padding: 25px; border-radius: 12px; text-align: center;">
                            <div style="font-size: 32px; font-weight: 700; margin-bottom: 5px;">${confirmed}</div>
                            <div>Confirmed</div>
                        </div>
                        <div style="background: linear-gradient(135deg, #10b981, #059669); color: white; padding: 25px; border-radius: 12px; text-align: center;">
                            <div style="font-size: 32px; font-weight: 700; margin-bottom: 5px;">${completed}</div>
                            <div>Completed</div>
                        </div>
                        <div style="background: linear-gradient(135deg, #f87171, #dc2626); color: white; padding: 25px; border-radius: 12px; text-align: center;">
                            <div style="font-size: 32px; font-weight: 700; margin-bottom: 5px;">$${revenue.toFixed(2)}</div>
                            <div>Total Revenue</div>
                        </div>
                    </div>
                `;
            }
        })
        .catch(error => console.error('Error loading stats:', error));
}

// Load Recent Bookings
function loadRecentBookings() {
    fetch(`${API_URL}?action=get_bookings`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const bookings = data.data.slice(0, 5);
                let html = `
                    <table>
                        <thead>
                            <tr>
                                <th>Booking ID</th>
                                <th>Customer</th>
                                <th>Service</th>
                                <th>Date</th>
                                <th>Status</th>
                                <th>Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                bookings.forEach(booking => {
                    const statusClass = `status-${booking.status}`;
                    html += `
                        <tr>
                            <td>#BK${booking.id}</td>
                            <td>${booking.customer_name}</td>
                            <td>${booking.service_name}</td>
                            <td>${booking.booking_date}</td>
                            <td><span class="status-badge ${statusClass}">${booking.status.charAt(0).toUpperCase() + booking.status.slice(1)}</span></td>
                            <td>$${parseFloat(booking.total_amount).toFixed(2)}</td>
                        </tr>
                    `;
                });
                
                html += `
                        </tbody>
                    </table>
                `;
                
                document.getElementById('recentBookings').innerHTML = html;
            }
        })
        .catch(error => console.error('Error loading bookings:', error));
}

// Load Bookings
function loadBookings(status = 'all') {
    currentBookingStatus = status;
    const url = status === 'all' ? `${API_URL}?action=get_bookings` : `${API_URL}?action=get_bookings&status=${status}`;
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderBookingsTable(data.data);
            }
        })
        .catch(error => console.error('Error loading bookings:', error));
}

function renderBookingsTable(bookings) {
    let html = `
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Customer</th>
                    <th>Phone</th>
                    <th>Service</th>
                    <th>Date & Time</th>
                    <th>Status</th>
                    <th>Amount</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    bookings.forEach(booking => {
        const statusClass = `status-${booking.status}`;
        const amount = parseFloat(booking.total_amount || booking.price || 0);
        const displayAmount = isNaN(amount) ? '0.00' : amount.toFixed(2);
        
        html += `
            <tr>
                <td>#BK${booking.id}</td>
                <td>${booking.customer_name}</td>
                <td>${booking.phone || 'N/A'}</td>
                <td>${booking.service_name}</td>
                <td>${booking.booking_date} ${booking.booking_time}</td>
                <td><span class="status-badge ${statusClass}">${booking.status.charAt(0).toUpperCase() + booking.status.slice(1)}</span></td>
                <td>$${displayAmount}</td>
                <td>
                    <button class="btn-edit" onclick="editBooking(${booking.id})">Edit</button>
                    ${booking.status === 'pending' ? `
                        <button class="btn-approve" onclick="approveBooking(${booking.id})">Approve</button>
                        <button class="btn-reject" onclick="rejectBooking(${booking.id})">Reject</button>
                    ` : ''}
                    <button class="btn-danger" onclick="deleteBooking(${booking.id})">Delete</button>
                </td>
            </tr>
        `;
    });
    
    html += `
            </tbody>
        </table>
    `;
    
    document.getElementById('bookingsContainer').innerHTML = html;
}

function filterBookings(status) {
    document.querySelectorAll('.nav-tab').forEach(tab => tab.classList.remove('active'));
    event.target.classList.add('active');
    loadBookings(status);
}

// Load Customers
function loadCustomers() {
    fetch(`${API_URL}?action=get_customers`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderCustomersTable(data.data);
                populateCustomerSelects(data.data);
            }
        })
        .catch(error => console.error('Error loading customers:', error));
}

function renderCustomersTable(customers) {
    let html = `
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>City</th>
                    <th>Bookings</th>
                    <th>Total Spent</th>
                    <th>Joined</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    customers.forEach(customer => {
        const joinDate = new Date(customer.created_at).toLocaleDateString();
        html += `
            <tr>
                <td>${customer.name}</td>
                <td>${customer.email}</td>
                <td>${customer.phone || 'N/A'}</td>
                <td>${customer.city || 'N/A'}</td>
                <td>${customer.total_bookings || 0}</td>
                <td>$${customer.total_spent}</td>
                <td>${joinDate}</td>
                <td>
                    <button class="btn-edit" onclick="editCustomer(${customer.id})">Edit</button>
                    <button class="btn-danger" onclick="deleteCustomer(${customer.id})">Delete</button>
                </td>
            </tr>
        `;
    });
    
    html += `
            </tbody>
        </table>
    `;
    
    document.getElementById('customersContainer').innerHTML = html;
}

// Load Services
function loadServices() {
    fetch(`${API_URL}?action=get_services`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderServicesTable(data.data);
                populateServiceSelects(data.data);
            }
        })
        .catch(error => console.error('Error loading services:', error));
}

function renderServicesTable(services) {
    let html = `
        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px;">
    `;
    
    services.forEach(service => {
        let imageUrl = 'assets/img/default/no-image.svg';
        if (service.image) {
            imageUrl = service.image.startsWith('assets/') ? service.image : `assets/img/service/${service.image}`;
        }
        html += `
            <div style="background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: all 0.3s ease;">
                <div style="width: 100%; height: 200px; background: #f0f0f0; overflow: hidden;">
                    <img src="${imageUrl}" alt="${service.name}" style="width: 100%; height: 100%; object-fit: cover;" onerror="this.src='assets/img/default/no-image.svg'">
                </div>
                <div style="padding: 15px;">
                    <h4 style="margin: 0 0 8px 0; color: #109c3d;">${service.name}</h4>
                    <p style="margin: 0 0 10px 0; color: #64748b; font-size: 12px;">${service.category || 'N/A'}</p>
                    <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                        <span style="color: #109c3d; font-weight: 600;">$${parseFloat(service.price).toFixed(2)}</span>
                        <span style="color: #64748b; font-size: 12px;">${service.duration} mins</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; margin-bottom: 12px;">
                        <span style="color: #64748b; font-size: 12px;">Bookings: ${service.bookings_count || 0}</span>
                        <span class="status-badge status-completed" style="font-size: 11px;">${service.status}</span>
                    </div>
                    <div style="display: flex; gap: 8px;">
                        <button class="btn-edit" onclick="editService(${service.id})" style="flex: 1; padding: 8px;">Edit</button>
                        <button class="btn-danger" onclick="deleteService(${service.id})" style="flex: 1; padding: 8px;">Delete</button>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += `
        </div>
    `;
    
    document.getElementById('servicesContainer').innerHTML = html;
}

function populateServiceSelects(services) {
    let options = '<option value="">Select Service</option>';
    services.forEach(service => {
        options += `<option value="${service.id}">${service.name}</option>`;
    });
    document.getElementById('bookingService').innerHTML = options;
    document.getElementById('galleryService').innerHTML = options;
}

function populateCustomerSelects(customers) {
    let options = '<option value="">Select Customer</option>';
    customers.forEach(customer => {
        options += `<option value="${customer.id}">${customer.name} (ID: ${customer.id})</option>`;
    });
    const customerSelect = document.getElementById('bookingCustomer');
    if (customerSelect) {
        customerSelect.innerHTML = options;
    }
}

// Load Team
function loadTeam() {
    fetch(`${API_URL}?action=get_team`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderTeamTable(data.data);
            }
        })
        .catch(error => console.error('Error loading team:', error));
}

function renderTeamTable(team) {
    let html = `
        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px;">
    `;
    
    team.forEach(member => {
        // Try different possible image column names
        const memberImage = member.image || member.profile_image || '';
        const imageUrl = memberImage ? (memberImage.startsWith('assets/') ? memberImage : `assets/img/team/${memberImage}`) : 'assets/img/default/no-image.svg';
        
        html += `
            <div style="background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: all 0.3s ease;">
                <div style="width: 100%; height: 220px; background: #f0f0f0; overflow: hidden;">
                    <img src="${imageUrl}" alt="${member.name}" style="width: 100%; height: 100%; object-fit: cover;" onerror="this.src='assets/img/default/no-image.svg'">
                </div>
                <div style="padding: 15px;">
                    <h4 style="margin: 0 0 5px 0; color: #0f172a;">${member.name}</h4>
                    <p style="margin: 0 0 10px 0; color: #109c3d; font-size: 13px; font-weight: 600;">${member.position || 'Team Member'}</p>
                    <p style="margin: 0 0 10px 0; color: #64748b; font-size: 12px;">${member.specialization || 'N/A'}</p>
                    <div style="display: flex; justify-content: space-between; margin-bottom: 10px; font-size: 12px;">
                        <span style="color: #64748b;"><i class="fa-solid fa-envelope"></i> ${member.email || 'N/A'}</span>
                        <span style="color: #64748b;"><i class="fa-solid fa-phone"></i> ${member.phone || 'N/A'}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; margin-bottom: 12px; font-size: 12px;">
                        <span style="color: #64748b;"><i class="fa-solid fa-briefcase"></i> ${member.experience || 0} years</span>
                        <span class="status-badge status-completed" style="font-size: 11px;">${member.status}</span>
                    </div>
                    <div style="display: flex; gap: 8px;">
                        <button class="btn-edit" onclick="editTeam(${member.id})" style="flex: 1; padding: 8px;">Edit</button>
                        <button class="btn-danger" onclick="deleteTeam(${member.id})" style="flex: 1; padding: 8px;">Delete</button>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += `
        </div>
    `;
    
    document.getElementById('teamContainer').innerHTML = html;
}

// Load Blog
function loadBlog() {
    fetch(`${API_URL}?action=get_blog_posts`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderBlogTable(data.data);
            }
        })
        .catch(error => console.error('Error loading blog:', error));
}

function renderBlogTable(posts) {
    let html = `
        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px;">
    `;
    
    posts.forEach(post => {
        const createDate = new Date(post.created_at).toLocaleDateString();
        // Try different possible image column names
        const postImage = post.featured_image || post.image || 'assets/img/default/no-image.svg';
        const imageUrl = postImage.startsWith('assets/') ? postImage : `assets/img/blog/${postImage}`;
        
        html += `
            <div style="background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: all 0.3s ease;">
                <div style="width: 100%; height: 180px; background: #f0f0f0; overflow: hidden;">
                    <img src="${imageUrl}" alt="${post.title}" style="width: 100%; height: 100%; object-fit: cover;" onerror="this.src='assets/img/default/no-image.svg'">
                </div>
                <div style="padding: 15px;">
                    <h4 style="margin: 0 0 8px 0; color: #0f172a; line-height: 1.3;">${post.title}</h4>
                    <p style="margin: 0 0 10px 0; color: #64748b; font-size: 12px;"><i class="fa-solid fa-user"></i> ${post.author_name || 'Admin'}</p>
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                        <span style="background: #e8f5e9; color: #109c3d; padding: 4px 8px; border-radius: 4px; font-size: 11px;">${post.category || 'General'}</span>
                        <span style="color: #64748b; font-size: 11px;">${createDate}</span>
                    </div>
                    <div style="display: flex; gap: 8px;">
                        <button class="btn-edit" onclick="editBlog(${post.id})" style="flex: 1; padding: 8px;">Edit</button>
                        <button class="btn-danger" onclick="deleteBlog(${post.id})" style="flex: 1; padding: 8px;">Delete</button>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += `
        </div>
    `;
    
    document.getElementById('blogContainer').innerHTML = html;
}

// Load Gallery
function loadGallery() {
    fetch(`${API_URL}?action=get_gallery`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderGalleryTable(data.data);
            }
        })
        .catch(error => console.error('Error loading gallery:', error));
}

function renderGalleryTable(gallery) {
    let html = `
        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px;">
    `;
    
    gallery.forEach(item => {
        const imageUrl = item.image_url || 'assets/img/default/no-image.svg';
        const addedDate = new Date(item.created_at).toLocaleDateString();
        html += `
            <div style="position: relative; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: all 0.3s ease; background: #f0f0f0; group: hover;" onmouseover="this.style.boxShadow='0 5px 15px rgba(0,0,0,0.2)'" onmouseout="this.style.boxShadow='0 2px 8px rgba(0,0,0,0.1)'">
                <div style="width: 100%; height: 200px; overflow: hidden;">
                    <img src="${imageUrl}" alt="${item.title}" style="width: 100%; height: 100%; object-fit: cover;" onerror="this.src='assets/img/default/no-image.svg'">
                </div>
                <div style="position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(transparent, rgba(0,0,0,0.7)); padding: 12px; color: white;">
                    <h5 style="margin: 0 0 4px 0; font-size: 13px;">${item.title}</h5>
                    <p style="margin: 0 0 6px 0; font-size: 11px; opacity: 0.9;">${item.service_name || 'Gallery'}</p>
                    <div style="display: flex; gap: 6px; font-size: 11px;">
                        <span style="background: rgba(255,255,255,0.2); padding: 2px 6px; border-radius: 3px;">${item.category || 'N/A'}</span>
                        <span style="background: rgba(255,255,255,0.2); padding: 2px 6px; border-radius: 3px;">${addedDate}</span>
                    </div>
                </div>
                <div style="position: absolute; top: 8px; right: 8px; display: flex; gap: 5px; z-index: 10;">
                    <button class="btn-edit" onclick="editGallery(${item.id})" style="padding: 6px 10px; font-size: 12px; cursor: pointer; opacity: 0.9;">Edit</button>
                    <button class="btn-danger" onclick="deleteGallery(${item.id})" style="padding: 6px 10px; font-size: 12px; cursor: pointer; opacity: 0.9;">Delete</button>
                </div>
            </div>
        `;
    });
    
    html += `
        </div>
    `;
    
    document.getElementById('galleryContainer').innerHTML = html;
}

// Load Contact Messages
function loadContactMessages() {
    fetch(`${API_URL}?action=get_contact_messages`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderContactTable(data.data);
            }
        })
        .catch(error => console.error('Error loading contacts:', error));
}

function renderContactTable(messages) {
    let html = `
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Subject</th>
                    <th>Status</th>
                    <th>Received</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    messages.forEach(msg => {
        const receivedDate = new Date(msg.created_at).toLocaleDateString();
        const statusClass = msg.status === 'new' ? 'status-pending' : 'status-completed';
        html += `
            <tr>
                <td>${msg.name}</td>
                <td>${msg.email}</td>
                <td>${msg.phone || 'N/A'}</td>
                <td>${msg.subject}</td>
                <td><span class="status-badge ${statusClass}">${msg.status}</span></td>
                <td>${receivedDate}</td>
                <td>
                    <button class="btn-edit" onclick="viewContact(${msg.id})">View</button>
                    <button class="btn-danger" onclick="deleteContact(${msg.id})">Delete</button>
                </td>
            </tr>
        `;
    });
    
    html += `
            </tbody>
        </table>
    `;
    
    document.getElementById('contactContainer').innerHTML = html;
}

// Load Feedback
function loadFeedback() {
    fetch(`${API_URL}?action=get_feedback`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderFeedbackTable(data.data);
            }
        })
        .catch(error => console.error('Error loading feedback:', error));
}

function renderFeedbackTable(feedback) {
    if (!feedback || feedback.length === 0) {
        document.getElementById('feedbackContainer').innerHTML = '<p style="text-align: center; color: #64748b; padding: 20px;">No feedback available.</p>';
        return;
    }

    let html = `
        <table>
            <thead>
                <tr>
                    <th>Customer</th>
                    <th>Rating</th>
                    <th>Feedback</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    feedback.forEach(item => {
        const feedDate = new Date(item.created_at).toLocaleDateString();
        const stars = '⭐'.repeat(item.rating);
        const statusClass = item.status === 'pending' ? 'status-pending' : 'status-completed';
        html += `
            <tr>
                <td>${item.customer_name}</td>
                <td>${stars}</td>
                <td>${item.review_text || 'N/A'}</td>
                <td><span class="status-badge ${statusClass}">${item.status}</span></td>
                <td>${feedDate}</td>
                <td>
                    ${item.status === 'pending' ? `<button class="btn-approve" onclick="approveFeedback(${item.id})">Approve</button>` : ''}
                    <button class="btn-danger" onclick="deleteFeedback(${item.id})">Delete</button>
                </td>
            </tr>
        `;
    });
    
    html += `
            </tbody>
        </table>
    `;
    
    document.getElementById('feedbackContainer').innerHTML = html;
}

// MODAL FUNCTIONS

// Booking Modal
function openAddBookingModal() {
    document.getElementById('bookingId').value = '';
    document.getElementById('bookingForm').reset();
    document.getElementById('bookingModalTitle').textContent = 'Add Reservation';
    loadCustomers();
    loadServices();
    document.getElementById('bookingModal').classList.add('active');
}

function closeBookingModal() {
    document.getElementById('bookingModal').classList.remove('active');
}

function editBooking(bookingId) {
    fetch(`${API_URL}?action=get_booking_details&id=${bookingId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const booking = data.data;
                document.getElementById('bookingId').value = booking.id;
                document.getElementById('bookingCustomer').value = booking.user_id;
                document.getElementById('bookingService').value = booking.service_id;
                document.getElementById('bookingDate').value = booking.booking_date;
                document.getElementById('bookingTime').value = booking.booking_time;
                document.getElementById('bookingAddress').value = booking.address;
                document.getElementById('bookingNotes').value = booking.notes;
                document.getElementById('bookingStatus').value = booking.status || 'pending';
                document.getElementById('bookingModalTitle').textContent = `Edit Reservation #${booking.id}`;
                loadCustomers();
                loadServices();
                document.getElementById('bookingModal').classList.add('active');
            }
        })
        .catch(error => console.error('Error loading booking:', error));
}

// Form Submissions
document.getElementById('bookingForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const bookingId = document.getElementById('bookingId').value;
    const action = bookingId ? 'edit_booking' : 'add_booking';
    
    const formData = new FormData();
    formData.append('action', action);
    if (bookingId) formData.append('booking_id', bookingId);
    formData.append('user_id', document.getElementById('bookingCustomer').value);
    formData.append('service_id', document.getElementById('bookingService').value);
    formData.append('booking_date', document.getElementById('bookingDate').value);
    formData.append('booking_time', document.getElementById('bookingTime').value);
    formData.append('address', document.getElementById('bookingAddress').value);
    formData.append('notes', document.getElementById('bookingNotes').value);
    formData.append('status', document.getElementById('bookingStatus').value);

    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('bookingModalAlert', 'Reservation saved successfully!', 'success');
                setTimeout(() => {
                    closeBookingModal();
                    loadBookings(currentBookingStatus);
                }, 1500);
            } else {
                showAlert('bookingModalAlert', data.message, 'danger');
            }
        })
        .catch(error => showAlert('bookingModalAlert', 'Error saving reservation', 'danger'));
});

// Customer Modal
function openAddCustomerModal() {
    document.getElementById('customerId').value = '';
    document.getElementById('customerForm').reset();
    document.getElementById('customerModalTitle').textContent = 'Add Customer';
    document.getElementById('customerModal').classList.add('active');
}

function closeCustomerModal() {
    document.getElementById('customerModal').classList.remove('active');
}

function editCustomer(customerId) {
    fetch(`${API_URL}?action=get_customer_details&id=${customerId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const customer = data.data;
                document.getElementById('customerId').value = customer.id;
                document.getElementById('customerName').value = customer.name;
                document.getElementById('customerEmail').value = customer.email;
                document.getElementById('customerPhone').value = customer.phone;
                document.getElementById('customerCity').value = customer.city;
                document.getElementById('customerAddress').value = customer.address;
                document.getElementById('customerModalTitle').textContent = 'Edit Customer';
                document.getElementById('customerModal').classList.add('active');
            }
        })
        .catch(error => console.error('Error loading customer:', error));
}

document.getElementById('customerForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const customerId = document.getElementById('customerId').value;
    const action = customerId ? 'edit_customer' : 'add_customer';
    
    const formData = new FormData();
    formData.append('action', action);
    if (customerId) formData.append('customer_id', customerId);
    formData.append('name', document.getElementById('customerName').value);
    formData.append('email', document.getElementById('customerEmail').value);
    formData.append('phone', document.getElementById('customerPhone').value);
    formData.append('city', document.getElementById('customerCity').value);
    formData.append('address', document.getElementById('customerAddress').value);

    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('customerModalAlert', 'Customer saved successfully!', 'success');
                setTimeout(() => {
                    closeCustomerModal();
                    loadCustomers();
                }, 1500);
            } else {
                showAlert('customerModalAlert', data.message, 'danger');
            }
        })
        .catch(error => showAlert('customerModalAlert', 'Error saving customer', 'danger'));
});

// Service Modal
function openAddServiceModal() {
    document.getElementById('serviceId').value = '';
    document.getElementById('serviceForm').reset();
    document.getElementById('serviceModalTitle').textContent = 'Add Service';
    document.getElementById('serviceModal').classList.add('active');
}

function closeServiceModal() {
    document.getElementById('serviceModal').classList.remove('active');
}

function editService(serviceId) {
    fetch(`${API_URL}?action=get_service_details&id=${serviceId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const service = data.data;
                document.getElementById('serviceId').value = service.id;
                document.getElementById('serviceName').value = service.name;
                document.getElementById('serviceDescription').value = service.description;
                document.getElementById('servicePrice').value = service.price;
                document.getElementById('serviceDuration').value = service.duration;
                document.getElementById('serviceCategory').value = service.category;
                document.getElementById('serviceModalTitle').textContent = 'Edit Service';
                document.getElementById('serviceModal').classList.add('active');
            }
        })
        .catch(error => console.error('Error loading service:', error));
}

document.getElementById('serviceForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const serviceId = document.getElementById('serviceId').value;
    const action = serviceId ? 'edit_service' : 'add_service';
    
    const formData = new FormData();
    formData.append('action', action);
    if (serviceId) formData.append('service_id', serviceId);
    formData.append('name', document.getElementById('serviceName').value);
    formData.append('description', document.getElementById('serviceDescription').value);
    formData.append('price', document.getElementById('servicePrice').value);
    formData.append('duration', document.getElementById('serviceDuration').value);
    formData.append('category', document.getElementById('serviceCategory').value);
    
    // Handle image upload
    const serviceImage = document.getElementById('serviceImage');
    if (serviceImage.files.length > 0) {
        const uploadedPath = await uploadImage(serviceImage.files[0], 'services');
        if (uploadedPath) {
            formData.append('image', uploadedPath);
        }
    }

    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('serviceModalAlert', 'Service saved successfully!', 'success');
                setTimeout(() => {
                    closeServiceModal();
                    loadServices();
                }, 1500);
            } else {
                showAlert('serviceModalAlert', data.message, 'danger');
            }
        })
        .catch(error => showAlert('serviceModalAlert', 'Error saving service', 'danger'));
});

// Team Modal
function openAddTeamModal() {
    document.getElementById('teamId').value = '';
    document.getElementById('teamForm').reset();
    document.getElementById('teamModalTitle').textContent = 'Add Team Member';
    document.getElementById('teamModal').classList.add('active');
}

function closeTeamModal() {
    document.getElementById('teamModal').classList.remove('active');
}

function editTeam(teamId) {
    fetch(`${API_URL}?action=get_team_member_details&id=${teamId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const member = data.data;
                document.getElementById('teamId').value = member.id;
                document.getElementById('teamName').value = member.name;
                document.getElementById('teamPosition').value = member.position;
                document.getElementById('teamEmail').value = member.email;
                document.getElementById('teamPhone').value = member.phone;
                document.getElementById('teamSpecialization').value = member.specialization;
                document.getElementById('teamExperience').value = member.experience;
                document.getElementById('teamModalTitle').textContent = 'Edit Team Member';
                document.getElementById('teamModal').classList.add('active');
            }
        })
        .catch(error => console.error('Error loading team member:', error));
}

document.getElementById('teamForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const teamId = document.getElementById('teamId').value;
    const action = teamId ? 'edit_team_member' : 'add_team_member';
    
    const formData = new FormData();
    formData.append('action', action);
    if (teamId) formData.append('team_id', teamId);
    formData.append('name', document.getElementById('teamName').value);
    formData.append('position', document.getElementById('teamPosition').value);
    formData.append('email', document.getElementById('teamEmail').value);
    formData.append('phone', document.getElementById('teamPhone').value);
    formData.append('specialization', document.getElementById('teamSpecialization').value);
    formData.append('experience', document.getElementById('teamExperience').value);
    
    // Handle image upload
    const teamImage = document.getElementById('teamImage');
    if (teamImage.files.length > 0) {
        const uploadedPath = await uploadImage(teamImage.files[0], 'team');
        if (uploadedPath) {
            formData.append('image', uploadedPath);
        }
    }

    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('teamModalAlert', 'Team member saved successfully!', 'success');
                setTimeout(() => {
                    closeTeamModal();
                    loadTeam();
                }, 1500);
            } else {
                showAlert('teamModalAlert', data.message, 'danger');
            }
        })
        .catch(error => showAlert('teamModalAlert', 'Error saving team member', 'danger'));
});

// Blog Modal
function openAddBlogModal() {
    document.getElementById('blogId').value = '';
    document.getElementById('blogForm').reset();
    document.getElementById('blogModalTitle').textContent = 'Add Blog Post';
    document.getElementById('blogModal').classList.add('active');
}

function closeBlogModal() {
    document.getElementById('blogModal').classList.remove('active');
}

function editBlog(blogId) {
    fetch(`${API_URL}?action=get_blog_details&id=${blogId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const post = data.data;
                document.getElementById('blogId').value = post.id;
                document.getElementById('blogTitle').value = post.title;
                document.getElementById('blogContent').value = post.content;
                document.getElementById('blogCategory').value = post.category;
                document.getElementById('blogModalTitle').textContent = 'Edit Blog Post';
                document.getElementById('blogModal').classList.add('active');
            }
        })
        .catch(error => console.error('Error loading blog post:', error));
}

document.getElementById('blogForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const blogId = document.getElementById('blogId').value;
    const action = blogId ? 'edit_blog' : 'add_blog';
    
    const formData = new FormData();
    formData.append('action', action);
    if (blogId) formData.append('blog_id', blogId);
    formData.append('title', document.getElementById('blogTitle').value);
    formData.append('content', document.getElementById('blogContent').value);
    formData.append('category', document.getElementById('blogCategory').value);
    
    // Handle image upload
    const blogImage = document.getElementById('blogImage');
    if (blogImage.files.length > 0) {
        const uploadedPath = await uploadImage(blogImage.files[0], 'blog');
        if (uploadedPath) {
            formData.append('image', uploadedPath);
        }
    }

    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('blogModalAlert', 'Blog post saved successfully!', 'success');
                setTimeout(() => {
                    closeBlogModal();
                    loadBlog();
                }, 1500);
            } else {
                showAlert('blogModalAlert', data.message, 'danger');
            }
        })
        .catch(error => showAlert('blogModalAlert', 'Error saving blog post', 'danger'));
});

// Gallery Modal
function openAddGalleryModal() {
    document.getElementById('galleryId').value = '';
    document.getElementById('galleryForm').reset();
    document.getElementById('galleryModalTitle').textContent = 'Add Gallery Image';
    document.getElementById('galleryImagePreview').style.display = 'none';
    const galleryImageInput = document.getElementById('galleryImage');
    if (galleryImageInput) {
        galleryImageInput.setAttribute('required', 'required');
    }
    loadServices();
    document.getElementById('galleryModal').classList.add('active');
}

function closeGalleryModal() {
    document.getElementById('galleryModal').classList.remove('active');
}

document.getElementById('galleryForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const galleryId = document.getElementById('galleryId').value;
    const action = galleryId ? 'edit_gallery' : 'add_gallery';
    
    const formData = new FormData();
    formData.append('action', action);
    if (galleryId) formData.append('gallery_id', galleryId);
    formData.append('title', document.getElementById('galleryTitle').value);
    formData.append('description', document.getElementById('galleryDescription').value);
    formData.append('service_id', document.getElementById('galleryService').value);
    formData.append('category', document.getElementById('galleryCategory').value);
    
    // Handle image upload
    const galleryImage = document.getElementById('galleryImage');
    if (galleryImage.files.length > 0) {
        const uploadedPath = await uploadImage(galleryImage.files[0], 'gallery');
        if (uploadedPath) {
            formData.append('image_url', uploadedPath);
        } else {
            showAlert('galleryModalAlert', 'Failed to upload image', 'danger');
            return;
        }
    } else if (!galleryId) {
        showAlert('galleryModalAlert', 'Please select an image', 'danger');
        return;
    }

    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('galleryModalAlert', 'Gallery image saved successfully!', 'success');
                setTimeout(() => {
                    closeGalleryModal();
                    loadGallery();
                }, 1500);
            } else {
                showAlert('galleryModalAlert', data.message, 'danger');
            }
        })
        .catch(error => showAlert('galleryModalAlert', 'Error saving gallery image', 'danger'));
});

// Delete Functions
function deleteBooking(bookingId) {
    if (confirm('Are you sure you want to delete this reservation?')) {
        const formData = new FormData();
        formData.append('action', 'delete_booking');
        formData.append('booking_id', bookingId);

        fetch(API_URL, {method: 'POST', body: formData})
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadBookings(currentBookingStatus);
                }
            })
            .catch(error => console.error('Error deleting booking:', error));
    }
}

function approveBooking(bookingId) {
    const formData = new FormData();
    formData.append('action', 'approve_booking');
    formData.append('booking_id', bookingId);

    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadBookings(currentBookingStatus);
            }
        })
        .catch(error => console.error('Error approving booking:', error));
}

function rejectBooking(bookingId) {
    const formData = new FormData();
    formData.append('action', 'reject_booking');
    formData.append('booking_id', bookingId);

    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadBookings(currentBookingStatus);
            }
        })
        .catch(error => console.error('Error rejecting booking:', error));
}

function deleteCustomer(customerId) {
    if (confirm('Are you sure you want to delete this customer?')) {
        const formData = new FormData();
        formData.append('action', 'delete_customer');
        formData.append('customer_id', customerId);

        fetch(API_URL, {method: 'POST', body: formData})
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadCustomers();
                }
            })
            .catch(error => console.error('Error deleting customer:', error));
    }
}

function deleteService(serviceId) {
    if (confirm('Are you sure you want to delete this service?')) {
        const formData = new FormData();
        formData.append('action', 'delete_service');
        formData.append('service_id', serviceId);

        fetch(API_URL, {method: 'POST', body: formData})
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadServices();
                }
            })
            .catch(error => console.error('Error deleting service:', error));
    }
}

function deleteTeam(teamId) {
    if (confirm('Are you sure you want to delete this team member?')) {
        const formData = new FormData();
        formData.append('action', 'delete_team_member');
        formData.append('team_id', teamId);

        fetch(API_URL, {method: 'POST', body: formData})
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadTeam();
                }
            })
            .catch(error => console.error('Error deleting team member:', error));
    }
}

function deleteBlog(blogId) {
    if (confirm('Are you sure you want to delete this blog post?')) {
        const formData = new FormData();
        formData.append('action', 'delete_blog');
        formData.append('blog_id', blogId);

        fetch(API_URL, {method: 'POST', body: formData})
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadBlog();
                }
            })
            .catch(error => console.error('Error deleting blog post:', error));
    }
}

function editGallery(galleryId) {
    fetch(`${API_URL}?action=get_gallery_details&id=${galleryId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const gallery = data.data;
                document.getElementById('galleryId').value = gallery.id;
                document.getElementById('galleryTitle').value = gallery.title;
                document.getElementById('galleryDescription').value = gallery.description;
                document.getElementById('galleryCategory').value = gallery.category || '';
                document.getElementById('galleryService').value = gallery.service_id || '';
                document.getElementById('galleryModalTitle').textContent = 'Edit Gallery Image';
                
                // Remove required attribute from file input for edit mode
                const galleryImageInput = document.getElementById('galleryImage');
                if (galleryImageInput) {
                    galleryImageInput.removeAttribute('required');
                }
                
                // Show image preview if exists
                if (gallery.image_url) {
                    document.getElementById('galleryImageImg').src = gallery.image_url;
                    document.getElementById('galleryImagePreview').style.display = 'block';
                } else {
                    document.getElementById('galleryImagePreview').style.display = 'none';
                }
                
                loadServices();
                document.getElementById('galleryModal').classList.add('active');
            }
        })
        .catch(error => console.error('Error loading gallery image:', error));
}

function deleteGallery(galleryId) {
    if (confirm('Are you sure you want to delete this gallery image?')) {
        const formData = new FormData();
        formData.append('action', 'delete_gallery');
        formData.append('gallery_id', galleryId);

        fetch(API_URL, {method: 'POST', body: formData})
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadGallery();
                }
            })
            .catch(error => console.error('Error deleting gallery image:', error));
    }
}

function deleteContact(messageId) {
    if (confirm('Are you sure you want to delete this message?')) {
        const formData = new FormData();
        formData.append('action', 'delete_contact');
        formData.append('message_id', messageId);

        fetch(API_URL, {method: 'POST', body: formData})
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadContactMessages();
                }
            })
            .catch(error => console.error('Error deleting message:', error));
    }
}

function approveFeedback(feedbackId) {
    const formData = new FormData();
    formData.append('action', 'approve_feedback');
    formData.append('feedback_id', feedbackId);

    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadFeedback();
            }
        })
        .catch(error => console.error('Error approving feedback:', error));
}

function deleteFeedback(feedbackId) {
    if (confirm('Are you sure you want to delete this feedback?')) {
        const formData = new FormData();
        formData.append('action', 'delete_feedback');
        formData.append('feedback_id', feedbackId);

        fetch(API_URL, {method: 'POST', body: formData})
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadFeedback();
                }
            })
            .catch(error => console.error('Error deleting feedback:', error));
    }
}

function viewContact(messageId) {
    const formData = new FormData();
    formData.append('action', 'mark_contact_read');
    formData.append('message_id', messageId);

    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .catch(error => console.error('Error marking message as read:', error));
}

function showAlert(elementId, message, type) {
    const alert = document.createElement('div');
    alert.className = `alert alert-${type}`;
    alert.textContent = message;
    const element = document.getElementById(elementId);
    element.innerHTML = '';
    element.appendChild(alert);
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardStats();
    loadRecentBookings();
    
    // Add image preview listeners
    addImagePreviewListeners();
});

// Image preview functionality
function addImagePreviewListeners() {
    // Service image preview
    const serviceImage = document.getElementById('serviceImage');
    if (serviceImage) {
        serviceImage.addEventListener('change', function(e) {
            previewImage(e, 'serviceImageImg', 'serviceImagePreview');
        });
    }
    
    // Team image preview
    const teamImage = document.getElementById('teamImage');
    if (teamImage) {
        teamImage.addEventListener('change', function(e) {
            previewImage(e, 'teamImageImg', 'teamImagePreview');
        });
    }
    
    // Blog image preview
    const blogImage = document.getElementById('blogImage');
    if (blogImage) {
        blogImage.addEventListener('change', function(e) {
            previewImage(e, 'blogImageImg', 'blogImagePreview');
        });
    }
    
    // Gallery image preview
    const galleryImage = document.getElementById('galleryImage');
    if (galleryImage) {
        galleryImage.addEventListener('change', function(e) {
            previewImage(e, 'galleryImageImg', 'galleryImagePreview');
        });
    }
}

// Image upload function
async function uploadImage(file, type) {
    if (!file) return null;
    
    const uploadFormData = new FormData();
    uploadFormData.append('image', file);
    
    try {
        const response = await fetch(`upload_handler.php?type=${type}`, {
            method: 'POST',
            body: uploadFormData
        });
        
        const data = await response.json();
        if (data.success) {
            return data.file_path;
        } else {
            throw new Error(data.message);
        }
    } catch (error) {
        console.error('Upload error:', error);
        return null;
    }
}

// Image Preview Functions
document.getElementById('serviceImage')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    const preview = document.getElementById('serviceImagePreview');
    const img = document.getElementById('serviceImageImg');
    
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            img.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(file);
    } else {
        preview.style.display = 'none';
    }
});

document.getElementById('teamImage')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    const preview = document.getElementById('teamImagePreview');
    const img = document.getElementById('teamImageImg');
    
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            img.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(file);
    } else {
        preview.style.display = 'none';
    }
});

document.getElementById('blogImage')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    const preview = document.getElementById('blogImagePreview');
    const img = document.getElementById('blogImageImg');
    
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            img.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(file);
    } else {
        preview.style.display = 'none';
    }
});

document.getElementById('galleryImage')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    const preview = document.getElementById('galleryImagePreview');
    const img = document.getElementById('galleryImageImg');
    
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            img.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(file);
    } else {
        preview.style.display = 'none';
    }
});

// ===== PROFILE FUNCTIONS =====
function loadProfile() {
    const profileContainer = document.getElementById('profileContainer');
    profileContainer.innerHTML = '<div class="loading"><div class="spinner"></div>Loading profile...</div>';
    
    fetch(`${API_URL}?action=get_admin_profile`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data) {
                renderProfileCard(data.data);
            } else {
                profileContainer.innerHTML = '<p style="padding: 20px; text-align: center; color: #64748b;">Unable to load profile information</p>';
            }
        })
        .catch(error => {
            console.error('Error loading profile:', error);
            profileContainer.innerHTML = '<p style="padding: 20px; text-align: center; color: var(--danger);">Error loading profile. Please try again.</p>';
        });
}

function renderProfileCard(profile) {
    if (!profile || !profile.name) {
        document.getElementById('profileContainer').innerHTML = '<p style="padding: 20px; text-align: center; color: #64748b;">Unable to load profile information</p>';
        return;
    }

    const html = `
        <div style="display: grid; gap: 20px; max-width: 700px;">
            <!-- Profile Header Card -->
            <div style="background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)); color: white; padding: 30px; border-radius: 12px;">
                <div style="display: flex; align-items: center; justify-content: space-between;">
                    <div style="display: flex; align-items: center; gap: 20px;">
                        <div style="font-size: 56px; width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; background: rgba(255,255,255,0.2); border-radius: 50%;">
                            ${profile.name.charAt(0).toUpperCase()}
                        </div>
                        <div>
                            <h3 style="margin: 0 0 5px 0; font-size: 24px;">${profile.name}</h3>
                            <p style="margin: 0; opacity: 0.9;">Administrator</p>
                        </div>
                    </div>
                    <button onclick="openEditProfileModal()" style="background: white; color: var(--primary-color); border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-weight: 600; transition: all 0.3s ease;">
                        <i class="fa-solid fa-edit"></i> Edit
                    </button>
                </div>
            </div>

            <!-- Profile Details Grid -->
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div style="background: white; padding: 20px; border-radius: 8px; border: 1px solid var(--border-color);">
                    <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Email</label>
                    <p style="margin: 8px 0 0 0; color: #0f172a; font-size: 16px; font-weight: 600;">${profile.email || 'N/A'}</p>
                </div>
                <div style="background: white; padding: 20px; border-radius: 8px; border: 1px solid var(--border-color);">
                    <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Phone</label>
                    <p style="margin: 8px 0 0 0; color: #0f172a; font-size: 16px; font-weight: 600;">${profile.phone || 'Not set'}</p>
                </div>
                <div style="background: white; padding: 20px; border-radius: 8px; border: 1px solid var(--border-color);">
                    <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Role</label>
                    <p style="margin: 8px 0 0 0; color: #0f172a; font-size: 16px; font-weight: 600;">Administrator</p>
                </div>
                <div style="background: white; padding: 20px; border-radius: 8px; border: 1px solid var(--border-color);">
                    <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">ID</label>
                    <p style="margin: 8px 0 0 0; color: #0f172a; font-size: 16px; font-weight: 600;">#${profile.id}</p>
                </div>
            </div>

            <!-- Action Button -->
            <button onclick="openEditProfileModal()" style="background: var(--primary-color); color: white; border: none; padding: 12px 20px; border-radius: 8px; cursor: pointer; font-weight: 600; transition: all 0.3s ease;">
                <i class="fa-solid fa-key"></i> Change Password
            </button>
        </div>
    `;
    document.getElementById('profileContainer').innerHTML = html;
}

function openEditProfileModal() {
    fetch(`${API_URL}?action=get_admin_profile`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const profile = data.data;
                document.getElementById('profileName').value = profile.name || '';
                document.getElementById('profileEmail').value = profile.email || '';
                document.getElementById('profilePhone').value = profile.phone || '';
                document.getElementById('profilePassword').value = '';
                document.getElementById('profilePasswordConfirm').value = '';
                document.getElementById('profileModal').classList.add('active');
            } else {
                showAlert('profileModalAlert', 'Error loading profile data', 'danger');
            }
        })
        .catch(error => {
            console.error('Error loading profile:', error);
            showAlert('profileModalAlert', 'Error loading profile', 'danger');
        });
}

function closeProfileModal() {
    document.getElementById('profileModal').classList.remove('active');
}

document.getElementById('profileForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const name = document.getElementById('profileName').value;
    const email = document.getElementById('profileEmail').value;
    const phone = document.getElementById('profilePhone').value;
    const password = document.getElementById('profilePassword').value;
    const passwordConfirm = document.getElementById('profilePasswordConfirm').value;
    
    // Validate email format
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        showAlert('profileModalAlert', 'Please enter a valid email address', 'danger');
        return;
    }
    
    // Validate password if provided
    if (password) {
        if (password.length < 8) {
            showAlert('profileModalAlert', 'Password must be at least 8 characters', 'danger');
            return;
        }
        if (password !== passwordConfirm) {
            showAlert('profileModalAlert', 'Passwords do not match', 'danger');
            return;
        }
    }
    
    const formData = new FormData();
    formData.append('action', 'update_admin_profile');
    formData.append('name', name);
    formData.append('email', email);
    formData.append('phone', phone);
    if (password) formData.append('password', password);
    
    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('profileModalAlert', 'Profile updated successfully!', 'success');
                setTimeout(() => {
                    closeProfileModal();
                    loadProfile();
                }, 1500);
            } else {
                showAlert('profileModalAlert', data.message || 'Error updating profile', 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('profileModalAlert', 'Error updating profile', 'danger');
        });
});

// ===== STAFF FUNCTIONS =====
function loadStaff() {
    fetch(`${API_URL}?action=get_staff`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderStaffTable(data.data);
            }
        })
        .catch(error => console.error('Error loading staff:', error));
}

function renderStaffTable(staff) {
    let html = `
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Services</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    staff.forEach(member => {
        const statusBadge = member.status === 'active' 
            ? '<span class="status-badge status-confirmed">Active</span>'
            : '<span class="status-badge status-pending">Inactive</span>';
        
        html += `
            <tr>
                <td>${member.name}</td>
                <td>${member.position}</td>
                <td>${member.email}</td>
                <td>${member.phone}</td>
                <td><small>${member.services_count || 0} services</small></td>
                <td>${statusBadge}</td>
                <td>
                    <button class="btn-edit" onclick="editStaff(${member.id})">Edit</button>
                    <button class="btn-danger" onclick="deleteStaff(${member.id})">Delete</button>
                </td>
            </tr>
        `;
    });
    
    html += `
            </tbody>
        </table>
    `;
    
    document.getElementById('staffContainer').innerHTML = html;
}

function openAddStaffModal() {
    document.getElementById('staffId').value = '';
    document.getElementById('staffForm').reset();
    document.getElementById('staffModalTitle').textContent = 'Add Staff Member';
    loadServicesForStaff();
    document.getElementById('staffModal').classList.add('active');
}

function closeStaffModal() {
    document.getElementById('staffModal').classList.remove('active');
}

function editStaff(staffId) {
    fetch(`${API_URL}?action=get_staff_details&id=${staffId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const staff = data.data;
                document.getElementById('staffId').value = staff.id;
                document.getElementById('staffName').value = staff.name;
                document.getElementById('staffEmail').value = staff.email;
                document.getElementById('staffPhone').value = staff.phone;
                document.getElementById('staffPosition').value = staff.position;
                document.getElementById('staffStatus').value = staff.status;
                document.getElementById('staffModalTitle').textContent = 'Edit Staff Member';
                
                // Make password optional for editing
                document.getElementById('staffPassword').value = '';
                document.getElementById('staffPassword').required = false;
                document.getElementById('passwordRequired').textContent = '(Optional)';
                document.getElementById('passwordHint').innerHTML = 'Leave empty to keep current password. Enter new password to change it (min 8 characters).';
                
                loadServicesForStaff(staff.services || []);
                document.getElementById('staffModal').classList.add('active');
            }
        })
        .catch(error => console.error('Error loading staff:', error));
}

function openAddStaffModal() {
    document.getElementById('staffId').value = '';
    document.getElementById('staffName').value = '';
    document.getElementById('staffEmail').value = '';
    document.getElementById('staffPhone').value = '';
    document.getElementById('staffPosition').value = '';
    document.getElementById('staffPassword').value = '';
    document.getElementById('staffStatus').value = 'active';
    document.getElementById('staffModalTitle').textContent = 'Add Staff Member';
    
    // Make password required for new staff
    document.getElementById('staffPassword').required = true;
    document.getElementById('passwordRequired').textContent = '*';
    document.getElementById('passwordHint').innerHTML = 'Min 8 characters. Required for new staff. Leave empty to keep current password when editing.';
    
    loadServicesForStaff([]);
    document.getElementById('staffModal').classList.add('active');
}

function closeStaffModal() {
    document.getElementById('staffModal').classList.remove('active');
    document.getElementById('staffForm').reset();
}

function togglePasswordField(fieldId) {
    const field = document.getElementById(fieldId);
    const type = field.getAttribute('type') === 'password' ? 'text' : 'password';
    field.setAttribute('type', type);
}

function deleteStaff(staffId) {
    if (confirm('Are you sure you want to delete this staff member?')) {
        const formData = new FormData();
        formData.append('action', 'delete_staff');
        formData.append('staff_id', staffId);
        
        fetch(API_URL, {method: 'POST', body: formData})
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadStaff();
                }
            })
            .catch(error => console.error('Error deleting staff:', error));
    }
}

function loadServicesForStaff(selectedServices = []) {
    fetch(`${API_URL}?action=get_services`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                let options = '<option value="">Select Services</option>';
                data.data.forEach(service => {
                    const isSelected = selectedServices.some(s => s.id === service.id);
                    options += `<option value="${service.id}" ${isSelected ? 'selected' : ''}>${service.name}</option>`;
                });
                document.getElementById('staffServices').innerHTML = options;
            }
        })
        .catch(error => console.error('Error loading services:', error));
}

document.getElementById('staffForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const staffId = document.getElementById('staffId').value;
    const action = staffId ? 'edit_staff' : 'add_staff';
    const password = document.getElementById('staffPassword').value;
    
    // Validate password for new staff
    if (!staffId && !password) {
        showAlert('staffModalAlert', 'Password is required for new staff members', 'danger');
        return;
    }
    
    // Validate password length if provided
    if (password && password.length < 8) {
        showAlert('staffModalAlert', 'Password must be at least 8 characters long', 'danger');
        return;
    }
    
    const serviceSelect = document.getElementById('staffServices');
    const selectedServices = Array.from(serviceSelect.selectedOptions).map(opt => opt.value);
    
    const formData = new FormData();
    formData.append('action', action);
    if (staffId) formData.append('staff_id', staffId);
    formData.append('name', document.getElementById('staffName').value);
    formData.append('email', document.getElementById('staffEmail').value);
    formData.append('phone', document.getElementById('staffPhone').value);
    formData.append('position', document.getElementById('staffPosition').value);
    formData.append('status', document.getElementById('staffStatus').value);
    if (password) formData.append('password', password);
    formData.append('services', JSON.stringify(selectedServices));
    
    fetch(API_URL, {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('staffModalAlert', 'Staff member saved successfully!', 'success');
                setTimeout(() => {
                    closeStaffModal();
                    loadStaff();
                }, 1500);
            } else {
                showAlert('staffModalAlert', data.message || 'Error saving staff member', 'danger');
            }
        })
        .catch(error => showAlert('staffModalAlert', 'Error saving staff member', 'danger'));
});

// ==================== TASK ASSIGNMENTS ====================

// Load Assignments
function loadAssignments(status) {
    fetch(`${API_URL}?action=get_task_assignments&status=${status}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const assignments = data.data || [];
                const container = document.getElementById('assignmentsContainer');
                
                if (assignments.length === 0) {
                    container.innerHTML = '<p style="text-align: center; color: #64748b; padding: 40px;">No assignments found</p>';
                    return;
                }
                
                let html = '<table><thead><tr><th>Staff</th><th>Task</th><th>Priority</th><th>Due Date</th><th>Status</th><th>Staff Status</th><th>Admin Status</th><th>Actions</th></tr></thead><tbody>';
                assignments.forEach(assignment => {
                    const statusClass = `status-${assignment.status}`;
                    html += `
                        <tr>
                            <td><strong>${assignment.staff_name}</strong></td>
                            <td>${assignment.task_description.substring(0, 50)}...</td>
                            <td><span class="status-badge status-${assignment.priority}">${assignment.priority.toUpperCase()}</span></td>
                            <td>${assignment.due_date}</td>
                            <td><span class="status-badge ${statusClass}">${assignment.status.toUpperCase()}</span></td>
                            <td><span class="status-badge status-${assignment.staff_status}">${assignment.staff_status.toUpperCase()}</span></td>
                            <td><span class="status-badge status-${assignment.admin_status}">${assignment.admin_status.toUpperCase()}</span></td>
                            <td>
                                <button class="btn-action" onclick="viewAssignmentDetails(${assignment.id})" style="background: #3b82f6; color: white; padding: 6px 12px; border-radius: 6px; border: none; cursor: pointer; margin-right: 5px;">View</button>
                                <button class="btn-danger" onclick="deleteAssignment(${assignment.id})" style="background: #ef4444; color: white; padding: 6px 12px; border-radius: 6px; border: none; cursor: pointer;">Delete</button>
                            </td>
                        </tr>
                    `;
                });
                html += '</tbody></table>';
                container.innerHTML = html;
            }
        })
        .catch(error => console.error('Error:', error));
}

// Filter Assignments
function filterAssignments(status) {
    loadAssignments(status);
    
    // Update active button
    if (event && event.target) {
        event.target.parentElement.querySelectorAll('.nav-tab').forEach(btn => btn.classList.remove('active'));
        event.target.classList.add('active');
    }
}

// Load Staff for Assignment
function loadStaffForAssignment() {
    fetch(`${API_URL}?action=get_staff`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const staffList = data.data || [];
                let options = '<option value="">-- Select Staff --</option>';
                staffList.forEach(staff => {
                    options += `<option value="${staff.id}">${staff.name} (${staff.email})</option>`;
                });
                document.getElementById('assignTaskStaff').innerHTML = options;
            }
        })
        .catch(error => console.error('Error:', error));
}

// Open Assign Task Modal
function openAssignTaskModal() {
    document.getElementById('assignTaskTitle').textContent = 'Assign New Task';
    document.getElementById('assignTaskForm').reset();
    document.getElementById('assignTaskAlert').innerHTML = '';
    
    // Set minimum date to today
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('assignTaskDueDate').min = today;
    document.getElementById('assignTaskDueDate').value = today;
    
    loadStaffForAssignment();
    document.getElementById('assignTaskModal').classList.add('active');
}

// Close Assign Task Modal
function closeAssignTaskModal() {
    document.getElementById('assignTaskModal').classList.remove('active');
    document.getElementById('assignTaskForm').reset();
}

// Handle Assign Task Form
document.getElementById('assignTaskForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const staffId = document.getElementById('assignTaskStaff').value;
    const taskDesc = document.getElementById('assignTaskDesc').value;
    const priority = document.getElementById('assignTaskPriority').value;
    const dueDate = document.getElementById('assignTaskDueDate').value;
    
    if (!staffId) {
        showAlert('assignTaskAlert', 'Please select a staff member', 'danger');
        return;
    }
    
    if (!taskDesc) {
        showAlert('assignTaskAlert', 'Please enter task description', 'danger');
        return;
    }
    
    if (!dueDate) {
        showAlert('assignTaskAlert', 'Please select a due date', 'danger');
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'assign_task');
    formData.append('staff_id', staffId);
    formData.append('task_description', taskDesc);
    formData.append('priority', priority);
    formData.append('due_date', dueDate);
    
    fetch(API_URL, { method: 'POST', body: formData })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('assignTaskAlert', 'Task assigned successfully!', 'success');
                setTimeout(() => {
                    closeAssignTaskModal();
                    loadAssignments('all');
                }, 1500);
            } else {
                showAlert('assignTaskAlert', data.message || 'Error assigning task', 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('assignTaskAlert', 'Error assigning task', 'danger');
        });
});

// View Assignment Details
function viewAssignmentDetails(assignmentId) {
    fetch(`${API_URL}?action=get_task_assignments`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const assignment = data.data.find(a => a.id === assignmentId);
                if (assignment) {
                    renderTaskDetailsModal(assignment);
                    document.getElementById('taskDetailsModal').classList.add('active');
                }
            }
        })
        .catch(error => console.error('Error:', error));
}

function renderTaskDetailsModal(assignment) {
    const priorityColors = {
        'low': '#10b981',
        'medium': '#f59e0b',
        'high': '#ef4444'
    };
    
    const statusColors = {
        'pending': '#f59e0b',
        'in_progress': '#3b82f6',
        'completed': '#10b981'
    };
    
    const html = `
        <div style="padding: 20px 0;">
            <!-- Task Info -->
            <div style="background: #f8fafc; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                    <div>
                        <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Staff Member</label>
                        <p style="margin: 8px 0 0 0; color: #0f172a; font-size: 16px; font-weight: 600;">${assignment.staff_name}</p>
                        <p style="margin: 4px 0 0 0; color: #64748b; font-size: 14px;">${assignment.staff_email}</p>
                    </div>
                    <div>
                        <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Priority</label>
                        <p style="margin: 8px 0 0 0;"><span style="background: ${priorityColors[assignment.priority] || '#ccc'}; color: white; padding: 4px 12px; border-radius: 20px; font-weight: 600; font-size: 12px;">${assignment.priority.toUpperCase()}</span></p>
                    </div>
                    <div>
                        <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Due Date</label>
                        <p style="margin: 8px 0 0 0; color: #0f172a; font-size: 16px; font-weight: 600;">${assignment.due_date}</p>
                    </div>
                    <div>
                        <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Days Left</label>
                        <p style="margin: 8px 0 0 0; color: #0f172a; font-size: 16px; font-weight: 600;">${calculateDaysLeft(assignment.due_date)} days</p>
                    </div>
                </div>
            </div>

            <!-- Task Description -->
            <div style="margin-bottom: 20px;">
                <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Task Description</label>
                <div style="background: white; border: 1px solid var(--border-color); padding: 15px; border-radius: 8px; margin-top: 8px; color: #0f172a; line-height: 1.6;">
                    ${assignment.task_description}
                </div>
            </div>

            <!-- Status Update Section -->
            <div style="background: #f0f9ff; border: 1px solid #bfdbfe; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                <h4 style="margin: 0 0 15px 0; color: #0f172a;">Update Status</h4>
                <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 15px;">
                    <div>
                        <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Overall Status</label>
                        <select id="overallStatus" class="form-control" style="margin-top: 8px;">
                            <option value="pending" ${assignment.status === 'pending' ? 'selected' : ''}>Pending</option>
                            <option value="in_progress" ${assignment.status === 'in_progress' ? 'selected' : ''}>In Progress</option>
                            <option value="completed" ${assignment.status === 'completed' ? 'selected' : ''}>Completed</option>
                        </select>
                    </div>
                    <div>
                        <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Staff Status</label>
                        <select id="staffStatus" class="form-control" style="margin-top: 8px;">
                            <option value="pending" ${assignment.staff_status === 'pending' ? 'selected' : ''}>Pending</option>
                            <option value="in_progress" ${assignment.staff_status === 'in_progress' ? 'selected' : ''}>In Progress</option>
                            <option value="completed" ${assignment.staff_status === 'completed' ? 'selected' : ''}>Completed</option>
                        </select>
                    </div>
                    <div>
                        <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Admin Status</label>
                        <select id="adminStatus" class="form-control" style="margin-top: 8px;">
                            <option value="pending" ${assignment.admin_status === 'pending' ? 'selected' : ''}>Pending</option>
                            <option value="in_progress" ${assignment.admin_status === 'in_progress' ? 'selected' : ''}>In Progress</option>
                            <option value="completed" ${assignment.admin_status === 'completed' ? 'selected' : ''}>Completed</option>
                        </select>
                    </div>
                </div>
                <button type="button" onclick="updateTaskStatus(${assignment.id})" style="background: var(--primary-color); color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; font-weight: 600; margin-top: 15px; width: 100%;">
                    <i class="fa-solid fa-save"></i> Update Status
                </button>
            </div>

            <!-- Staff Notes -->
            <div>
                <label style="color: #64748b; font-size: 12px; font-weight: 600; text-transform: uppercase;">Staff Notes</label>
                <div style="background: white; border: 1px solid var(--border-color); padding: 15px; border-radius: 8px; margin-top: 8px; color: #0f172a; min-height: 60px;">
                    ${assignment.staff_notes || '<em style="color: #94a3b8;">No notes from staff yet</em>'}
                </div>
            </div>
        </div>
    `;
    
    document.getElementById('taskDetailsContainer').innerHTML = html;
}

function calculateDaysLeft(dueDate) {
    const due = new Date(dueDate);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const diff = Math.ceil((due - today) / (1000 * 60 * 60 * 24));
    return diff > 0 ? diff : 0;
}

function updateTaskStatus(assignmentId) {
    const overallStatus = document.getElementById('overallStatus').value;
    const staffStatus = document.getElementById('staffStatus').value;
    const adminStatus = document.getElementById('adminStatus').value;
    
    const formData = new FormData();
    formData.append('action', 'update_task_status');
    formData.append('assignment_id', assignmentId);
    formData.append('status', overallStatus);
    formData.append('staff_status', staffStatus);
    formData.append('admin_status', adminStatus);
    
    fetch(API_URL, { method: 'POST', body: formData })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('taskDetailsAlert', 'Task status updated successfully!', 'success');
                setTimeout(() => {
                    closeTaskDetailsModal();
                    loadAssignments('all');
                }, 1500);
            } else {
                showAlert('taskDetailsAlert', data.message || 'Error updating status', 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('taskDetailsAlert', 'Error updating task status', 'danger');
        });
}

function closeTaskDetailsModal() {
    document.getElementById('taskDetailsModal').classList.remove('active');
    document.getElementById('taskDetailsAlert').innerHTML = '';
}

// Delete Assignment
function deleteAssignment(assignmentId) {
    if (!confirm('Are you sure you want to delete this task assignment?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'delete_task_assignment');
    formData.append('assignment_id', assignmentId);
    
    fetch(API_URL, { method: 'POST', body: formData })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('assignTaskAlert', 'Task assignment deleted successfully!', 'success');
                loadAssignments('all');
            } else {
                showAlert('assignTaskAlert', data.message || 'Error deleting task assignment', 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('assignTaskAlert', 'Error deleting task assignment', 'danger');
        });
}
