<?php
// app/Views/hr/index.php — v2 (Smart Attendance + Add Staff + Shift Management)
$isHrRole = ($_SESSION['role'] === 'hr_manager');
$baseUrl  = $isHrRole ? '/hr' : '/admin/hr';
$cqs      = $ctx['cashier_id'] ? '?cashier_id=' . $ctx['cashier_id'] : '';

$statusLabels = [
    'present'      => ['label'=>'Present',       'color'=>'#6ee7b7', 'bg'=>'rgba(16,185,129,0.15)'],
    'absent'       => ['label'=>'Absent',        'color'=>'#f87171', 'bg'=>'rgba(239,68,68,0.15)'],
    'late'         => ['label'=>'Late',          'color'=>'#fcd34d', 'bg'=>'rgba(245,158,11,0.15)'],
    'half_day'     => ['label'=>'Half Day',      'color'=>'#93c5fd', 'bg'=>'rgba(59,130,246,0.15)'],
    'holiday'      => ['label'=>'Holiday',       'color'=>'#94a3b8', 'bg'=>'rgba(100,116,139,0.15)'],
    'early_out'    => ['label'=>'Early Out',     'color'=>'#f9a8d4', 'bg'=>'rgba(236,72,153,0.15)'],
    'leave'        => ['label'=>'Leave (Paid)',  'color'=>'#c084fc', 'bg'=>'rgba(168,85,247,0.15)'],
    'unpaid_leave' => ['label'=>'Leave (Unpaid)','color'=>'#fb923c', 'bg'=>'rgba(249,115,22,0.15)'],
];
?>

<div class="space-y-5" x-data="hrApp()">

<?php if (!empty($_GET['success'])): ?>
<div x-data="{v:true}" x-show="v" x-init="setTimeout(()=>v=false,4000)"
     class="rounded-xl px-4 py-3 text-sm font-medium flex items-center gap-2"
     style="background:rgba(16,185,129,0.12); border:1px solid rgba(16,185,129,0.3); color:#6ee7b7">
    <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($_GET['success']); ?>
</div>
<?php endif; ?>
<?php if (!empty($_GET['error'])): ?>
<div class="rounded-xl px-4 py-3 text-sm font-medium flex items-center gap-2"
     style="background:rgba(239,68,68,0.12); border:1px solid rgba(239,68,68,0.3); color:#f87171">
    <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($_GET['error']); ?>
</div>
<?php endif; ?>

<!-- ── Page Header ── -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
    <div>
        <h2 class="text-xl font-bold text-white flex items-center gap-2">
            <i class="fas fa-users-cog text-indigo-400"></i>
            HR Management
            <?php if (!empty($cashierName)): ?>
                <span class="text-sm font-medium px-2 py-0.5 rounded-lg" style="background:rgba(99,102,241,0.15); color:#a5b4fc">
                    <i class="fas fa-store text-xs mr-1"></i><?php echo htmlspecialchars($cashierName); ?>
                </span>
            <?php endif; ?>
        </h2>
        <p class="text-xs text-slate-500 mt-0.5">Staff · Attendance · Payroll</p>
    </div>
    <div class="flex items-center gap-2 flex-wrap">
        <!-- Branch switcher (admin only) -->
        <?php if ($ctx['is_admin'] && !empty($cashiers)): ?>
        <form method="GET" action="<?php echo $baseUrl . ($activeTab !== 'staff' ? '/' . $activeTab : ''); ?>" class="flex items-center gap-2">
            <select name="cashier_id" onchange="this.form.submit()"
                    class="text-xs px-3 py-2 rounded-xl text-white outline-none"
                    style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.12)">
                <option value="">All Branches</option>
                <?php foreach($cashiers as $c): ?>
                <option value="<?php echo $c['id']; ?>" <?php echo $ctx['cashier_id'] == $c['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($c['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </form>
        <?php endif; ?>

        <!-- Tab nav (admin view only — hr layout has it in header) -->
        <?php if (!$isHrRole): ?>
        <div class="flex items-center gap-1 rounded-xl p-1" style="background:rgba(255,255,255,0.05)">
            <?php
            $tabs = [
                'staff'      => ['i'=>'fas fa-users',         'l'=>'Staff',      'u'=>$baseUrl.$cqs],
                'attendance' => ['i'=>'fas fa-calendar-check', 'l'=>'Attendance', 'u'=>$baseUrl.'/attendance'.$cqs],
                'payroll'    => ['i'=>'fas fa-money-bill-wave','l'=>'Payroll',    'u'=>$baseUrl.'/payroll'.$cqs],
            ];
            foreach ($tabs as $key => $tab):
                $isActive = $key === $activeTab;
            ?>
            <a href="<?php echo $tab['u']; ?>"
               class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition <?php echo $isActive ? 'text-white' : 'text-slate-400 hover:text-white hover:bg-white/5'; ?>"
               style="<?php echo $isActive ? 'background:rgba(99,102,241,0.3)' : ''; ?>">
                <i class="<?php echo $tab['i']; ?>"></i> <?php echo $tab['l']; ?>
            </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>


<?php if ($activeTab === 'staff'): ?>
<!-- ══════════════════════════════════════════════════════════════════════════
     STAFF TAB
═══════════════════════════════════════════════════════════════════════════ -->

<!-- Top action bar -->
<div class="flex flex-wrap items-center gap-2">
    <button @click="addStaffModal=true"
            class="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold text-white"
            style="background:linear-gradient(135deg,#6366f1,#4f46e5)">
        <i class="fas fa-user-plus text-xs"></i> Add Staff Member
    </button>
    <button @click="addShiftModal=true"
            class="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold transition"
            style="background:rgba(245,158,11,0.15); color:#fcd34d; border:1px solid rgba(245,158,11,0.25)">
        <i class="fas fa-clock text-xs"></i> Manage Shifts
    </button>
    <div class="relative ml-auto">
        <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-xs"></i>
        <input type="text" x-model="search" placeholder="Search staff…"
               class="pl-8 pr-3 py-2 text-xs text-white rounded-xl outline-none"
               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1); width:190px">
    </div>
</div>

<!-- Shift Cards -->
<?php if (!empty($shifts)): ?>
<div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
    <?php foreach($shifts as $sh): ?>
    <div class="rounded-xl p-3 flex items-start justify-between"
         style="background:rgba(245,158,11,0.08); border:1px solid rgba(245,158,11,0.18)">
        <div>
            <div class="text-xs font-bold text-amber-300 flex items-center gap-1">
                <?php if ($sh['is_default']): ?><i class="fas fa-star text-[9px]"></i><?php endif; ?>
                <?php echo htmlspecialchars($sh['name']); ?>
            </div>
            <div class="text-[11px] text-slate-400 mt-0.5">
                <?php echo date('g:i A', strtotime($sh['start_time'])); ?> – <?php echo date('g:i A', strtotime($sh['end_time'])); ?>
            </div>
            <div class="text-[10px] text-slate-600 mt-0.5">Late after <?php echo $sh['late_threshold_minutes']; ?>min</div>
        </div>
        <button @click="editShift(<?php echo htmlspecialchars(json_encode($sh), ENT_QUOTES); ?>)"
                class="text-slate-500 hover:text-amber-400 text-xs transition ml-2">
            <i class="fas fa-pen"></i>
        </button>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Staff stats -->
