<?php
// app/Controllers/StaffController.php

class StaffController {
    private function requireAdmin() {
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
            header('Location: /login'); exit;
        }
    }

    public function index() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $pageTitle = 'Staff Management';

        // Load active cashiers
        $cashStmt = $db->prepare('SELECT id, name FROM users WHERE restaurant_id = ? AND role = "cashier" AND status = "active" ORDER BY name ASC');
        $cashStmt->execute([$rest_id]);
        $cashiers = $cashStmt->fetchAll();

        $stmt = $db->prepare('
            SELECT u.*, c.name as cashier_name 
            FROM users u 
            LEFT JOIN users c ON u.cashier_id = c.id 
            WHERE u.restaurant_id = ? AND u.role IN ("cashier","waiter","kitchen","inventory","hr_manager") 
            ORDER BY u.created_at DESC
        ');
        $stmt->execute([$rest_id]);
        $staff = $stmt->fetchAll();

        $cashierCheck = FeatureGate::canAddCashier($rest_id);
        $waiterCheck = FeatureGate::canAddWaiter($rest_id);
        $gate = FeatureGate::check($rest_id);

        ob_start(); ?>
<div class="space-y-6">

    <?php if (!empty($_GET['error'])): ?>
    <div class="rounded-xl px-4 py-3 text-sm font-medium text-red-300 flex items-center gap-2" style="background:rgba(239,68,68,0.12); border:1px solid rgba(239,68,68,0.25)">
        <i class="fas fa-exclamation-circle"></i>
        <?php echo htmlspecialchars($_GET['error']); ?>
    </div>
    <?php endif; ?>

    <?php if (!empty($_GET['msg'])): ?>
    <div class="rounded-xl px-4 py-3 text-sm font-medium text-emerald-300 flex items-center gap-2" style="background:rgba(16,185,129,0.12); border:1px solid rgba(16,185,129,0.25)">
        <i class="fas fa-check-circle"></i>
        <?php echo htmlspecialchars($_GET['msg']); ?>
    </div>
    <?php endif; ?>

    <!-- Quota Info Banner -->
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div class="rounded-2xl p-4 flex items-center justify-between transition duration-300 hover:scale-[1.01]" style="background:rgba(59,130,246,0.06); border:1px solid rgba(59,130,246,0.15); backdrop-filter:blur(10px)">
            <div class="flex items-center gap-3.5">
                <div class="w-11 h-11 rounded-xl flex items-center justify-center bg-blue-500/10 text-blue-400 border border-blue-500/10">
                    <i class="fas fa-cash-register text-base"></i>
                </div>
                <div>
                    <span class="block text-[11px] text-slate-400 font-medium uppercase tracking-wider">Cashier Limit</span>
                    <span class="text-base font-semibold text-white"><?php echo $cashierCheck['current']; ?> <span class="text-slate-500 font-normal text-xs">/</span> <?php echo $cashierCheck['max'] ?? '∞'; ?></span>
                </div>
            </div>
            <div class="text-xs font-semibold px-2.5 py-1 rounded-lg bg-blue-500/15 text-blue-300 border border-blue-500/10">
                <?php echo isset($cashierCheck['max']) ? round(($cashierCheck['current'] / $cashierCheck['max']) * 100) . '%' : 'Active'; ?>
            </div>
        </div>
        <div class="rounded-2xl p-4 flex items-center justify-between transition duration-300 hover:scale-[1.01]" style="background:rgba(245,158,11,0.06); border:1px solid rgba(245,158,11,0.15); backdrop-filter:blur(10px)">
            <div class="flex items-center gap-3.5">
                <div class="w-11 h-11 rounded-xl flex items-center justify-center bg-amber-500/10 text-amber-400 border border-amber-500/10">
                    <i class="fas fa-users-cog text-base"></i>
                </div>
                <div>
                    <span class="block text-[11px] text-slate-400 font-medium uppercase tracking-wider">Waiter Limit</span>
                    <span class="text-base font-semibold text-white"><?php echo $waiterCheck['current']; ?> <span class="text-slate-500 font-normal text-xs">/</span> <?php echo $waiterCheck['max'] ?? '∞'; ?></span>
                </div>
            </div>
            <div class="text-xs font-semibold px-2.5 py-1 rounded-lg bg-amber-500/15 text-amber-300 border border-amber-500/10">
                <?php echo isset($waiterCheck['max']) ? round(($waiterCheck['current'] / $waiterCheck['max']) * 100) . '%' : 'Active'; ?>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6" x-data="staffListApp()" x-init="init()">
        <!-- Add Staff Form -->
        <div class="rounded-2xl p-6 h-fit" style="background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06); backdrop-filter:blur(10px)">
            <h3 class="text-base font-bold text-white mb-5 flex items-center gap-2">
                <i class="fas fa-user-plus text-emerald-400"></i> Add Staff Member
            </h3>
            <form action="/admin/staff/store" method="POST" class="space-y-4">
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Name</label>
                    <input type="text" name="name" required class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none transition focus:border-emerald-500/40 focus:ring-2 focus:ring-emerald-500/10" style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Email Address</label>
                    <input type="email" name="email" required class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none transition focus:border-emerald-500/40 focus:ring-2 focus:ring-emerald-500/10" style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Password</label>
                    <input type="password" name="password" required class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none transition focus:border-emerald-500/40 focus:ring-2 focus:ring-emerald-500/10" style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Role</label>
                    <select name="role" id="roleSelect" onchange="toggleCashierDropdown(this.value)" class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none transition focus:border-emerald-500/40 focus:ring-2 focus:ring-emerald-500/10" style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.08)">
                        <option value="cashier">Cashier</option>
                        <option value="waiter">Waiter</option>
                        <?php if (FeatureGate::hasKitchen($rest_id)): ?>
                        <option value="kitchen">Kitchen</option>
                        <?php endif; ?>
                        <option value="inventory">Inventory Manager</option>
                        <option value="hr_manager">HR Manager</option>
                    </select>
                </div>
                <div id="cashierWrapper" style="display:none">
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Assign to Cashier (Branch)</label>
                    <select name="cashier_id" class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none transition focus:border-emerald-500/40 focus:ring-2 focus:ring-emerald-500/10" style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.08)">
                        <option value="">General Pool / Unassigned</option>
                        <?php foreach($cashiers as $c): ?>
                        <option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="w-full py-3 rounded-xl font-bold text-white transition text-sm flex items-center justify-center gap-2 hover:opacity-95 shadow-lg shadow-emerald-500/10" style="background:linear-gradient(135deg,#10b981,#059669)">
                    <i class="fas fa-plus-circle"></i> Add Staff Member
                </button>
            </form>
        </div>

        <!-- Staff List (with Search & Filters) -->
        <div class="lg:col-span-2 space-y-4">
            <div class="flex flex-col sm:flex-row gap-4 items-center justify-between p-4 rounded-2xl border border-white/5" style="background:rgba(255,255,255,0.02); backdrop-filter:blur(8px)">
                <div class="relative w-full sm:w-64">
                    <i class="fas fa-search absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500 text-xs"></i>
                    <input type="text" x-model="search" placeholder="Search staff..." 
                           class="w-full pl-9 pr-4 py-2 text-xs text-white rounded-xl outline-none transition focus:border-emerald-500/40 focus:ring-2 focus:ring-emerald-500/10"
                           style="background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.08)">
                </div>
                <div class="w-full sm:w-auto">
                    <select x-model="roleFilter" class="w-full sm:w-auto text-xs px-4 py-2 rounded-xl text-white outline-none bg-[#0d2137] transition focus:border-emerald-500/40 focus:ring-2 focus:ring-emerald-500/10"
                            style="border:1px solid rgba(255,255,255,0.08)">
                        <option value="">All Roles</option>
                        <option value="cashier">Cashier</option>
                        <option value="waiter">Waiter</option>
                        <option value="kitchen">Kitchen</option>
                        <option value="inventory">Inventory Manager</option>
                        <option value="hr_manager">HR Manager</option>
                    </select>
                </div>
            </div>

            <div class="rounded-2xl border border-white/5 bg-white/[0.02] overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="border-b border-white/5 bg-white/[0.01]">
                                <th class="text-left px-6 py-4 text-slate-400 font-semibold text-xs tracking-wider uppercase">Name</th>
                                <th class="text-left px-6 py-4 text-slate-400 font-semibold text-xs tracking-wider uppercase">Email</th>
                                <th class="text-left px-6 py-4 text-slate-400 font-semibold text-xs tracking-wider uppercase">Role</th>
                                <th class="text-left px-6 py-4 text-slate-400 font-semibold text-xs tracking-wider uppercase">Status</th>
                                <th class="text-right px-6 py-4 text-slate-400 font-semibold text-xs tracking-wider uppercase">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(empty($staff)): ?>
                            <tr><td colspan="5" class="px-6 py-10 text-center text-slate-500">No staff added yet.</td></tr>
                            <?php endif; ?>
                            <?php foreach($staff as $m): ?>
                            <tr class="border-b border-white/5 hover:bg-white/5 transition staff-row group"
                                data-name="<?php echo strtolower(htmlspecialchars($m['name'])); ?>"
                                data-role="<?php echo htmlspecialchars($m['role']); ?>">
                                <td class="px-6 py-4 font-medium text-white">
                                    <div class="font-semibold text-slate-200"><?php echo htmlspecialchars($m['name']); ?></div>
                                    <?php if ($m['role'] !== 'cashier' && !empty($m['cashier_name'])): ?>
                                    <span class="text-[10px] text-slate-400 font-medium inline-flex items-center gap-1.5 mt-1 px-1.5 py-0.5 rounded bg-blue-500/10 border border-blue-500/10">
                                        <i class="fas fa-store text-[9px] text-blue-400"></i>
                                        Branch: <?php echo htmlspecialchars($m['cashier_name']); ?>
                                    </span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-slate-300">
                                    <div class="flex items-center gap-2">
                                        <div class="truncate max-w-[130px] md:max-w-[180px] font-mono text-xs text-slate-400" title="<?php echo htmlspecialchars($m['email']); ?>">
                                            <?php echo htmlspecialchars($m['email']); ?>
                                        </div>
                                        <button onclick="navigator.clipboard.writeText('<?php echo addslashes($m['email']); ?>'); alert('Email copied: <?php echo addslashes($m['email']); ?>');" 
                                                class="opacity-0 group-hover:opacity-100 focus:opacity-100 text-[10px] text-slate-500 hover:text-emerald-400 transition cursor-pointer p-0.5" 
                                                title="Copy Email">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <?php 
                                    if ($m['role'] === 'cashier') {
                                        $rc = 'rgba(59,130,246,0.15)'; $cc = '#93c5fd';
                                    } elseif ($m['role'] === 'waiter') {
                                        $rc = 'rgba(245,158,11,0.15)'; $cc = '#fcd34d';
                                    } elseif ($m['role'] === 'inventory') {
                                        $rc = 'rgba(16,185,129,0.15)'; $cc = '#6ee7b7';
                                    } elseif ($m['role'] === 'hr_manager') {
                                        $rc = 'rgba(99,102,241,0.15)'; $cc = '#a5b4fc';
                                    } else {
                                        $rc = 'rgba(168,85,247,0.15)'; $cc = '#d8b4fe';
                                    }
                                    ?>
                                    <span class="px-2.5 py-1 rounded-full text-xs font-semibold border border-white/5" style="background:<?php echo $rc; ?>; color:<?php echo $cc; ?>"><?php echo ucfirst($m['role']); ?></span>
                                </td>
                                <td class="px-6 py-4">
                                    <?php 
                                    $sc = $m['status']==='active'?'rgba(16,185,129,0.15)':($m['status']==='inactive'?'rgba(100,116,139,0.15)':'rgba(239,68,68,0.15)');
                                    $sColor = $m['status']==='active'?'#6ee7b7':($m['status']==='inactive'?'#94a3b8':'#f87171');
                                    ?>
                                    <span class="px-2.5 py-1 rounded-full text-xs font-semibold border border-white/5" style="background:<?php echo $sc; ?>; color:<?php echo $sColor; ?>"><?php echo ucfirst($m['status']); ?></span>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <div class="flex items-center justify-end gap-2">
                                        <a href="/admin/staff/edit?id=<?php echo $m['id']; ?>" class="w-8 h-8 rounded-lg flex items-center justify-center bg-white/5 text-slate-400 hover:text-emerald-400 hover:bg-emerald-500/10 transition border border-white/5" title="Edit Staff">
                                            <i class="fas fa-edit text-xs"></i>
                                        </a>
                                        <form action="/admin/staff/delete" method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this staff member?');">
                                            <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                                            <button type="submit" class="w-8 h-8 rounded-lg flex items-center justify-center bg-white/5 text-slate-400 hover:text-red-400 hover:bg-red-500/10 transition border border-white/5 cursor-pointer" title="Delete Staff">
                                                <i class="fas fa-trash-alt text-xs"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function toggleCashierDropdown(role) {
    const wrapper = document.getElementById('cashierWrapper');
    if (!wrapper) return;
    if (role === 'waiter' || role === 'kitchen' || role === 'inventory' || role === 'hr_manager') {
        wrapper.style.display = 'block';
    } else {
        wrapper.style.display = 'none';
    }
}
document.addEventListener('DOMContentLoaded', () => {
    const roleSelect = document.getElementById('roleSelect');
    if (roleSelect) toggleCashierDropdown(roleSelect.value);
});

function staffListApp() {
    return {
        search: '',
        roleFilter: '',
        init() {
            this.$watch('search', () => this.applyFilters());
            this.$watch('roleFilter', () => this.applyFilters());
        },
        applyFilters() {
            const s = this.search.toLowerCase();
            const r = this.roleFilter;
            document.querySelectorAll('.staff-row').forEach(row => {
                const nm = (row.dataset.name||'').includes(s) || !s;
                const rl = !r || row.dataset.role === r;
                row.style.display = (nm && rl) ? '' : 'none';
            });
        }
    };
}
</script>

<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/admin.php';
    }

    public function store() {
        $this->requireAdmin();
        $role = $_POST['role'] ?? '';
        $rest_id = $_SESSION['restaurant_id'];
        $allowedRoles = ['cashier', 'waiter', 'kitchen', 'inventory', 'hr_manager'];
        if (!in_array($role, $allowedRoles)) {
            header('Location: /admin/staff?error=' . urlencode('Invalid role selected or feature not enabled.')); exit;
        }
        if ($role === 'kitchen' && !FeatureGate::hasKitchen($rest_id)) {
            header('Location: /admin/staff?error=' . urlencode('Kitchen Display is not available in your subscription package.')); exit;
        }
        $db = getDB();

        if ($_POST['role'] === 'cashier') {
            $check = FeatureGate::canAddCashier($_SESSION['restaurant_id']);
            if (!$check['allowed']) {
                header('Location: /admin/staff?error=' . urlencode('Cashier limit reached. Upgrade your package.')); exit;
            }
        }
        if ($_POST['role'] === 'waiter') {
            $check = FeatureGate::canAddWaiter($_SESSION['restaurant_id']);
            if (!$check['allowed']) {
                header('Location: /admin/staff?error=' . urlencode('Waiter limit reached. Upgrade your package.')); exit;
            }
        }

        $cashier_id = (!empty($_POST['cashier_id']) && in_array($_POST['role'], ['waiter', 'kitchen', 'inventory', 'hr_manager'])) ? intval($_POST['cashier_id']) : null;

        // Check if email is already taken
        $emailCheck = $db->prepare('SELECT COUNT(*) FROM users WHERE email = ?');
        $emailCheck->execute([$_POST['email']]);
        if ($emailCheck->fetchColumn() > 0) {
            header('Location: /admin/staff?error=' . urlencode('Email address is already in use by another account.')); exit;
        }
        $hashed = password_hash($_POST['password'], PASSWORD_BCRYPT);
        $db->prepare('INSERT INTO users (restaurant_id, cashier_id, name, email, password, role, status) VALUES (?, ?, ?, ?, ?, ?, ?)')
           ->execute([$_SESSION['restaurant_id'], $cashier_id, $_POST['name'], $_POST['email'], $hashed, $_POST['role'], 'active']);
        header('Location: /admin/staff?msg=' . urlencode('Staff member added successfully.')); exit;
    }

    public function edit() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $id = $_GET['id'] ?? null;

        if (!$id) {
            header('Location: /admin/staff?error=' . urlencode('Invalid staff ID.')); exit;
        }

        $stmt = $db->prepare('SELECT * FROM users WHERE id = ? AND restaurant_id = ? AND role IN ("cashier", "waiter", "kitchen", "inventory", "hr_manager")');
        $stmt->execute([$id, $rest_id]);
        $member = $stmt->fetch();

        if (!$member) {
            header('Location: /admin/staff?error=' . urlencode('Staff member not found.')); exit;
        }

        // Load active cashiers
        $cashStmt = $db->prepare('SELECT id, name FROM users WHERE restaurant_id = ? AND role = "cashier" AND status = "active" AND id != ? ORDER BY name ASC');
        $cashStmt->execute([$rest_id, $id]);
        $cashiers = $cashStmt->fetchAll();

        $pageTitle = 'Edit Staff Member';
        ob_start(); ?>
        
