<?php
session_start();
if (!isset($_SESSION['gym_id'])) {
    header("Location: login.php");
    exit();
}

require_once 'config/database.php';
$db = (new Database())->getConnection();
$gym_id = $_SESSION['gym_id'];

// Current gym کا data fetch کریں sidebar کے لیے
$gym_stmt = $db->prepare("SELECT name, owner_name FROM gyms WHERE id = ?");
$gym_stmt->execute([$gym_id]);
$current_gym = $gym_stmt->fetch(PDO::FETCH_ASSOC);

// Check if it's an AJAX request
$is_ajax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

if ($_POST && isset($_POST['add_staff'])) {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = $_POST['role'];
    $phone = trim($_POST['phone']);
    $salary = $_POST['salary'];
    $trainer_fee = $_POST['trainer_fee'] ?? null;
    $join_date = $_POST['join_date'];
    $status = 'active';

    // Check if email exists - ONLY IN CURRENT GYM
    $check_query = "SELECT id FROM staff WHERE email = ? AND gym_id = ?";
    $stmt = $db->prepare($check_query);
    $stmt->execute([$email, $gym_id]);
    
    if ($stmt->rowCount() > 0) {
        // ALWAYS return JSON for AJAX requests
        echo json_encode(['success' => false, 'message' => 'Email already exists!']);
        exit();
    } else {
        $query = "INSERT INTO staff (gym_id, name, email, password, role, phone, salary, trainer_fee, join_date, status) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$gym_id, $name, $email, $password, $role, $phone, $salary, $trainer_fee, $join_date, $status])) {
            // ALWAYS return JSON for AJAX requests
            echo json_encode(['success' => true, 'message' => 'Staff added successfully!']);
            exit();
        } else {
            // ALWAYS return JSON for AJAX requests
            echo json_encode(['success' => false, 'message' => 'Failed to add staff!']);
            exit();
        }
    }
}

// Update staff
if ($_POST && isset($_POST['update_staff'])) {
    $staff_id = $_POST['staff_id'];
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $role = $_POST['role'];
    $phone = trim($_POST['phone']);
    $salary = $_POST['salary'];
    $trainer_fee = $_POST['trainer_fee'] ?? null;
    $join_date = $_POST['join_date'];
    $status = $_POST['status'];

    // Check if email exists (excluding current staff) - ONLY IN CURRENT GYM
    $check_query = "SELECT id FROM staff WHERE email = ? AND id != ? AND gym_id = ?";
    $stmt = $db->prepare($check_query);
    $stmt->execute([$email, $staff_id, $gym_id]);
    
    if ($stmt->rowCount() > 0) {
        // ALWAYS return JSON for AJAX requests
        echo json_encode(['success' => false, 'message' => 'Email already exists!']);
        exit();
    } else {
        $query = "UPDATE staff SET name=?, email=?, role=?, phone=?, salary=?, trainer_fee=?, join_date=?, status=? WHERE id=? AND gym_id=?";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$name, $email, $role, $phone, $salary, $trainer_fee, $join_date, $status, $staff_id, $gym_id])) {
            // ALWAYS return JSON for AJAX requests
            echo json_encode(['success' => true, 'message' => 'Staff updated successfully!']);
            exit();
        } else {
            // ALWAYS return JSON for AJAX requests
            echo json_encode(['success' => false, 'message' => 'Failed to update staff!']);
            exit();
        }
    }
}