<?php
$totalStaff  = count($staff ?? []);
$withProfile = count(array_filter($staff ?? [], fn($s) => !empty($s['profile_id'])));
$withShift   = count(array_filter($staff ?? [], fn($s) => !empty($s['shift_id'])));
$roles       = array_count_values(array_column($staff ?? [], 'role'));
?>
<div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
    <div class="rounded-2xl p-4" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
        <p class="text-xs text-slate-500 mb-1">Total Staff</p>
        <p class="text-2xl font-bold text-white"><?php echo $totalStaff; ?></p>
    </div>
    <div class="rounded-2xl p-4" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
        <p class="text-xs text-slate-500 mb-1">Profiles Set</p>
        <p class="text-2xl font-bold text-indigo-400"><?php echo $withProfile; ?></p>
    </div>
    <div class="rounded-2xl p-4" style="background:rgba(245,158,11,0.07); border:1px solid rgba(245,158,11,0.15)">
        <p class="text-xs text-slate-500 mb-1">Shifts Assigned</p>
        <p class="text-2xl font-bold text-amber-400"><?php echo $withShift; ?></p>
    </div>
    <div class="rounded-2xl p-4" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
        <p class="text-xs text-slate-500 mb-1">Cashiers / Waiters</p>
        <p class="text-sm font-bold text-white mt-1">
            <span class="text-blue-400"><?php echo $roles['cashier'] ?? 0; ?>C</span>
            <span class="text-slate-600 mx-1">/</span>
            <span class="text-amber-400"><?php echo $roles['waiter'] ?? 0; ?>W</span>
        </p>
    </div>
</div>

<!-- Staff Table -->
<?php if (empty($staff)): ?>
<div class="rounded-2xl py-16 text-center" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
    <div class="w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-4" style="background:rgba(99,102,241,0.1)">
        <i class="fas fa-users text-indigo-400 text-xl"></i>
    </div>
    <p class="text-slate-400 font-medium">No staff yet</p>
    <p class="text-slate-600 text-xs mt-1">Click "Add Staff Member" to add your first staff</p>
</div>
<?php else: ?>
<div class="rounded-2xl overflow-hidden" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead>
                <tr class="border-b border-white/5 text-[11px] uppercase tracking-wide">
                    <th class="text-left px-5 py-3 text-slate-500 font-semibold">Name</th>
                    <th class="text-left px-4 py-3 text-slate-500 font-semibold">Role</th>
                    <th class="text-left px-4 py-3 text-slate-500 font-semibold">Designation</th>
                    <th class="text-left px-4 py-3 text-slate-500 font-semibold">Shift</th>
                    <th class="text-left px-4 py-3 text-slate-500 font-semibold">PIN</th>
                    <th class="text-left px-4 py-3 text-slate-500 font-semibold">Salary</th>
                    <th class="text-right px-5 py-3 text-slate-500 font-semibold">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $roleColors = [
                    'cashier'    => ['rgba(59,130,246,0.15)',  '#93c5fd'],
                    'waiter'     => ['rgba(245,158,11,0.15)',  '#fcd34d'],
                    'kitchen'    => ['rgba(168,85,247,0.15)',  '#d8b4fe'],
                    'inventory'  => ['rgba(16,185,129,0.15)',  '#6ee7b7'],
                    'hr_manager' => ['rgba(99,102,241,0.15)',  '#a5b4fc'],
                ];
                foreach($staff as $m):
                    $rc = $roleColors[$m['role']] ?? ['rgba(100,116,139,0.15)', '#94a3b8'];
                ?>
                <tr class="border-b border-white/5 hover:bg-white/5 transition staff-row"
                    data-name="<?php echo strtolower(htmlspecialchars($m['name'])); ?>">
                    <td class="px-5 py-3">
                        <div class="flex items-center gap-3">
                            <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($m['name']); ?>&background=6366f1&color=fff&size=40"
                                 class="w-8 h-8 rounded-full flex-shrink-0">
                            <div>
                                <div class="font-semibold text-white text-sm"><?php echo htmlspecialchars($m['name']); ?></div>
                                <div class="text-xs text-slate-500"><?php echo htmlspecialchars($m['email']); ?></div>
                            </div>
                        </div>
                    </td>
                    <td class="px-4 py-3">
                        <span class="px-2 py-0.5 rounded-full text-xs font-semibold"
                              style="background:<?php echo $rc[0]; ?>; color:<?php echo $rc[1]; ?>">
                            <?php echo (strpos($m['email'], '@restpo.local') !== false) ? 'Other Staff' : ucfirst(str_replace('_',' ',$m['role'])); ?>
                        </span>
                    </td>
                    <td class="px-4 py-3">
                        <div class="text-slate-300 text-sm"><?php echo htmlspecialchars($m['designation'] ?? '—'); ?></div>
                        <div class="text-slate-600 text-xs"><?php echo htmlspecialchars($m['department'] ?? ''); ?></div>
                    </td>
                    <td class="px-4 py-3">
                        <?php if (!empty($m['shift_name'])): ?>
                        <div class="text-amber-300 text-xs font-semibold"><?php echo htmlspecialchars($m['shift_name']); ?></div>
                        <div class="text-slate-500 text-[11px]">
                            <?php echo date('g:i A', strtotime($m['start_time'])); ?> – <?php echo date('g:i A', strtotime($m['end_time'])); ?>
                        </div>
                        <?php else: ?>
                        <span class="text-slate-600 text-xs italic">No shift</span>
                        <?php endif; ?>
                    </td>
                    <td class="px-4 py-3 font-mono">
                        <?php if (!empty($m['clock_in_pin'])): ?>
                        <span class="px-2 py-0.5 rounded-lg text-xs bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 font-bold">
                            <?php echo htmlspecialchars($m['clock_in_pin']); ?>
                        </span>
                        <?php else: ?>
                        <span class="text-slate-600 text-xs italic">Not set</span>
                        <?php endif; ?>
                    </td>
                    <td class="px-4 py-3">
                        <?php if (!empty($m['base_salary'])): ?>
                        <div class="text-white font-semibold text-sm"><?php echo number_format($m['base_salary'],2); ?></div>
                        <div class="text-slate-500 text-xs"><?php echo ucfirst($m['salary_type'] ?? 'monthly'); ?></div>
                        <?php else: ?>
                        <span class="text-slate-600 text-xs">Not set</span>
                        <?php endif; ?>
                    </td>
                    <td class="px-5 py-3 text-right">
                        <button @click="openProfile(<?php echo htmlspecialchars(json_encode($m), ENT_QUOTES); ?>)"
                                class="px-3 py-1.5 rounded-lg text-xs font-semibold transition"
                                style="background:rgba(99,102,241,0.15); color:#a5b4fc; border:1px solid rgba(99,102,241,0.2)">
                            <i class="fas fa-edit mr-1"></i> Edit
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>


<?php elseif ($activeTab === 'attendance'): ?>
<!-- ══════════════════════════════════════════════════════════════════════════
     ATTENDANCE TAB — Smart
═══════════════════════════════════════════════════════════════════════════ -->

<!-- Smart info banner -->
<div class="rounded-xl px-4 py-3 flex items-start gap-3 text-xs"
     style="background:rgba(99,102,241,0.08); border:1px solid rgba(99,102,241,0.2)">
    <i class="fas fa-brain text-indigo-400 mt-0.5"></i>
    <div class="text-slate-400">
        <span class="text-indigo-300 font-semibold">Smart Detection Active:</span>
        If a staff member has a shift assigned, the system auto-marks <span class="text-amber-300">Late</span> when check-in exceeds the late threshold,
        and <span class="text-pink-300">Half Day</span> when check-out is too early. You can still override manually.
    </div>
</div>

