<?php
// app/Views/hr/payroll.php — Enhanced Payroll Management tab

$isHrRole = ($_SESSION['role'] === 'hr_manager');
$baseUrl  = $isHrRole ? '/restpo/hr' : '/restpo/admin/hr';
$cqs      = $ctx['cashier_id'] ? '?cashier_id=' . $ctx['cashier_id'] : '';
$currency = $currency ?? '';

$curMonth = $month ?? date('n');
$curYear  = $year  ?? date('Y');
$monthName = date('F', mktime(0,0,0,$curMonth,1,$curYear));

// Totals
$totalNet    = array_sum(array_column($payrollMap ?? [], 'net_pay'));
$totalGross  = array_sum(array_column($payrollMap ?? [], 'gross_pay'));
$totalBonus  = array_sum(array_column($payrollMap ?? [], 'bonus'));
$totalDeduct = array_sum(array_column($payrollMap ?? [], 'deductions'));
$totalOtPay  = array_sum(array_column($payrollMap ?? [], 'overtime_pay'));
$paidCount   = count(array_filter($payrollMap ?? [], fn($r) => $r['status'] === 'paid'));
$draftCount  = count(array_filter($payrollMap ?? [], fn($r) => $r['status'] === 'draft'));
$paidAmount  = array_sum(array_map(fn($r) => $r['status']==='paid' ? $r['net_pay'] : 0, $payrollMap ?? []));
?>

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

<?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; ?>

<!-- ── 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-money-bill-wave text-emerald-400"></i>
            Payroll 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">Generate · Adjust · Pay · Print slips</p>
    </div>
    <div class="flex items-center gap-2 flex-wrap">
        <!-- Branch switcher -->
        <?php if ($ctx['is_admin'] && !empty($cashiers)): ?>
        <form method="GET" action="<?php echo $baseUrl; ?>/payroll" 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) -->
        <?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 === 'payroll';
            ?>
            <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(16,185,129,0.25)':''; ?>">
                <i class="<?php echo $tab['i']; ?>"></i> <?php echo $tab['l']; ?>
            </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Period selector + Actions -->
<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===$curMonth?'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===$curYear?'selected':''; ?>><?php echo $yv; ?></option>
            <?php endfor; ?>
        </select>
    </form>

    <div class="flex items-center gap-2 ml-auto">
        <form action="<?php echo $baseUrl; ?>/payroll/generate" method="POST"
              onsubmit="return confirm('Generate/re-generate payroll for <?php echo $monthName . ' ' . $curYear; ?>? Draft records will be overwritten.')">
            <input type="hidden" name="month" value="<?php echo $curMonth; ?>">
            <input type="hidden" name="year"  value="<?php echo $curYear; ?>">
            <?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 transition"
                    style="background:linear-gradient(135deg,#6366f1,#4f46e5)">
                <i class="fas fa-cogs text-xs"></i> Generate Payroll
            </button>
        </form>

        <?php if ($draftCount > 0): ?>
        <form action="<?php echo $baseUrl; ?>/payroll/pay-all" method="POST"
              onsubmit="return confirm('Mark ALL <?php echo $draftCount; ?> draft records as paid?')">
            <input type="hidden" name="month" value="<?php echo $curMonth; ?>">
            <input type="hidden" name="year"  value="<?php echo $curYear; ?>">
            <?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"
                    style="background:rgba(16,185,129,0.15); color:#6ee7b7; border:1px solid rgba(16,185,129,0.25)">
                <i class="fas fa-check-double text-xs"></i> Pay All (<?php echo $draftCount; ?>)
            </button>
        </form>
        <?php endif; ?>
    </div>
</div>

<!-- Summary Dashboard -->
<div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
    <div class="rounded-2xl p-4 col-span-2 sm:col-span-1"
         style="background:linear-gradient(135deg,rgba(16,185,129,0.15),rgba(5,150,105,0.08)); border:1px solid rgba(16,185,129,0.2)">
        <p class="text-xs text-slate-400 mb-1">Total Net Payroll</p>
        <p class="text-2xl font-bold text-emerald-400"><?php echo $currency . number_format($totalNet, 2); ?></p>
        <p class="text-xs text-slate-500 mt-1"><?php echo $monthName . ' ' . $curYear; ?></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-400 mb-1">Gross Payroll</p>
        <p class="text-lg font-bold text-white"><?php echo $currency . number_format($totalGross, 2); ?></p>
        <p class="text-[11px] text-slate-500 mt-1">Before adj.</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-400 mb-1">OT Pay</p>
        <p class="text-lg font-bold text-amber-400"><?php echo $currency . number_format($totalOtPay, 2); ?></p>
        <p class="text-[11px] text-slate-500 mt-1">Overtime earned</p>
    </div>
    <div class="rounded-2xl p-4" style="background:rgba(99,102,241,0.07); border:1px solid rgba(99,102,241,0.15)">
        <p class="text-xs text-slate-400 mb-1">Bonus / Deductions</p>
        <p class="text-lg font-bold text-indigo-300">
            <span class="text-emerald-400">+<?php echo number_format($totalBonus, 2); ?></span>
            <span class="text-slate-600 text-sm mx-1">/</span>
            <span class="text-red-400">-<?php echo number_format($totalDeduct, 2); ?></span>
        </p>
    </div>