// Delete staff - ONLY FROM CURRENT GYM (This should NOT be AJAX)
if (isset($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    $query = "DELETE FROM staff WHERE id = ? AND gym_id = ?";
    $stmt = $db->prepare($query);
    if ($stmt->execute([$delete_id, $gym_id])) {
        $_SESSION['success'] = "Staff member deleted successfully!";
    } else {
        $_SESSION['error'] = "Failed to delete staff member!";
    }
    header("Location: basic-staff.php");
    exit();
}

// Get all staff members - ONLY FROM CURRENT GYM
$query = "SELECT * FROM staff WHERE gym_id = ? ORDER BY created_at DESC";
$stmt = $db->prepare($query);
$stmt->execute([$gym_id]);
$staff_members = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>


<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<?php include 'includes/navbar.php'; ?>

<!-- Include SweetAlert -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

<div class="main-panel">
    <div class="content-wrapper">
        <div class="page-header">
            <h3 class="page-title">Staff Management</h3>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Staff Management</li>
                </ol>
            </nav>
        </div>

        <!-- Success/Error Messages (for non-AJAX requests) -->
        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-lg-12 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h4 class="card-title">Staff Members</h4>
                            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addStaffModal">
                                <i class="mdi mdi-plus-circle"></i> Add New Staff
                            </button>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Profile</th>
                                        <th>Email</th>
                                        <th>Role</th>
                                        <th>Phone</th>
                                        <th>Salary</th>
                                        <th>Join Date</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($staff_members)): ?>
                                        <tr>
                                            <td colspan="8" class="text-center text-muted py-4">
                                                <i class="mdi mdi-account-off-outline display-4 d-block mb-2"></i>
                                                No staff members found. <a href="#" data-bs-toggle="modal" data-bs-target="#addStaffModal">Add the first staff member</a>.
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($staff_members as $staff): ?>
                                        <tr>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <i class="mdi mdi-account" style="font-size:30px; color:#7a7a7a;"></i>
                                                    <div class="ms-3">
                                                        <div class="fw-semibold"><?php echo htmlspecialchars($staff['name']); ?></div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td><?php echo htmlspecialchars($staff['email']); ?></td>
                                            <td>
                                                <label class="badge badge-<?php 
                                                    echo $staff['role'] == 'admin' ? 'danger' : 
                                                        ($staff['role'] == 'gym_manager' ? 'warning' : 
                                                        ($staff['role'] == 'trainer' ? 'info' : 
                                                        ($staff['role'] == 'receptionist' ? 'success' : 
                                                        ($staff['role'] == 'cleaner' ? 'secondary' : 'primary')))); 
                                                ?>">
                                                    <?php echo ucfirst(str_replace('_', ' ', $staff['role'])); ?>
                                                </label>
                                            </td>
                                            <td><?php echo $staff['phone'] ? htmlspecialchars($staff['phone']) : 'N/A'; ?></td>
                                            <td>
                                                <?php if ($staff['salary']): ?>
                                                    Rs. <?php echo number_format($staff['salary']); ?>
                                                <?php else: ?>
                                                    N/A
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo date('M d, Y', strtotime($staff['join_date'])); ?></td>
                                            <td>
                                                <label class="badge badge-<?php echo $staff['status'] == 'active' ? 'success' : 'danger'; ?>">
                                                    <?php echo ucfirst($staff['status']); ?>
                                                </label>
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-primary edit-staff-btn" 
                                                        data-id="<?php echo $staff['id']; ?>"
                                                        data-name="<?php echo htmlspecialchars($staff['name']); ?>"
                                                        data-email="<?php echo htmlspecialchars($staff['email']); ?>"
                                                        data-role="<?php echo $staff['role']; ?>"
                                                        data-phone="<?php echo $staff['phone']; ?>"
                                                        data-salary="<?php echo $staff['salary']; ?>"
                                                        data-trainer-fee="<?php echo $staff['trainer_fee']; ?>"
                                                        data-join-date="<?php echo $staff['join_date']; ?>"
                                                        data-status="<?php echo $staff['status']; ?>">
                                                    <i class="mdi mdi-pencil"></i>
                                                </button>
                                                <button class="btn btn-sm btn-danger delete-staff-btn" 
                                                        data-id="<?php echo $staff['id']; ?>"
                                                        data-name="<?php echo htmlspecialchars($staff['name']); ?>">
                                                    <i class="mdi mdi-delete"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Staff Modal -->
    <div class="modal fade" id="addStaffModal" tabindex="-1" aria-labelledby="addStaffModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addStaffModalLabel">Add New Staff Member</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="addStaffForm" method="POST">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="name" class="form-label">Full Name *</label>
                                    <input type="text" class="form-control" id="name" name="name" required 
                                           placeholder="Enter full name">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="email" class="form-label">Email Address *</label>
                                    <input type="email" class="form-control" id="email" name="email" required 
                                           placeholder="Enter email address">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="password" class="form-label">Password *</label>
                                    <input type="password" class="form-control" id="password" name="password" required 
                                           placeholder="Enter password">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="role" class="form-label">Role *</label>
                                    <select class="form-control" id="role" name="role" required>
                                        <option value="">Select Role</option>
                                        <option value="admin">Admin</option>
                                        <option value="gym_manager">Gym Manager</option>
                                        <option value="trainer">Trainer</option>
                                        <option value="receptionist">Receptionist</option>
                                        <option value="cleaner">Cleaner</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="phone" class="form-label">Phone Number</label>
                                    <input type="text" class="form-control" id="phone" name="phone" 
                                           placeholder="0300-1234567">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="salary" class="form-label">Salary (PKR)</label>
                                    <input type="number" class="form-control" id="salary" name="salary" 
                                           placeholder="50000" step="0.01">
                                </div>
                            </div>
                        </div>

                        <!-- Trainer Fee Field (Initially Hidden) -->
                        <div class="row" id="trainer_fee_section" style="display: none;">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="trainer_fee" class="form-label">Trainer Fee (PKR)</label>
                                    <input type="number" class="form-control" id="trainer_fee" name="trainer_fee" 
                                           placeholder="2000 per session" step="0.01">
                                    <small class="text-muted">Fee per training session</small>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="join_date" class="form-label">Join Date</label>
                            <input type="date" class="form-control" id="join_date" name="join_date" 
                                   value="<?php echo date('Y-m-d'); ?>">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Staff</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Staff Modal -->
    <div class="modal fade" id="editStaffModal" tabindex="-1" aria-labelledby="editStaffModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editStaffModalLabel">Edit Staff Member</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="editStaffForm" method="POST">
                    <div class="modal-body">
                        <input type="hidden" id="edit_staff_id" name="staff_id">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_name" class="form-label">Full Name *</label>
                                    <input type="text" class="form-control" id="edit_name" name="name" required 
                                           placeholder="Enter full name">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_email" class="form-label">Email Address *</label>
                                    <input type="email" class="form-control" id="edit_email" name="email" required 
                                           placeholder="Enter email address">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_role" class="form-label">Role *</label>
                                    <select class="form-control" id="edit_role" name="role" required>
                                        <option value="">Select Role</option>
                                        <option value="admin">Admin</option>
                                        <option value="gym_manager">Gym Manager</option>
                                        <option value="trainer">Trainer</option>
                                        <option value="receptionist">Receptionist</option>
                                        <option value="cleaner">Cleaner</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_phone" class="form-label">Phone Number</label>
                                    <input type="text" class="form-control" id="edit_phone" name="phone" 
                                           placeholder="0300-1234567">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_salary" class="form-label">Salary (PKR)</label>
                                    <input type="number" class="form-control" id="edit_salary" name="salary" 
                                           placeholder="50000" step="0.01">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_join_date" class="form-label">Join Date</label>
                                    <input type="date" class="form-control" id="edit_join_date" name="join_date">
                                </div>
                            </div>
                        </div>

                        <!-- Trainer Fee Field for Edit -->
                        <div class="row" id="edit_trainer_fee_section" style="display: none;">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_trainer_fee" class="form-label">Trainer Fee (PKR)</label>
                                    <input type="number" class="form-control" id="edit_trainer_fee" name="trainer_fee" 
                                           placeholder="2000 per session" step="0.01">
                                    <small class="text-muted">Fee per training session</small>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="edit_status" class="form-label">Status</label>
                            <select class="form-control" id="edit_status" name="status">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Staff</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'includes/footer.php'; ?>