<!-- Date picker + bulk actions -->
<div class="flex flex-col sm:flex-row sm:items-center gap-3">
    <form method="GET" action="<?php echo $baseUrl; ?>/attendance" class="flex items-center gap-2">
        <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>
        <input type="date" name="date" value="<?php echo htmlspecialchars($date ?? date('Y-m-d')); ?>"
               class="px-3 py-2 rounded-xl text-white text-sm outline-none"
               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)"
               onchange="this.form.submit()">
        <span class="text-slate-400 text-sm font-medium"><?php echo date('l, F j Y', strtotime($date ?? date('Y-m-d'))); ?></span>
    </form>
    <div class="flex items-center gap-2 ml-auto flex-wrap">
        <button onclick="markAll('present')" class="px-3 py-1.5 rounded-lg text-xs font-semibold"
                style="background:rgba(16,185,129,0.15); color:#6ee7b7; border:1px solid rgba(16,185,129,0.25)">
            <i class="fas fa-check mr-1"></i> All Present
        </button>
        <button onclick="markAll('absent')" class="px-3 py-1.5 rounded-lg text-xs font-semibold"
                style="background:rgba(239,68,68,0.15); color:#f87171; border:1px solid rgba(239,68,68,0.25)">
            <i class="fas fa-times mr-1"></i> All Absent
        </button>
        <button onclick="markAll('holiday')" class="px-3 py-1.5 rounded-lg text-xs font-semibold"
                style="background:rgba(100,116,139,0.15); color:#94a3b8; border:1px solid rgba(100,116,139,0.25)">
            <i class="fas fa-umbrella-beach mr-1"></i> Holiday
        </button>
        <button type="button" @click="geofencingModal = true" class="px-3 py-1.5 rounded-lg text-xs font-semibold"
                style="background:rgba(99,102,241,0.15); color:#a5b4fc; border:1px solid rgba(99,102,241,0.25)">
            <i class="fas fa-qrcode mr-1"></i> Branch QR & Geofence
        </button>
    </div>
</div>

<?php if (empty($staff)): ?>
<div class="rounded-2xl py-16 text-center" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
    <p class="text-slate-500">No staff to mark attendance for.</p>
</div>
<?php else: ?>
<form action="<?php echo $baseUrl; ?>/attendance/mark" method="POST" id="attendanceForm">
    <input type="hidden" name="date" value="<?php echo htmlspecialchars($date); ?>">
    <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>

    <!-- Live status indicators (today only) -->
    <?php if ($date === date('Y-m-d')): ?>
    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <?php
        $inCount   = count(array_filter($todayMap ?? [], fn($r) => $r['check_in'] && !$r['check_out']));
        $outCount  = count(array_filter($todayMap ?? [], fn($r) => $r['check_out']));
        $absCnt    = count($staff) - count($todayMap ?? []);
        $lateCnt   = count(array_filter($todayMap ?? [], fn($r) => $r['status'] === 'late'));
        ?>
        <div class="rounded-xl p-3 text-center" style="background:rgba(16,185,129,0.08); border:1px solid rgba(16,185,129,0.2)">
            <div class="text-2xl font-bold text-emerald-400"><?php echo $inCount; ?></div>
            <div class="text-xs text-slate-500 mt-0.5"><i class="fas fa-door-open mr-1"></i>Currently In</div>
        </div>
        <div class="rounded-xl p-3 text-center" style="background:rgba(59,130,246,0.08); border:1px solid rgba(59,130,246,0.2)">
            <div class="text-2xl font-bold text-blue-400"><?php echo $outCount; ?></div>
            <div class="text-xs text-slate-500 mt-0.5"><i class="fas fa-door-closed mr-1"></i>Checked Out</div>
        </div>
        <div class="rounded-xl p-3 text-center" style="background:rgba(239,68,68,0.08); border:1px solid rgba(239,68,68,0.2)">
            <div class="text-2xl font-bold text-red-400"><?php echo $absCnt; ?></div>
            <div class="text-xs text-slate-500 mt-0.5"><i class="fas fa-user-slash mr-1"></i>Not Marked</div>
        </div>
        <div class="rounded-xl p-3 text-center" style="background:rgba(245,158,11,0.08); border:1px solid rgba(245,158,11,0.2)">
            <div class="text-2xl font-bold text-amber-400"><?php echo $lateCnt; ?></div>
            <div class="text-xs text-slate-500 mt-0.5"><i class="fas fa-clock mr-1"></i>Late</div>
        </div>
    </div>
    <?php endif; ?>

    <div class="rounded-2xl overflow-hidden" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
        <div class="flex items-center justify-between px-5 py-3 border-b border-white/5">
            <p class="text-sm font-semibold text-white">
                Attendance — <span style="color:#a5b4fc"><?php echo date('M j, Y', strtotime($date)); ?></span>
            </p>
            <button type="submit" class="px-4 py-1.5 rounded-xl text-xs font-bold text-white"
                    style="background:linear-gradient(135deg,#6366f1,#4f46e5)">
                <i class="fas fa-save mr-1"></i> Save All
            </button>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead>
                    <tr class="border-b border-white/5 text-[11px] uppercase tracking-wide">
                        <th class="text-left px-5 py-3 text-slate-500 font-semibold" style="min-width:180px">Staff</th>
                        <th class="text-left px-4 py-3 text-slate-500 font-semibold" style="min-width:90px">Shift</th>
                        <th class="text-left px-4 py-3 text-slate-500 font-semibold" style="min-width:155px">Status</th>
                        <th class="text-left px-4 py-3 text-slate-500 font-semibold" style="min-width:105px">Check-In</th>
                        <th class="text-left px-4 py-3 text-slate-500 font-semibold" style="min-width:105px">Check-Out</th>
                        <th class="text-left px-4 py-3 text-slate-500 font-semibold" style="min-width:90px">OT hrs</th>
                        <th class="text-left px-4 py-3 text-slate-500 font-semibold" style="min-width:80px">Month</th>
                        <th class="text-left px-4 py-3 text-slate-500 font-semibold" style="min-width:140px">Notes</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($staff as $m):
                        $att     = $attendanceMap[$m['id']] ?? [];
                        $status  = $att['status'] ?? 'absent';
                        $summary = $summaryMap[$m['id']] ?? [];
                        $sc      = $statusLabels[$status] ?? $statusLabels['absent'];
                    ?>
                    <tr class="border-b border-white/5 hover:bg-white/5 transition" id="row-<?php echo $m['id']; ?>">
                        <td class="px-5 py-3">
                            <div class="flex items-center gap-2">
                                <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($m['name']); ?>&background=6366f1&color=fff&size=32"
                                     class="w-7 h-7 rounded-full flex-shrink-0">
                                <div>
                                    <div class="text-white font-semibold text-xs"><?php echo htmlspecialchars($m['name']); ?></div>
                                    <div class="text-slate-500 text-[10px]"><?php echo htmlspecialchars($m['designation'] ?? ucfirst($m['role'])); ?></div>
                                </div>
                            </div>
                        </td>
                        <td class="px-4 py-3">
                            <?php if (!empty($m['shift_name'])): ?>
                            <div class="text-amber-300 text-[11px] font-semibold leading-tight"><?php echo htmlspecialchars($m['shift_name']); ?></div>
                            <div class="text-slate-600 text-[10px]">
                                <?php echo date('g:i A', strtotime($m['start_time'])); ?>
                            </div>
                            <?php else: ?>
                            <span class="text-slate-700 text-[10px]">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-3">
                            <select name="attendance[<?php echo $m['id']; ?>][status]"
                                    class="att-status w-full px-2 py-1.5 rounded-lg text-xs font-semibold outline-none"
                                    style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.1); color:<?php echo $sc['color']; ?>"
                                    onchange="updateRowColor(this)">
                                <?php foreach($statusLabels as $sv => $sl): ?>
                                <option value="<?php echo $sv; ?>" <?php echo $status === $sv ? 'selected' : ''; ?>>
                                    <?php echo $sl['label']; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                            <?php if (!empty($att['check_in']) && !empty($m['shift_name'])): ?>
                            <div class="text-[10px] mt-0.5" style="color:<?php echo $sc['color']; ?> ">
                                <i class="fas fa-robot text-[8px]"></i> Auto-detected
                            </div>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-3">
                            <input type="time" name="attendance[<?php echo $m['id']; ?>][check_in]"
                                   value="<?php echo htmlspecialchars($att['check_in'] ?? ''); ?>"
                                   class="w-full px-2 py-1.5 rounded-lg text-xs text-white outline-none"
                                   style="background:rgba(255,255,255,0.06); border:1px solid rgba(255,255,255,0.1)">
                        </td>
                        <td class="px-4 py-3">
                            <input type="time" name="attendance[<?php echo $m['id']; ?>][check_out]"
                                   value="<?php echo htmlspecialchars($att['check_out'] ?? ''); ?>"
                                   class="w-full px-2 py-1.5 rounded-lg text-xs text-white outline-none"
                                   style="background:rgba(255,255,255,0.06); border:1px solid rgba(255,255,255,0.1)">
                        </td>
                        <td class="px-4 py-3">
                            <input type="number" name="attendance[<?php echo $m['id']; ?>][overtime_hours]"
                                   value="<?php echo htmlspecialchars($att['overtime_hours'] ?? '0'); ?>"
                                   min="0" max="24" step="0.5"
                                   class="w-full px-2 py-1.5 rounded-lg text-xs text-white outline-none text-center"
                                   style="background:rgba(255,255,255,0.06); border:1px solid rgba(255,255,255,0.1)">
                        </td>
                        <td class="px-4 py-3">
                            <div class="text-[11px] space-y-0.5">
                                <div><span class="text-emerald-400 font-bold"><?php echo $summary['present'] ?? 0; ?></span><span class="text-slate-600">P</span></div>
                                <div><span class="text-red-400 font-bold"><?php echo $summary['absent'] ?? 0; ?></span><span class="text-slate-600">A</span>
                                <span class="text-amber-400 font-bold ml-1"><?php echo $summary['late'] ?? 0; ?></span><span class="text-slate-600">L</span></div>
                                <?php if (!empty($summary['total_hours'])): ?>
                                <div class="text-blue-400 text-[10px]"><?php echo $summary['total_hours']; ?>h</div>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td class="px-4 py-3">
                            <input type="text" name="attendance[<?php echo $m['id']; ?>][notes]"
                                   value="<?php echo htmlspecialchars($att['notes'] ?? ''); ?>"
                                   placeholder="Notes…"
                                   class="w-full px-2 py-1.5 rounded-lg text-xs text-white outline-none"
                                   style="background:rgba(255,255,255,0.06); border:1px solid rgba(255,255,255,0.1)">
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="px-5 py-3 border-t border-white/5 flex justify-end">
            <button type="submit" class="px-6 py-2.5 rounded-xl text-sm font-bold text-white"
                    style="background:linear-gradient(135deg,#6366f1,#4f46e5)">
                <i class="fas fa-save mr-2"></i> Save All Attendance
            </button>
        </div>
    </div>
