<?php
$pageTitle = 'Staff Management';
require_once __DIR__ . '/includes/header.php';

if (!$isAdmin) {
    echo '<div class="alert alert-danger">Access denied. Only restaurant administrators can manage staff.</div>';
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

$staffRoles = $db->query("SELECT id, name, description FROM roles WHERE id IN (2,3,4,5,6) ORDER BY id ASC")->fetchAll();

$staff = $db->query("
    SELECT u.*, r.name as role_name
    FROM users u
    INNER JOIN roles r ON u.role_id = r.id
    WHERE u.restaurant_id = ? AND r.id IN (2,3,4,5,6)
    ORDER BY u.created_at DESC
", [$restaurantId])->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0">Staff Management</h6>
        <small class="text-muted">Manage your restaurant staff</small>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staffModal" onclick="resetStaffForm()">
        <i class="fas fa-plus me-1"></i>Add Staff
    </button>
</div>

<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover datatable mb-0">
                <thead class="table-light">
                    <tr><th>Name</th><th>Email</th><th>Phone</th><th>Role</th><th>Status</th><th>Last Login</th><th>Actions</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($staff as $s): ?>
                        <tr>
                            <td><strong><?php echo sanitize($s['name']); ?></strong></td>
                            <td><?php echo sanitize($s['email']); ?></td>
                            <td><?php echo sanitize($s['phone'] ?? '-'); ?></td>
                            <td><span class="badge bg-info"><?php echo sanitize($s['role_name']); ?></span></td>
                            <td>
                                <?php if ($s['id'] == $auth->userId()): ?>
                                    <span class="badge bg-success">You</span>
                                <?php else: ?>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input toggle-staff-status" type="checkbox" data-id="<?php echo $s['id']; ?>" <?php echo $s['status'] === 'active' ? 'checked' : ''; ?>>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td><small><?php echo $s['last_login'] ? timeAgo($s['last_login']) : 'Never'; ?></small></td>
                            <td>
                                <?php if ($s['id'] != $auth->userId()): ?>
                                <button class="btn btn-sm btn-outline-primary me-1" onclick="editStaff(<?php echo $s['id']; ?>)"><i class="fas fa-edit"></i></button>
                                <button class="btn-ajax-delete btn btn-sm btn-outline-danger" data-url="<?php echo $baseUrl; ?>/restaurant-admin/staff_save.php" data-name="<?php echo sanitize($s['name']); ?>" data-id="<?php echo $s['id']; ?>"><i class="fas fa-trash"></i></button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="staffModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="staffForm">
                <?php echo $csrf->field(); ?>
                <input type="hidden" name="action" id="stAction" value="add">
                <input type="hidden" name="staff_id" id="stId" value="">
                <div class="modal-header">
                    <h5 class="modal-title" id="stModalTitle">Add Staff</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Full Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" id="stName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email <span class="text-danger">*</span></label>
                        <input type="email" class="form-control" name="email" id="stEmail" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Phone</label>
                        <input type="text" class="form-control" name="phone" id="stPhone">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Role <span class="text-danger">*</span></label>
                        <select class="form-select" name="role_id" id="stRole" required>
                            <option value="">Select Role</option>
                            <?php foreach ($staffRoles as $sr): ?>
                            <option value="<?php echo $sr['id']; ?>"><?php echo sanitize(ucfirst(str_replace('_', ' ', $sr['name']))); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3" id="passwordGroup">
                        <label class="form-label">Password <span class="text-danger" id="passwordRequired">*</span></label>
                        <input type="password" class="form-control" name="password" id="stPassword">
                        <small class="text-muted">Min 6 characters</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="status" id="stStatus">
                            <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"><i class="fas fa-save me-1"></i>Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetStaffForm() {
    document.getElementById('stAction').value = 'add';
    document.getElementById('stId').value = '';
    document.getElementById('stName').value = '';
    document.getElementById('stEmail').value = '';
    document.getElementById('stPhone').value = '';
    document.getElementById('stRole').value = '';
    document.getElementById('stPassword').value = '';
    document.getElementById('stStatus').value = 'active';
    document.getElementById('stModalTitle').textContent = 'Add Staff';
    document.getElementById('passwordRequired').style.display = 'inline';
}

function editStaff(id) {
    fetch(BASE_URL + '/restaurant-admin/staff_save.php?action=get&id=' + id, {headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){
            var s = data.staff;
            document.getElementById('stAction').value = 'edit';
            document.getElementById('stId').value = s.id;
            document.getElementById('stName').value = s.name;
            document.getElementById('stEmail').value = s.email;
            document.getElementById('stPhone').value = s.phone || '';
            document.getElementById('stRole').value = s.role_id;
            document.getElementById('stPassword').value = '';
            document.getElementById('stStatus').value = s.status;
            document.getElementById('stModalTitle').textContent = 'Edit Staff';
            document.getElementById('passwordRequired').style.display = 'none';
            new bootstrap.Modal(document.getElementById('staffModal')).show();
        }
    });
}

document.getElementById('staffForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    formData.append('csrf_token', CSRF_TOKEN);
    fetch(BASE_URL + '/restaurant-admin/staff_save.php', {method:'POST',body:formData,headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){showAlert('success',data.message);setTimeout(function(){location.reload();},1000);}
        else{showAlert('danger',data.message);}
    });
});

document.querySelectorAll('.toggle-staff-status').forEach(function(toggle) {
    toggle.addEventListener('change', function(e) {
        e.preventDefault();
        ajaxPost(BASE_URL + '/restaurant-admin/staff_save.php', 'action=toggle_status&id=' + this.dataset.id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
            if (data.success) showAlert('success', data.message);
            else showAlert('danger', data.message);
        });
    });
});

document.querySelectorAll('.btn-ajax-delete[data-id]').forEach(function(btn) {
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        if (confirm('Delete staff member "' + (this.dataset.name || '') + '"?')) {
            ajaxPost(BASE_URL + '/restaurant-admin/staff_save.php', 'action=delete&id=' + this.dataset.id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
                if (data.success) { showAlert('success', data.message); setTimeout(function(){location.reload();},1000); }
                else showAlert('danger', data.message);
            });
        }
    });
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