<div class="max-w-2xl mx-auto space-y-6">
    <div class="flex items-center justify-between mb-4">
        <div>
            <h2 class="text-xl font-bold text-white flex items-center gap-2">
                <i class="fas fa-user-edit text-emerald-500"></i> Edit Staff Member
            </h2>
            <p class="text-xs text-slate-400">Modify cashier or waiter details and credentials</p>
        </div>
        <a href="/admin/staff" class="px-4 py-2 rounded-xl text-sm font-semibold text-slate-300 hover:text-white border border-white/10 hover:bg-white/5 transition flex items-center gap-2">
            <i class="fas fa-arrow-left text-xs"></i> Back to List
        </a>
    </div>

    <?php if (!empty($_GET['error'])): ?>
    <div class="rounded-xl px-4 py-3 text-sm font-medium text-red-300 flex items-center gap-2" style="background:rgba(239,68,68,0.12); border:1px solid rgba(239,68,68,0.25)">
        <i class="fas fa-exclamation-circle"></i>
        <?php echo htmlspecialchars($_GET['error']); ?>
    </div>
    <?php endif; ?>

    <div class="rounded-2xl p-8" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
        <form action="/admin/staff/update" method="POST" class="space-y-6">
            <input type="hidden" name="id" value="<?php echo $member['id']; ?>">
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm text-slate-400 mb-1.5 font-medium">Name</label>
                    <input type="text" name="name" value="<?php echo htmlspecialchars($member['name']); ?>" required class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500" style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
                </div>
                <div>
                    <label class="block text-sm text-slate-400 mb-1.5 font-medium">Email Address</label>
                    <input type="email" name="email" value="<?php echo htmlspecialchars($member['email']); ?>" required class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500" style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm text-slate-400 mb-1.5 font-medium">Role</label>
                    <select name="role" id="roleSelectEdit" onchange="toggleCashierDropdownEdit(this.value)" class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500" style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.1)">
                        <option value="cashier" <?php echo $member['role'] === 'cashier' ? 'selected' : ''; ?>>Cashier</option>
                        <option value="waiter" <?php echo $member['role'] === 'waiter' ? 'selected' : ''; ?>>Waiter</option>
                        <?php if (FeatureGate::hasKitchen($rest_id) || $member['role'] === 'kitchen'): ?>
                        <option value="kitchen" <?php echo $member['role'] === 'kitchen' ? 'selected' : ''; ?>>Kitchen</option>
                        <?php endif; ?>
                        <option value="inventory" <?php echo $member['role'] === 'inventory' ? 'selected' : ''; ?>>Inventory Manager</option>
                        <option value="hr_manager" <?php echo $member['role'] === 'hr_manager' ? 'selected' : ''; ?>>HR Manager</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm text-slate-400 mb-1.5 font-medium">Status</label>
                    <select name="status" class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500" style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.1)">
                        <option value="active" <?php echo $member['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo $member['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
            </div>

            <div id="cashierWrapperEdit" style="display:none">
                <label class="block text-sm text-slate-400 mb-1.5 font-medium">Assign to Cashier (Branch)</label>
                <select name="cashier_id" class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500" style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.1)">
                    <option value="">General Pool / Unassigned</option>
                    <?php foreach($cashiers as $c): ?>
                    <option value="<?php echo $c['id']; ?>" <?php echo $member['cashier_id'] == $c['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="pt-4 border-t border-white/5">
                <label class="block text-sm text-slate-400 mb-1 font-medium">New Password</label>
                <p class="text-xs text-slate-500 mb-2">Leave blank to keep the current password.</p>
                <input type="password" name="password" placeholder="••••••••" class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500" style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)" autocomplete="new-password">
            </div>

            <div class="flex gap-4 pt-2">
                <button type="submit" class="flex-1 py-3 rounded-xl font-semibold text-white transition text-sm" style="background:linear-gradient(135deg,#10b981,#059669)">
                    Update Staff Member
                </button>
                <a href="/admin/staff" class="px-6 py-3 rounded-xl font-semibold text-slate-300 hover:text-white border border-white/10 hover:bg-white/5 transition text-center text-sm">
                    Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<script>
function toggleCashierDropdownEdit(role) {
    const wrapper = document.getElementById('cashierWrapperEdit');
    if (!wrapper) return;
    if (role === 'waiter' || role === 'kitchen' || role === 'inventory' || role === 'hr_manager') {
        wrapper.style.display = 'block';
    } else {
        wrapper.style.display = 'none';
    }
}
document.addEventListener('DOMContentLoaded', () => {
    const roleSelectEdit = document.getElementById('roleSelectEdit');
    if (roleSelectEdit) toggleCashierDropdownEdit(roleSelectEdit.value);
});
</script>
<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/admin.php';
    }

    public function update() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $id = $_POST['id'] ?? null;
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $role = $_POST['role'] ?? '';
        $status = $_POST['status'] ?? '';
        $password = $_POST['password'] ?? '';

        if (!$id) {
            header('Location: /admin/staff?error=' . urlencode('Invalid staff ID.')); exit;
        }

        // Fetch existing user to verify restaurant ownership and current role
        $stmt = $db->prepare('SELECT * FROM users WHERE id = ? AND restaurant_id = ? AND role IN ("cashier", "waiter", "kitchen", "inventory", "hr_manager")');
        $stmt->execute([$id, $rest_id]);
        $existing = $stmt->fetch();

        if (!$existing) {
            header('Location: /admin/staff?error=' . urlencode('Staff member not found.')); exit;
        }

        $allowedRoles = ['cashier', 'waiter', 'kitchen', 'inventory', 'hr_manager'];
        if (!$name || !$email || !in_array($role, $allowedRoles) || !in_array($status, ['active', 'inactive'])) {
            header('Location: /admin/staff?error=' . urlencode('All fields except password are required.')); exit;
        }

        // Feature limit checks ONLY if role is changed
        if ($existing['role'] !== $role) {
            if ($role === 'cashier') {
                $check = FeatureGate::canAddCashier($rest_id);
                if (!$check['allowed']) {
                    header('Location: /admin/staff/edit?id=' . $id . '&error=' . urlencode('Cashier limit reached. Upgrade your package to assign this role.')); exit;
                }
            }
            if ($role === 'waiter') {
                $check = FeatureGate::canAddWaiter($rest_id);
                if (!$check['allowed']) {
                    header('Location: /admin/staff/edit?id=' . $id . '&error=' . urlencode('Waiter limit reached. Upgrade your package to assign this role.')); exit;
                }
            }
            if ($role === 'kitchen') {
                if (!FeatureGate::hasKitchen($rest_id)) {
                    header('Location: /admin/staff/edit?id=' . $id . '&error=' . urlencode('Kitchen Display is not available in your subscription package.')); exit;
                }
            }
        }

        // Check if email is already taken by another user
        $emailCheck = $db->prepare('SELECT COUNT(*) FROM users WHERE email = ? AND id != ?');
        $emailCheck->execute([$email, $id]);
        if ($emailCheck->fetchColumn() > 0) {
            header('Location: /admin/staff/edit?id=' . $id . '&error=' . urlencode('Email address is already in use by another user.')); exit;
        }

        $cashier_id = (!empty($_POST['cashier_id']) && in_array($role, ['waiter', 'kitchen', 'inventory', 'hr_manager'])) ? intval($_POST['cashier_id']) : null;

        if ($password !== '') {
            $hashed = password_hash($password, PASSWORD_BCRYPT);
            $db->prepare('UPDATE users SET cashier_id = ?, name = ?, email = ?, password = ?, role = ?, status = ? WHERE id = ?')
               ->execute([$cashier_id, $name, $email, $hashed, $role, $status, $id]);
        } else {
            $db->prepare('UPDATE users SET cashier_id = ?, name = ?, email = ?, role = ?, status = ? WHERE id = ?')
               ->execute([$cashier_id, $name, $email, $role, $status, $id]);
        }

        header('Location: /admin/staff?msg=' . urlencode('Staff member updated successfully.')); exit;
    }

    public function delete() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $id = $_POST['id'] ?? null;

        if (!$id) {
            header('Location: /admin/staff?error=' . urlencode('Invalid staff ID.')); exit;
        }

        // Verify the user exists, belongs to this restaurant, and is cashier, waiter or kitchen
        $stmt = $db->prepare('SELECT * FROM users WHERE id = ? AND restaurant_id = ? AND role IN ("cashier", "waiter", "kitchen", "inventory", "hr_manager")');
        $stmt->execute([$id, $rest_id]);
        $member = $stmt->fetch();

        if (!$member) {
            header('Location: /admin/staff?error=' . urlencode('Staff member not found or permission denied.')); exit;
        }

        $db->prepare('DELETE FROM users WHERE id = ?')->execute([$id]);
        header('Location: /admin/staff?msg=' . urlencode('Staff member deleted successfully.')); exit;
    }
}