</form>
<?php endif; // empty staff ?>


<?php elseif ($activeTab === 'payroll'): ?>
<!-- ══════════════════════════════════════════════════════════════════════════
     PAYROLL TAB
═══════════════════════════════════════════════════════════════════════════ -->

<div class="flex flex-col sm:flex-row sm:items-center gap-3">
    <form method="GET" action="<?php echo $baseUrl; ?>/payroll" class="flex items-center gap-2">
        <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>
        <select name="month" class="px-3 py-2 rounded-xl text-white text-sm outline-none"
                style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.12)" onchange="this.form.submit()">
            <?php for($mv=1;$mv<=12;$mv++): ?>
            <option value="<?php echo $mv; ?>" <?php echo $mv === ($month ?? date('n')) ? 'selected' : ''; ?>>
                <?php echo date('F', mktime(0,0,0,$mv,1)); ?>
            </option>
            <?php endfor; ?>
        </select>
        <select name="year" class="px-3 py-2 rounded-xl text-white text-sm outline-none"
                style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.12)" onchange="this.form.submit()">
            <?php for($yv=date('Y')-2; $yv<=date('Y')+1; $yv++): ?>
            <option value="<?php echo $yv; ?>" <?php echo $yv === ($year ?? date('Y')) ? 'selected' : ''; ?>><?php echo $yv; ?></option>
            <?php endfor; ?>
        </select>
    </form>
    <form action="<?php echo $baseUrl; ?>/payroll/generate" method="POST" class="ml-auto"
          onsubmit="return confirm('Generate payroll for <?php echo date('F Y', mktime(0,0,0,$month??1,1,$year??2026)); ?>? This will overwrite any draft records.')">
        <input type="hidden" name="month" value="<?php echo $month ?? date('n'); ?>">
        <input type="hidden" name="year"  value="<?php echo $year  ?? date('Y'); ?>">
        <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>
        <button type="submit" class="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold text-white"
                style="background:linear-gradient(135deg,#6366f1,#4f46e5)">
            <i class="fas fa-cogs text-xs"></i> Generate Payroll
        </button>
    </form>
</div>

<?php
$totalNet   = array_sum(array_column($payrollMap ?? [], 'net_pay'));
$totalPaid  = count(array_filter($payrollMap ?? [], fn($r) => $r['status'] === 'paid'));
$totalDraft = count(array_filter($payrollMap ?? [], fn($r) => $r['status'] === 'draft'));
?>
<div class="grid grid-cols-3 gap-4">
    <div class="rounded-2xl p-4" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
        <p class="text-xs text-slate-500 mb-1">Total Payroll</p>
        <p class="text-xl font-bold text-white"><?php echo ($currency??'')  . number_format($totalNet, 2); ?></p>
    </div>
    <div class="rounded-2xl p-4" style="background:rgba(16,185,129,0.07); border:1px solid rgba(16,185,129,0.15)">
        <p class="text-xs text-slate-500 mb-1">Paid</p>
        <p class="text-xl font-bold text-emerald-400"><?php echo $totalPaid; ?> records</p>
    </div>
    <div class="rounded-2xl p-4" style="background:rgba(245,158,11,0.07); border:1px solid rgba(245,158,11,0.15)">
        <p class="text-xs text-slate-500 mb-1">Drafts</p>
        <p class="text-xl font-bold text-amber-400"><?php echo $totalDraft; ?></p>
    </div>
</div>

<?php if (empty($staff)): ?>
<div class="rounded-2xl py-16 text-center" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
    <p class="text-slate-500">No staff found.</p>