</div>

<!-- Progress bar: paid vs pending -->
<?php if (!empty($payrollMap)): ?>
<div class="rounded-2xl p-4" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
    <div class="flex items-center justify-between mb-2 text-xs">
        <span class="text-slate-400 font-medium">Payment Progress — <?php echo $monthName; ?></span>
        <span class="text-white font-semibold"><?php echo $paidCount; ?>/<?php echo count($payrollMap); ?> paid</span>
    </div>
    <?php $paidPct = count($payrollMap) > 0 ? round(($paidCount / count($payrollMap)) * 100) : 0; ?>
    <div class="w-full rounded-full h-2.5" style="background:rgba(255,255,255,0.08)">
        <div class="h-2.5 rounded-full transition-all duration-500"
             style="width:<?php echo $paidPct; ?>%; background:linear-gradient(90deg,#10b981,#059669)"></div>
    </div>
    <div class="flex items-center justify-between mt-1.5 text-[11px] text-slate-500">
        <span><?php echo $currency . number_format($paidAmount, 2); ?> disbursed</span>
        <span><?php echo $currency . number_format($totalNet - $paidAmount, 2); ?> pending</span>
    </div>
</div>
<?php endif; ?>

<!-- Staff Payroll Cards -->
<?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. Add staff from the Staff tab first.</p>
</div>
<?php else: ?>
<div class="space-y-3">
    <?php foreach(($staff ?? []) as $m):
        $pr = $payrollMap[$m['id']] ?? null;
        $mismatch = $pr && (
            (float)$pr['base_salary'] !== (float)$m['base_salary'] ||
            $pr['salary_type'] !== $m['salary_type'] ||
            (float)$pr['overtime_rate'] !== (float)$m['overtime_rate']
        );
    ?>
    <div class="rounded-2xl overflow-hidden transition"
         style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">

        <!-- Card Header -->
        <div class="flex items-center gap-3 px-5 py-3 border-b border-white/5"
             :class="expanded === <?php echo $m['id']; ?> ? 'bg-white/5' : ''">
            <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($m['name']); ?>&background=6366f1&color=fff&size=40"
                 class="w-9 h-9 rounded-full flex-shrink-0">
            <div class="flex-1 min-w-0">
                <div class="text-white font-semibold text-sm"><?php echo htmlspecialchars($m['name']); ?></div>
                <div class="text-slate-500 text-xs"><?php echo htmlspecialchars($m['designation'] ?? ucfirst($m['role'])); ?>
                    <?php if (!empty($m['shift_name'])): ?>· <span class="text-amber-400"><?php echo htmlspecialchars($m['shift_name']); ?></span><?php endif; ?>
                </div>
            </div>

            <div class="flex items-center gap-2 flex-shrink-0">
                <?php if ($pr): ?>
                <!-- Status badge -->
                <span class="px-2.5 py-1 rounded-full text-xs font-bold"
                      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>
                <?php if ($mismatch): ?>
                <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold"
                      style="background:rgba(239,68,68,0.15); color:#f87171"
                      title="Salary profile was edited after this payroll was generated. Refresh or rollback to apply changes.">
                    ⚠️ Rate Mismatch
                </span>
                <?php endif; ?>
                <!-- Net pay -->
                <div class="text-right">
                    <div class="text-white font-bold text-sm"><?php echo $currency . number_format($pr['net_pay'],2); ?></div>
                    <div class="text-slate-600 text-[10px]">net pay</div>
                </div>
                <!-- Print -->
                <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 flex-shrink-0"
                   style="background:rgba(59,130,246,0.15); color:#93c5fd" title="Payslip">
                    <i class="fas fa-print"></i>
                </a>
                <?php if ($pr['status'] === 'paid'): ?>
                <!-- Rollback to Draft -->
                <form action="<?php echo $baseUrl; ?>/payroll/unpay" method="POST" class="inline"
                      onsubmit="return confirm('Rollback <?php echo htmlspecialchars(addslashes($m['name'])); ?>\'s paid record to draft? Salary rates will be updated.')">
                    <input type="hidden" name="record_id" value="<?php echo $pr['id']; ?>">
                    <input type="hidden" name="month" value="<?php echo $curMonth; ?>">
                    <input type="hidden" name="year"  value="<?php echo $curYear; ?>">
                    <?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 flex-shrink-0"
                            style="background:rgba(245,158,11,0.15); color:#fcd34d" title="Rollback to Draft">
                        <i class="fas fa-undo"></i>
                    </button>
                </form>
                <?php endif; ?>
                <?php if ($pr['status'] === 'draft'): ?>
                <!-- Regenerate Single Draft -->
                <form action="<?php echo $baseUrl; ?>/payroll/generate" method="POST" class="inline"
                      onsubmit="return confirm('Refresh attendance and reset adjustments for <?php echo htmlspecialchars(addslashes($m['name'])); ?>?')">
                    <input type="hidden" name="user_id" value="<?php echo $m['id']; ?>">
                    <input type="hidden" name="month" value="<?php echo $curMonth; ?>">
                    <input type="hidden" name="year"  value="<?php echo $curYear; ?>">
                    <?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 flex-shrink-0"
                            style="background:rgba(59,130,246,0.15); color:#93c5fd" title="Refresh / Recalculate">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </form>
                <!-- Adjust -->
                <button @click="openAdjust(<?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 flex-shrink-0"
                        style="background:rgba(99,102,241,0.15); color:#a5b4fc" title="Adjust">
                    <i class="fas fa-sliders-h"></i>
                </button>
                <!-- Mark Paid -->
                <form action="<?php echo $baseUrl; ?>/payroll/pay" method="POST" class="inline"
                      onsubmit="return confirm('Mark <?php echo htmlspecialchars(addslashes($m['name'])); ?> as paid?')">
                    <input type="hidden" name="record_id" value="<?php echo $pr['id']; ?>">
                    <input type="hidden" name="month" value="<?php echo $curMonth; ?>">
                    <input type="hidden" name="year"  value="<?php echo $curYear; ?>">
                    <?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 flex-shrink-0"
                            style="background:rgba(16,185,129,0.2); color:#6ee7b7; border:1px solid rgba(16,185,129,0.3)">
                        Pay
                    </button>
                </form>
                <!-- Delete -->
                <form action="<?php echo $baseUrl; ?>/payroll/delete" method="POST" class="inline"
                      onsubmit="return confirm('Delete draft?')">
                    <input type="hidden" name="record_id" value="<?php echo $pr['id']; ?>">
                    <input type="hidden" name="month" value="<?php echo $curMonth; ?>">
                    <input type="hidden" name="year"  value="<?php echo $curYear; ?>">
                    <?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 flex-shrink-0"
                            style="background:rgba(239,68,68,0.12); color:#f87171">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                </form>
                <?php endif; ?>
                <!-- Expand toggle -->
                <button @click="expanded = expanded === <?php echo $m['id']; ?> ? null : <?php echo $m['id']; ?>"
                        class="w-7 h-7 flex items-center justify-center rounded-lg text-slate-500 hover:text-white transition">
                    <i class="fas fa-chevron-down text-xs transition-transform"
                       :style="expanded === <?php echo $m['id']; ?> ? 'transform:rotate(180deg)' : ''"></i>
                </button>
                <?php else: ?>
                <span class="text-xs text-slate-600 italic mr-2">Not generated</span>
                <form action="<?php echo $baseUrl; ?>/payroll/generate" method="POST" class="inline">
                    <input type="hidden" name="user_id" value="<?php echo $m['id']; ?>">
                    <input type="hidden" name="month" value="<?php echo $curMonth; ?>">
                    <input type="hidden" name="year"  value="<?php echo $curYear; ?>">
                    <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>
                    <button type="submit" class="px-2.5 py-1 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)">
                        Generate
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <!-- Expanded Detail -->
        <?php if ($pr): ?>
        <div x-show="expanded === <?php echo $m['id']; ?>"
             x-transition:enter="transition ease-out duration-200"
             x-transition:enter-start="opacity-0 -translate-y-1"
             x-transition:enter-end="opacity-100 translate-y-0"
             style="display:none">
            <div class="px-5 py-4 grid grid-cols-2 sm:grid-cols-6 gap-4 border-b border-white/5">
                <div class="text-center">
                    <p class="text-[10px] text-slate-500 uppercase tracking-wide mb-1">Present</p>
                    <p class="text-base 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 uppercase tracking-wide mb-1">Absent</p>
                    <p class="text-base font-bold text-red-400"><?php echo $pr['days_absent']; ?></p>
                </div>
                <div class="text-center">
                    <p class="text-[10px] text-slate-500 uppercase tracking-wide mb-1">Late/Half</p>
                    <p class="text-base font-bold text-amber-400"><?php echo $pr['days_late']; ?>/<span class="text-blue-400"><?php echo $pr['days_half']; ?></span></p>
                </div>
                <div class="text-center">
                    <p class="text-[10px] text-slate-500 uppercase tracking-wide mb-1">OT Hours</p>
                    <p class="text-base font-bold text-indigo-400"><?php echo number_format($pr['overtime_hours'],1); ?>h</p>
                </div>
                <div class="text-center">
                    <p class="text-[10px] text-slate-500 uppercase tracking-wide mb-1">Gross</p>
                    <p class="text-base font-bold text-white"><?php echo $currency . number_format($pr['gross_pay'],2); ?></p>
                </div>
                <div class="text-center">
                    <p class="text-[10px] text-slate-500 uppercase tracking-wide mb-1">Net</p>
                    <p class="text-base font-bold text-emerald-400"><?php echo $currency . number_format($pr['net_pay'],2); ?></p>
                </div>
            </div>
            <!-- Breakdown bar -->
            <div class="px-5 py-3 flex items-center gap-3 text-xs text-slate-500">
                <span>Base: <span class="text-white"><?php echo $currency . number_format($pr['base_salary'],2); ?></span></span>
                <?php if ($pr['overtime_pay'] > 0): ?>
                <span class="text-emerald-400">+OT: <?php echo $currency . number_format($pr['overtime_pay'],2); ?></span>
                <?php endif; ?>
                <?php if ($pr['bonus'] > 0): ?>
                <span class="text-green-400">+Bonus: <?php echo $currency . number_format($pr['bonus'],2); ?></span>
                <?php endif; ?>
                <?php if ($pr['deductions'] > 0): ?>
                <span class="text-red-400">-Deduct: <?php echo $currency . number_format($pr['deductions'],2); ?></span>
                <?php endif; ?>
                <?php if (!empty($pr['leave_deduction']) && $pr['leave_deduction'] > 0): ?>
                <span class="text-orange-400">-Leave: <?php echo $currency . number_format($pr['leave_deduction'],2); ?></span>
                <?php endif; ?>
                <?php if ($pr['notes']): ?>
                <span class="text-slate-600 italic"><?php echo htmlspecialchars($pr['notes']); ?></span>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>


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