</div>

<script>
// SweetAlert configuration
const Toast = Swal.mixin({
    toast: true,
    position: 'top-end',
    showConfirmButton: false,
    timer: 3000,
    timerProgressBar: true,
    didOpen: (toast) => {
        toast.addEventListener('mouseenter', Swal.stopTimer)
        toast.addEventListener('mouseleave', Swal.resumeTimer)
    }
});

// Role change handler for Add Modal
document.getElementById('role').addEventListener('change', function() {
    const trainerFeeSection = document.getElementById('trainer_fee_section');
    if (this.value === 'trainer') {
        trainerFeeSection.style.display = 'block';
        document.getElementById('trainer_fee').required = true;
    } else {
        trainerFeeSection.style.display = 'none';
        document.getElementById('trainer_fee').required = false;
        document.getElementById('trainer_fee').value = '';
    }
});

// Role change handler for Edit Modal
document.getElementById('edit_role').addEventListener('change', function() {
    const trainerFeeSection = document.getElementById('edit_trainer_fee_section');
    if (this.value === 'trainer') {
        trainerFeeSection.style.display = 'block';
        document.getElementById('edit_trainer_fee').required = true;
    } else {
        trainerFeeSection.style.display = 'none';
        document.getElementById('edit_trainer_fee').required = false;
        document.getElementById('edit_trainer_fee').value = '';
    }
});