</div>
<?php else: ?>
<div class="space-y-3">
    <?php foreach($staff as $m):
        $pr = $payrollMap[$m['id']] ?? null;
    ?>
    <div class="rounded-2xl overflow-hidden" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
        <div class="flex items-center justify-between px-5 py-3 border-b border-white/5">
            <div class="flex items-center gap-3">
                <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($m['name']); ?>&background=6366f1&color=fff&size=40"
                     class="w-8 h-8 rounded-full">
                <div>
                    <div class="font-semibold text-white text-sm"><?php echo htmlspecialchars($m['name']); ?></div>
                    <div class="text-xs text-slate-500"><?php echo htmlspecialchars($m['designation'] ?? ucfirst($m['role'])); ?></div>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <?php if ($pr): ?>
                    <span class="px-2 py-0.5 rounded-full text-xs font-semibold"
                          style="background:<?php echo $pr['status']==='paid'?'rgba(16,185,129,0.2)':'rgba(245,158,11,0.2)'; ?>;
                                 color:<?php echo $pr['status']==='paid'?'#6ee7b7':'#fcd34d'; ?>">
                        <?php echo $pr['status'] === 'paid' ? '✓ Paid' : '⏳ Draft'; ?>
                    </span>
                    <a href="<?php echo $baseUrl; ?>/payslip?id=<?php echo $pr['id']; ?>" target="_blank"
                       class="w-7 h-7 flex items-center justify-center rounded-lg text-xs"
                       style="background:rgba(59,130,246,0.15); color:#93c5fd" title="Print Payslip">
                        <i class="fas fa-print"></i>
                    </a>
                    <?php if ($pr['status'] === 'draft'): ?>
                    <button @click="openPayrollEdit(<?php echo htmlspecialchars(json_encode(array_merge($pr, ['staff_name'=>$m['name']])), ENT_QUOTES); ?>)"
                            class="w-7 h-7 flex items-center justify-center rounded-lg text-xs"
                            style="background:rgba(99,102,241,0.15); color:#a5b4fc" title="Adjust">
                        <i class="fas fa-sliders-h"></i>
                    </button>
                    <form action="<?php echo $baseUrl; ?>/payroll/pay" method="POST" class="inline"
                          onsubmit="return confirm('Mark as paid?')">
                        <input type="hidden" name="record_id" value="<?php echo $pr['id']; ?>">
                        <input type="hidden" name="month" value="<?php echo $month ?? date('n'); ?>">
                        <input type="hidden" name="year"  value="<?php echo $year  ?? date('Y'); ?>">
                        <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>
                        <button type="submit" class="px-3 py-1.5 rounded-lg text-xs font-semibold"
                                style="background:rgba(16,185,129,0.2); color:#6ee7b7; border:1px solid rgba(16,185,129,0.3)">
                            <i class="fas fa-check mr-1"></i> Mark Paid
                        </button>
                    </form>
                    <form action="<?php echo $baseUrl; ?>/payroll/delete" method="POST" class="inline"
                          onsubmit="return confirm('Delete this draft?')">
                        <input type="hidden" name="record_id" value="<?php echo $pr['id']; ?>">
                        <input type="hidden" name="month" value="<?php echo $month ?? date('n'); ?>">
                        <input type="hidden" name="year"  value="<?php echo $year  ?? date('Y'); ?>">
                        <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>
                        <button type="submit" class="w-7 h-7 flex items-center justify-center rounded-lg text-xs"
                                style="background:rgba(239,68,68,0.12); color:#f87171">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </form>
                    <?php endif; ?>
                <?php else: ?>
                    <span class="text-xs text-slate-600 italic">Not generated</span>
                <?php endif; ?>
            </div>
        </div>
        <?php if ($pr): ?>
        <div class="px-5 py-3 grid grid-cols-5 gap-4">
            <div class="text-center">
                <p class="text-[10px] text-slate-500 mb-1 uppercase">Present</p>
                <p class="text-sm font-bold text-emerald-400"><?php echo $pr['days_present']; ?><span class="text-slate-600 text-xs font-normal">/<?php echo $pr['working_days']; ?></span></p>
            </div>
            <div class="text-center">
                <p class="text-[10px] text-slate-500 mb-1 uppercase">Absent</p>
                <p class="text-sm font-bold text-red-400"><?php echo $pr['days_absent']; ?></p>
            </div>
            <div class="text-center">
                <p class="text-[10px] text-slate-500 mb-1 uppercase">Late/Half</p>
                <p class="text-sm font-bold text-amber-400"><?php echo $pr['days_late']; ?>/<?php echo $pr['days_half']; ?></p>
            </div>
            <div class="text-center">
                <p class="text-[10px] text-slate-500 mb-1 uppercase">OT</p>
                <p class="text-sm font-bold text-blue-400"><?php echo number_format($pr['overtime_hours'],1); ?>h</p>
            </div>
            <div class="text-center sm:text-right">
                <p class="text-[10px] text-slate-500 mb-1 uppercase">Net Pay</p>
                <p class="text-lg font-bold text-white"><?php echo ($currency??'').number_format($pr['net_pay'],2); ?></p>
                <?php if ($pr['bonus']>0 || $pr['deductions']>0): ?>
                <p class="text-[10px]">
                    <?php if($pr['bonus']): ?><span class="text-emerald-400">+<?php echo number_format($pr['bonus'],2);?></span><?php endif; ?>
                    <?php if($pr['deductions']): ?><span class="text-red-400 ml-1">-<?php echo number_format($pr['deductions'],2);?></span><?php endif; ?>
                </p>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="px-5 py-3 text-center text-slate-600 text-xs">Click "Generate Payroll" to compute pay.</div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>
<?php endif; // end tab ?>


<!-- ══════════════════════════════════════════════════════════════════════════
     MODALS
═══════════════════════════════════════════════════════════════════════════ -->

<!-- ── Add Staff Modal ── -->
<div x-show="addStaffModal" @keydown.escape.window="addStaffModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.78); backdrop-filter:blur(6px); display:none">
    <div class="w-full max-w-lg mx-4 rounded-2xl shadow-2xl" @click.away="addStaffModal=false"
         style="background:#0d1f3a; border:1px solid rgba(99,102,241,0.3)">
        <div class="flex items-center justify-between p-5 border-b border-white/8">
            <h3 class="text-base font-bold text-white flex items-center gap-2">
                <i class="fas fa-user-plus text-indigo-400"></i> Add Staff Member
            </h3>
            <button @click="addStaffModal=false" class="text-slate-500 hover:text-white"><i class="fas fa-times"></i></button>
        </div>
        <form action="<?php echo $baseUrl; ?>/staff/add" method="POST" class="p-5 space-y-4">
            <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>
            <div class="grid grid-cols-2 gap-4">
                <div class="col-span-2">
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Full Name *</label>
                    <input type="text" name="name" required placeholder="e.g. John Rahman"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div x-show="addStaffRole !== 'others'" class="col-span-2 grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs text-slate-400 mb-1.5 font-medium">Email *</label>
                        <input type="email" name="email" :required="addStaffRole !== 'others'" :disabled="addStaffRole === 'others'" placeholder="name@email.com"
                               class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                    </div>
                    <div>
                        <label class="block text-xs text-slate-400 mb-1.5 font-medium">Password *</label>
                        <input type="password" name="password" :required="addStaffRole !== 'others'" :disabled="addStaffRole === 'others'" placeholder="Set login password"
                               class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                    </div>
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Role *</label>
                    <select name="role" required x-model="addStaffRole"
                            class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                            style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.12)">
                        <option value="waiter">Waiter (Can log in to system)</option>
                        <option value="others">Others (Cleaner, Security, etc.)</option>
                    </select>
                </div>
                <div x-show="addStaffRole === 'others'" class="col-span-2">
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Specify Custom Role / Designation *</label>
                    <input type="text" name="custom_role" :required="addStaffRole === 'others'" :disabled="addStaffRole !== 'others'" placeholder="e.g. Security Guard, Cleaner"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                </div>
                <?php if ($ctx['is_admin'] && !empty($cashiers)): ?>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Assign to Branch</label>
                    <select name="assign_cashier_id"
                            class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                            style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.12)">
                        <option value="">No branch</option>
                        <?php foreach($cashiers as $c): ?>
                        <option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
            </div>
            <div class="rounded-xl p-3 space-y-3" style="background:rgba(99,102,241,0.06); border:1px solid rgba(99,102,241,0.15)">
                <p class="text-xs font-semibold text-indigo-300">Basic Salary (optional)</p>
                <div class="grid grid-cols-3 gap-3">
                    <div x-show="addStaffRole !== 'others'">
                        <label class="block text-xs text-slate-400 mb-1.5">Designation</label>
                        <input type="text" name="designation" :disabled="addStaffRole === 'others'" placeholder="e.g. Waiter"
                               class="w-full px-2 py-2 rounded-lg text-white text-xs outline-none"
                               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
                    </div>
                    <div>
                        <label class="block text-xs text-slate-400 mb-1.5">Salary Type</label>
                        <select name="salary_type"
                                class="w-full px-2 py-2 rounded-lg text-white text-xs outline-none"
                                style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.1)">
                            <option value="monthly">Monthly</option>
                            <option value="daily">Daily</option>
                            <option value="hourly">Hourly</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs text-slate-400 mb-1.5">Base Amount</label>
                        <input type="number" name="base_salary" min="0" step="0.01" placeholder="0"
                               class="w-full px-2 py-2 rounded-lg text-white text-xs outline-none"
                               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
                    </div>
                </div>
            </div>
            <div class="flex gap-3 pt-1">
                <button type="submit" class="flex-1 py-2.5 rounded-xl font-semibold text-white text-sm"
                        style="background:linear-gradient(135deg,#6366f1,#4f46e5)">
                    <i class="fas fa-user-plus mr-1.5"></i> Add Staff
                </button>
                <button type="button" @click="addStaffModal=false"
                        class="px-5 py-2.5 rounded-xl text-sm text-slate-400 border border-white/10 hover:bg-white/5 transition">
                    Cancel
                </button>
            </div>
        </form>
    </div>