<!-- Adjust Payroll Modal -->
<div x-show="adjustModal" @keydown.escape.window="adjustModal=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="adjustModal=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="activeRecord.staff_name"></p>
            </div>
            <button @click="adjustModal=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="activeRecord.id">
            <input type="hidden" name="month" value="<?php echo $curMonth; ?>">
            <input type="hidden" name="year"  value="<?php echo $curYear; ?>">
            <?php if ($ctx['cashier_id']): ?><input type="hidden" name="cashier_id" value="<?php echo $ctx['cashier_id']; ?>"><?php endif; ?>

            <!-- Summary -->
            <div class="rounded-xl p-3 text-xs space-y-1.5" 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">Base Salary</span>
                    <span class="text-white font-semibold" x-text="'<?php echo $currency; ?>' + parseFloat(activeRecord.base_salary||0).toFixed(2)"></span>
                </div>
                <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(activeRecord.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(activeRecord.overtime_pay||0).toFixed(2)"></span>
                </div>
            </div>

            <div class="grid grid-cols-2 gap-3">
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5 font-medium">Bonus</label>
                    <input type="number" name="bonus" :value="activeRecord.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 font-medium">Deductions</label>
                    <input type="number" name="deductions" :value="activeRecord.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>
            <div>
                <label class="block text-xs text-slate-400 mb-1.5 font-medium">Notes</label>
                <input type="text" name="notes" :value="activeRecord.notes" placeholder="Reason for adjustment…"
                       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>

            <!-- Live net pay preview -->
            <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)">
                <p class="text-xs text-slate-400 mb-1">Estimated Net Pay</p>
                <p class="text-xl font-bold text-emerald-400" x-text="'<?php echo $currency; ?>' + estimatedNet()"></p>
            </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>

</div>

<script>
function payrollApp() {
    return {
        expanded: null,
        adjustModal: false,
        activeRecord: {},

        openAdjust(rec) { this.activeRecord = rec; this.adjustModal = true; },

        estimatedNet() {
            const gross  = parseFloat(this.activeRecord.gross_pay) || 0;
            const bonus  = parseFloat(document.querySelector('[name="bonus"]')?.value) || 0;
            const deduct = parseFloat(document.querySelector('[name="deductions"]')?.value) || 0;
            return Math.max(0, gross + bonus - deduct).toFixed(2);
        },
    };
}
</script>