// Add Staff Form Submission
document.getElementById('addStaffForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    // Show loading state
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="mdi mdi-loading mdi-spin"></i> Adding...';
    submitBtn.disabled = true;
    
    const formData = new FormData(this);
    formData.append('add_staff', 'true');
    
    fetch('basic-staff.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            Toast.fire({
                icon: 'success',
                title: data.message
            });
            // Hide modal and reset form
            const modal = bootstrap.Modal.getInstance(document.getElementById('addStaffModal'));
            modal.hide();
            document.getElementById('addStaffForm').reset();
            document.getElementById('trainer_fee_section').style.display = 'none';
            // Reload page after delay
            setTimeout(() => location.reload(), 1500);
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: data.message
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Network Error!',
            text: 'Failed to connect to server. Please try again.'
        });
    })
    .finally(() => {
        // Reset button state
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});

// Edit Staff Modal Open
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('edit-staff-btn') || e.target.closest('.edit-staff-btn')) {
        const button = e.target.classList.contains('edit-staff-btn') ? e.target : e.target.closest('.edit-staff-btn');
        const staffId = button.getAttribute('data-id');
        const staffName = button.getAttribute('data-name');
        const staffEmail = button.getAttribute('data-email');
        const staffRole = button.getAttribute('data-role');
        const staffPhone = button.getAttribute('data-phone');
        const staffSalary = button.getAttribute('data-salary');
        const staffTrainerFee = button.getAttribute('data-trainer-fee');
        const staffJoinDate = button.getAttribute('data-join-date');
        const staffStatus = button.getAttribute('data-status');
        
        // Populate edit form
        document.getElementById('edit_staff_id').value = staffId;
        document.getElementById('edit_name').value = staffName;
        document.getElementById('edit_email').value = staffEmail;
        document.getElementById('edit_role').value = staffRole;
        document.getElementById('edit_phone').value = staffPhone || '';
        document.getElementById('edit_salary').value = staffSalary || '';
        document.getElementById('edit_trainer_fee').value = staffTrainerFee || '';
        document.getElementById('edit_join_date').value = staffJoinDate;
        document.getElementById('edit_status').value = staffStatus;
        
        // Show/hide trainer fee section based on role
        const trainerFeeSection = document.getElementById('edit_trainer_fee_section');
        if (staffRole === 'trainer') {
            trainerFeeSection.style.display = 'block';
        } else {
            trainerFeeSection.style.display = 'none';
        }
        
        // Show edit modal
        const editModal = new bootstrap.Modal(document.getElementById('editStaffModal'));
        editModal.show();
    }
});

// Edit Staff Form Submission
document.getElementById('editStaffForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    // Show loading state
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="mdi mdi-loading mdi-spin"></i> Updating...';
    submitBtn.disabled = true;
    
    const formData = new FormData(this);
    formData.append('update_staff', 'true');
    
    fetch('basic-staff.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            Toast.fire({
                icon: 'success',
                title: data.message
            });
            // Hide modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('editStaffModal'));
            modal.hide();
            // Reload page after delay
            setTimeout(() => location.reload(), 1500);
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: data.message
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Network Error!',
            text: 'Failed to connect to server. Please try again.'
        });
    })
    .finally(() => {
        // Reset button state
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});

// Delete Staff with SweetAlert
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('delete-staff-btn') || e.target.closest('.delete-staff-btn')) {
        const button = e.target.classList.contains('delete-staff-btn') ? e.target : e.target.closest('.delete-staff-btn');
        const staffId = button.getAttribute('data-id');
        const staffName = button.getAttribute('data-name');
        
        Swal.fire({
            title: 'Delete Staff Member?',
            html: `Are you sure you want to delete <strong>${staffName}</strong>?<br>This action cannot be undone!`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ff0852',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = `basic-staff.php?delete_id=${staffId}`;
            }
        });
    }
});

// Auto-close alerts after 5 seconds
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(alert => {
        const bsAlert = new bootstrap.Alert(alert);
        bsAlert.close();
    });
}, 5000);

// Reset form when modal is closed
document.getElementById('addStaffModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('addStaffForm').reset();
    document.getElementById('trainer_fee_section').style.display = 'none';
});

// Debugging: Check if forms are working
console.log('Staff management script loaded successfully');

// Test if fetch is working
fetch('basic-staff.php')
    .then(response => console.log('Basic connection test:', response.status))
    .catch(error => console.error('Connection test failed:', error));
</script>