</div>


<!-- ── Shift Management Modal ── -->
<div x-show="addShiftModal" @keydown.escape.window="addShiftModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.78); backdrop-filter:blur(6px); display:none">
    <div class="w-full max-w-md mx-4 rounded-2xl shadow-2xl max-h-[90vh] overflow-y-auto" @click.away="addShiftModal=false"
         style="background:#0d1f3a; border:1px solid rgba(245,158,11,0.3)">
        <div class="flex items-center justify-between p-5 border-b border-white/8 sticky top-0 z-10" style="background:#0d1f3a">
            <h3 class="text-base font-bold text-white flex items-center gap-2">
                <i class="fas fa-clock text-amber-400"></i>
                <span x-text="activeShift.id ? 'Edit Shift' : 'New Shift Schedule'">Shift Schedule</span>
            </h3>
            <button @click="addShiftModal=false; activeShift={}" class="text-slate-500 hover:text-white"><i class="fas fa-times"></i></button>
        </div>
        <form :action="'<?php echo $baseUrl; ?>/shift/store'" method="POST" class="p-5 space-y-4">
            <input type="hidden" name="shift_id" :value="activeShift.id || 0">
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Shift Name *</label>
                <input type="text" name="shift_name" :value="activeShift.name" required placeholder="e.g. Morning Shift"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Start Time *</label>
                    <input type="time" name="start_time" :value="activeShift.start_time" required
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">End Time *</label>
                    <input type="time" name="end_time" :value="activeShift.end_time" required
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                </div>
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Late After (minutes)</label>
                    <input type="number" name="late_threshold_minutes" :value="activeShift.late_threshold_minutes || 15" min="0" max="120"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                    <p class="text-[10px] text-slate-600 mt-1">Minutes past start before "Late"</p>
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Early-Out Before (minutes)</label>
                    <input type="number" name="early_out_threshold_minutes" :value="activeShift.early_out_threshold_minutes || 15" min="0" max="120"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                    <p class="text-[10px] text-slate-600 mt-1">Minutes before end triggers early-out</p>
                </div>
            </div>
            <label class="flex items-center gap-3 cursor-pointer">
                <input type="checkbox" name="is_default" value="1" :checked="activeShift.is_default == 1"
                       class="w-4 h-4 rounded" style="accent-color:#f59e0b">
                <span class="text-sm text-slate-300">Set as default shift</span>
            </label>

            <!-- Existing shifts list -->
            <?php if (!empty($shifts)): ?>
            <div class="rounded-xl overflow-hidden" style="border:1px solid rgba(255,255,255,0.07)">
                <div class="px-3 py-2 text-xs text-slate-500 font-semibold uppercase" style="background:rgba(255,255,255,0.04)">
                    Existing Shifts
                </div>
                <?php foreach($shifts as $sh): ?>
                <div class="flex items-center justify-between px-3 py-2 border-t border-white/5">
                    <div>
                        <span class="text-xs font-semibold text-white"><?php echo htmlspecialchars($sh['name']); ?></span>
                        <span class="text-[11px] text-slate-500 ml-2">
                            <?php echo date('g:i A', strtotime($sh['start_time'])); ?> – <?php echo date('g:i A', strtotime($sh['end_time'])); ?>
                        </span>
                        <?php if ($sh['is_default']): ?><span class="text-[10px] text-amber-400 ml-1">★ default</span><?php endif; ?>
                    </div>
                    <div class="flex items-center gap-1">
                        <button type="button" @click="editShift(<?php echo htmlspecialchars(json_encode($sh), ENT_QUOTES); ?>)"
                                class="text-xs px-2 py-1 rounded text-indigo-400 hover:text-white transition">Edit</button>
                        <form action="<?php echo $baseUrl; ?>/shift/delete" method="POST" class="inline"
                              onsubmit="return confirm('Delete this shift?')">
                            <input type="hidden" name="shift_id" value="<?php echo $sh['id']; ?>">
                            <button type="submit" class="text-xs px-2 py-1 rounded text-red-400 hover:text-white transition">Del</button>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <div class="flex gap-3 pt-1">
                <button type="submit" class="flex-1 py-2.5 rounded-xl font-semibold text-white text-sm"
                        style="background:linear-gradient(135deg,#f59e0b,#d97706)">
                    <i class="fas fa-save mr-1.5"></i> Save Shift
                </button>
                <button type="button" @click="addShiftModal=false; activeShift={}"
                        class="px-5 py-2.5 rounded-xl text-sm text-slate-400 border border-white/10 hover:bg-white/5 transition">
                    Cancel
                </button>
            </div>
        </form>
    </div>
</div>


<!-- ── Edit Staff Profile Modal ── -->
<div x-show="profileModal" @keydown.escape.window="profileModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.78); backdrop-filter:blur(6px); display:none">
    <div class="w-full max-w-2xl mx-4 rounded-2xl shadow-2xl max-h-[90vh] overflow-y-auto" @click.away="profileModal=false"
         style="background:#0d1f3a; border:1px solid rgba(99,102,241,0.3)">
        <div class="flex items-center justify-between p-5 border-b border-white/8 sticky top-0 z-10" style="background:#0d1f3a">
            <div>
                <h3 class="text-base font-bold text-white flex items-center gap-2">
                    <i class="fas fa-user-edit text-indigo-400"></i> Edit Staff Profile
                </h3>
                <p class="text-xs text-slate-400 mt-0.5" x-text="activeStaff.name"></p>
            </div>
            <button @click="profileModal=false" class="text-slate-500 hover:text-white"><i class="fas fa-times"></i></button>
        </div>
        <form action="<?php echo $baseUrl; ?>/staff/store" method="POST" class="p-5 space-y-4">
            <input type="hidden" name="user_id" :value="activeStaff.id">
            <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Designation</label>
                    <input type="text" name="designation" :value="activeStaff.designation" placeholder="e.g. Head Waiter"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Department</label>
                    <input type="text" name="department" :value="activeStaff.department" placeholder="e.g. Front of House"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Join Date</label>
                    <input type="date" name="join_date" :value="activeStaff.join_date"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Phone</label>
                    <input type="text" name="phone" :value="activeStaff.phone" placeholder="+880…"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                </div>
            </div>

            <!-- Shift assignment -->
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium"><i class="fas fa-clock text-amber-400 mr-1"></i>Assign Work Shift</label>
                <select name="shift_id"
                        class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                        style="background:rgba(13,33,55,1); border:1px solid rgba(245,158,11,0.25)">
                    <option value="">— No shift (manual status only) —</option>
                    <?php foreach(($shifts ?? []) as $sh): ?>
                    <option value="<?php echo $sh['id']; ?>"
                            :selected="activeStaff.shift_id == <?php echo $sh['id']; ?>">
                        <?php echo htmlspecialchars($sh['name']); ?>
                        (<?php echo date('g:i A', strtotime($sh['start_time'])); ?> – <?php echo date('g:i A', strtotime($sh['end_time'])); ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
                <p class="text-[10px] text-slate-600 mt-1">When a shift is assigned, attendance status is auto-detected from check-in/out times.</p>
            </div>

            <div class="rounded-xl p-4 space-y-3" style="background:rgba(99,102,241,0.06); border:1px solid rgba(99,102,241,0.15)">
                <p class="text-xs font-semibold text-indigo-300 uppercase">Salary Configuration</p>
                <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
                    <div>
                        <label class="block text-xs text-slate-400 mb-1.5">Salary Type</label>
                        <select name="salary_type" x-model="activeStaff.salary_type"
                                class="w-full px-2 py-2 rounded-lg text-white text-sm outline-none"
                                style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.12)">
                            <option value="monthly">Monthly</option>
                            <option value="daily">Daily</option>
                            <option value="hourly">Hourly</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs text-slate-400 mb-1.5">Base Amount</label>
                        <input type="number" name="base_salary" :value="activeStaff.base_salary" min="0" step="0.01"
                               class="w-full px-2 py-2 rounded-lg text-white text-sm outline-none"
                               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                    </div>
                    <div>
                        <label class="block text-xs text-slate-400 mb-1.5">OT Rate / hr</label>
                        <input type="number" name="overtime_rate" :value="activeStaff.overtime_rate" min="0" step="0.01"
                               class="w-full px-2 py-2 rounded-lg text-white text-sm outline-none"
                               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                    </div>
                    <div>
                        <label class="block text-xs text-slate-400 mb-1.5">Work Days/Mo</label>
                        <input type="number" name="working_days_per_month" :value="activeStaff.working_days_per_month || 26" min="1" max="31"
                               class="w-full px-2 py-2 rounded-lg text-white text-sm outline-none"
                               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                    </div>
                </div>
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Address</label>
                <textarea name="address" rows="2" :value="activeStaff.address"
                          class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none resize-none"
                          style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)"></textarea>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Emergency Contact</label>
                    <input type="text" name="emergency_contact" :value="activeStaff.emergency_contact" placeholder="Name & phone…"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium"><i class="fas fa-key text-emerald-400 mr-1"></i>Clock-In PIN (Unique)</label>
                    <input type="text" name="clock_in_pin" :value="activeStaff.clock_in_pin" placeholder="e.g. 2580"
                           maxlength="10"
                           class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(16,185,129,0.25)">
                </div>
            </div>
            <div class="flex gap-3">
                <button type="submit" class="flex-1 py-2.5 rounded-xl font-semibold text-white text-sm"
                        style="background:linear-gradient(135deg,#6366f1,#4f46e5)">
                    <i class="fas fa-save mr-1.5"></i> Save Profile
                </button>
                <button type="button" @click="profileModal=false"
                        class="px-5 py-2.5 rounded-xl text-sm text-slate-400 border border-white/10 hover:bg-white/5 transition">Cancel</button>
            </div>
        </form>
    </div>
</div>


<!-- ── Payroll Adjust Modal ── -->
<div x-show="payrollEditModal" @keydown.escape.window="payrollEditModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center"
     style="background:rgba(0,0,0,0.78); backdrop-filter:blur(6px); display:none">
    <div class="w-full max-w-sm mx-4 rounded-2xl shadow-2xl" @click.away="payrollEditModal=false"
         style="background:#0d1f3a; border:1px solid rgba(99,102,241,0.3)">
        <div class="flex items-center justify-between p-5 border-b border-white/8">
            <div>
                <h3 class="text-base font-bold text-white flex items-center gap-2">
                    <i class="fas fa-sliders-h text-indigo-400"></i> Adjust Payroll
                </h3>
                <p class="text-xs text-slate-400 mt-0.5" x-text="activePayroll.staff_name"></p>
            </div>
            <button @click="payrollEditModal=false" class="text-slate-500 hover:text-white"><i class="fas fa-times"></i></button>
        </div>
        <form action="<?php echo $baseUrl; ?>/payroll/update" method="POST" class="p-5 space-y-4">
            <input type="hidden" name="record_id" :value="activePayroll.id">
            <input type="hidden" name="month" value="<?php echo $month ?? date('n'); ?>">
            <input type="hidden" name="year"  value="<?php echo $year  ?? date('Y'); ?>">
            <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>
            <div class="rounded-xl p-3 text-xs space-y-1" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
                <div class="flex justify-between">
                    <span class="text-slate-400">Gross Pay</span>
                    <span class="text-white font-semibold" x-text="'<?php echo $currency??''; ?>' + parseFloat(activePayroll.gross_pay||0).toFixed(2)"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-slate-400">OT Pay</span>
                    <span class="text-blue-400" x-text="'<?php echo $currency??''; ?>' + parseFloat(activePayroll.overtime_pay||0).toFixed(2)"></span>
                </div>
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5">Bonus</label>
                <input type="number" name="bonus" :value="activePayroll.bonus || 0" min="0" step="0.01"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07); border:1px solid rgba(16,185,129,0.3)">
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5">Deductions</label>
                <input type="number" name="deductions" :value="activePayroll.deductions || 0" min="0" step="0.01"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07); border:1px solid rgba(239,68,68,0.3)">
            </div>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5">Notes</label>
                <input type="text" name="notes" :value="activePayroll.notes" placeholder="Reason…"
                       class="w-full px-3 py-2.5 rounded-xl text-white text-sm outline-none"
                       style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.12)">
            </div>
            <button type="submit" class="w-full py-2.5 rounded-xl font-semibold text-white text-sm"
                    style="background:linear-gradient(135deg,#6366f1,#4f46e5)">
                <i class="fas fa-check mr-1.5"></i> Update Payroll
            </button>
        </form>
    </div>
</div>

<!-- ── Branch QR & Geofencing Modal ── -->
<div x-show="geofencingModal" @keydown.escape.window="geofencingModal=false"
     class="fixed inset-0 z-50 flex items-center justify-center p-4"
     style="background:rgba(0,0,0,0.78); backdrop-filter:blur(6px); display:none">
    <div class="w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden" @click.away="geofencingModal=false"
         style="background:#0d1f3a; border:1px solid rgba(99,102,241,0.3)">
        
        <div class="flex items-center justify-between p-5 border-b border-white/8">
            <div>
                <h3 class="text-base font-bold text-white flex items-center gap-2">
                    <i class="fas fa-qrcode text-indigo-400"></i> Cashier Branches QR & Geofencing
                </h3>
                <p class="text-xs text-slate-400 mt-0.5">Configure geofencing and generate check-in QR codes per branch cashier.</p>
            </div>
            <button @click="geofencingModal=false" class="text-slate-500 hover:text-white"><i class="fas fa-times"></i></button>
        </div>

        <div class="p-6 max-h-[70vh] overflow-y-auto space-y-6">
            <?php if (empty($cashiers)): ?>
            <p class="text-slate-400 text-sm text-center py-6">No cashier branches found. Create a cashier user first.</p>
            <?php else: ?>
            <div class="space-y-4">
                <?php foreach ($cashiers as $c): 
                    $loc = $cashierLocations[$c['id']] ?? null;
                    $lat = $loc ? $loc['latitude'] : '';
                    $lng = $loc ? $loc['longitude'] : '';
                    $radius = $loc ? $loc['radius'] : 100;
                    $clockUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/clock?cashier_id=' . $c['id'];
                    $qrCardUrl = $baseUrl . '/cashier/qr-card?id=' . $c['id'];
                ?>
                <div class="rounded-xl p-4 border border-white/5 bg-white/[0.02] flex flex-col md:flex-row gap-4 items-start md:items-center justify-between">
                    <div>
                        <h4 class="text-sm font-bold text-white"><?php echo htmlspecialchars($c['name']); ?></h4>
                        <p class="text-xs text-slate-500 mt-0.5"><?php echo htmlspecialchars($c['email']); ?></p>
                        
                        <?php if ($loc): ?>
                        <div class="text-[10px] text-indigo-300 mt-2 flex items-center gap-2">
                            <span><i class="fas fa-map-marker-alt"></i> Lat: <?php echo $lat; ?>, Lng: <?php echo $lng; ?></span>
                            <span>&bull;</span>
                            <span>Radius: <?php echo $radius; ?>m</span>
                        </div>
                        <?php else: ?>
                        <div class="text-[10px] text-amber-400 mt-2"><i class="fas fa-warning"></i> Geofence not configured yet</div>
                        <?php endif; ?>
                    </div>

                    <div class="flex flex-wrap items-center gap-3 w-full md:w-auto">
                        <!-- QR Code Actions -->
                        <a href="<?php echo $qrCardUrl; ?>" target="_blank"
                           class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold bg-indigo-500/10 text-indigo-300 border border-indigo-500/20 hover:bg-indigo-500/20 transition">
                            <i class="fas fa-print"></i> Get QR Code
                        </a>

                        <!-- Setup Form -->
                        <div x-data="{ open: false, lat: '<?php echo $lat; ?>', lng: '<?php echo $lng; ?>', radius: '<?php echo $radius; ?>', loading: false }">
                            <button @click="open = !open" type="button"
                                    class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold bg-white/5 text-slate-300 border border-white/10 hover:text-white transition">
                                <i class="fas fa-cog"></i> Config Geofence
                            </button>

                            <div x-show="open" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm" style="display:none">
                                <form action="<?php echo $baseUrl; ?>/cashier-location/store" method="POST"
                                      class="w-full max-w-sm rounded-2xl p-5 space-y-4 shadow-2xl text-left"
                                      style="background:#0d2137; border:1px solid rgba(99,102,241,0.4)">
                                    
                                    <input type="hidden" name="cashier_id" value="<?php echo $c['id']; ?>">
                                    <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id_ctx" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>
                                    
                                    <div>
                                        <h4 class="text-sm font-bold text-white">Geofence Settings</h4>
                                        <p class="text-[10px] text-slate-400 mt-0.5">Define location coordinates for <?php echo htmlspecialchars($c['name']); ?></p>
                                    </div>

                                    <div class="grid grid-cols-2 gap-3">
                                        <div>
                                            <label class="block text-[10px] text-slate-400 mb-1">Latitude</label>
                                            <input type="number" step="any" name="latitude" x-model="lat" required
                                                   class="w-full px-2 py-1.5 rounded-lg text-xs bg-white/5 border border-white/10 text-white outline-none">
                                        </div>
                                        <div>
                                            <label class="block text-[10px] text-slate-400 mb-1">Longitude</label>
                                            <input type="number" step="any" name="longitude" x-model="lng" required
                                                   class="w-full px-2 py-1.5 rounded-lg text-xs bg-white/5 border border-white/10 text-white outline-none">
                                        </div>
                                    </div>

                                    <div>
                                        <label class="block text-[10px] text-slate-400 mb-1">Allowed Radius (meters)</label>
                                        <input type="number" name="radius" x-model="radius" required min="10"
                                               class="w-full px-2 py-1.5 rounded-lg text-xs bg-white/5 border border-white/10 text-white outline-none">
                                    </div>

                                    <div class="flex gap-2">
                                        <button type="button" @click="
                                            loading = true;
                                            navigator.geolocation.getCurrentPosition(
                                                (pos) => {
                                                    lat = pos.coords.latitude;
                                                    lng = pos.coords.longitude;
                                                    loading = false;
                                                },
                                                (err) => {
                                                    alert('Error fetching coordinates. Please enter manually.');
                                                    loading = false;
                                                }
                                            )
                                        " class="flex-grow py-2 rounded-lg text-xs font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 hover:bg-emerald-500/20 transition flex items-center justify-center gap-1">
                                            <i class="fas" :class="loading ? 'fa-spinner animate-spin' : 'fa-map-marker-alt'"></i>
                                            <span>Current Location</span>
                                        </button>
                                        
                                        <button type="button" @click="
                                            window.open('https://www.google.com/maps', '_blank')
                                        " class="px-3 py-2 rounded-lg text-xs font-medium bg-white/5 text-slate-400 border border-white/10 hover:text-white transition">
                                            <i class="fas fa-map"></i> Map
                                        </button>
                                    </div>

                                    <div class="flex gap-2 pt-2">
                                        <button type="submit" class="flex-grow py-2 rounded-lg text-xs font-bold bg-indigo-500 text-white hover:bg-indigo-600 transition">Save Location</button>
                                        <button type="button" @click="open=false" class="px-4 py-2 rounded-lg text-xs bg-white/5 text-slate-400 border border-white/10 hover:text-white transition">Cancel</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <div class="p-4 border-t border-white/8 flex justify-end">
            <button @click="geofencingModal=false" class="px-5 py-2 rounded-xl text-xs font-semibold bg-white/5 text-slate-400 border border-white/10 hover:text-white transition">Close</button>
        </div>
    </div>
</div>

</div><!-- x-data hrApp -->

<script>
function hrApp() {
    return {
        search: '',
        addStaffModal: false,
        addStaffRole: 'waiter',
        addShiftModal: false,
        profileModal: false,
        activeStaff: {},
        activeShift: {},
        payrollEditModal: false,
        activePayroll: {},
        geofencingModal: false,

        openProfile(staff) { this.activeStaff = staff; this.profileModal = true; },
        openPayrollEdit(pr) { this.activePayroll = pr; this.payrollEditModal = true; },
        editShift(sh) { this.activeShift = sh; this.addShiftModal = true; },

        init() {
            this.$watch('search', val => {
                const v = val.toLowerCase();
                document.querySelectorAll('.staff-row').forEach(row => {
                    const n = row.dataset.name || '';
                    row.style.display = (!v || n.includes(v)) ? '' : 'none';
                });
            });
        }
    };
}

function markAll(status) {
    document.querySelectorAll('.att-status').forEach(sel => {
        sel.value = status;
        updateRowColor(sel);
    });
}

function updateRowColor(sel) {
    const colors = {
        present:      '#6ee7b7',
        absent:       '#f87171',
        late:         '#fcd34d',
        half_day:     '#93c5fd',
        holiday:      '#94a3b8',
        early_out:    '#f9a8d4',
        leave:        '#c084fc',
        unpaid_leave: '#fb923c',
    };
    sel.style.color = colors[sel.value] || '#fff';
}

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.att-status').forEach(updateRowColor);
});
</script>
