<?php
session_start();
if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "company_admin") { header("Location: ../auth/login.php"); exit; }
require_once '../config/database.php';
$companyId = (int)$_SESSION["company_id"];

/* ── Save salary ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["save_salary"])) {
    $staffId    = (int)$_POST["staff_id"];
    $month      = (int)$_POST["month"];
    $year       = (int)$_POST["year"];
    $base       = (float)str_replace(",", "", $_POST["base_salary"] ?? 0);
    $otHours    = (float)($_POST["ot_hours"] ?? 0);
    $otRate     = (float)str_replace(",", "", $_POST["ot_rate"] ?? 0);
    $totalOt    = round($otHours * $otRate, 2);
    $deductions = (float)str_replace(",", "", $_POST["deductions"] ?? 0);

    /* sum recurring allowances */
    $stA = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM hr_allowances WHERE staff_id=? AND company_id=? AND is_recurring=1");
    $stA->execute([$staffId, $companyId]);
    $allowSum = (float)$stA->fetchColumn();

    $netPay = $base + $totalOt + $allowSum - $deductions;
    $paidAt = !empty($_POST["mark_paid"]) ? date("Y-m-d H:i:s") : null;

    $chk = $pdo->prepare("SELECT id FROM hr_salary WHERE staff_id=? AND company_id=? AND month=? AND year=?");
    $chk->execute([$staffId, $companyId, $month, $year]);
    $existId = $chk->fetchColumn();

    if ($existId) {
        $pdo->prepare("UPDATE hr_salary SET base_salary=?,ot_hours=?,ot_rate=?,total_ot=?,total_allowances=?,deductions=?,net_pay=?,paid_at=? WHERE id=?")
            ->execute([$base,$otHours,$otRate,$totalOt,$allowSum,$deductions,$netPay,$paidAt,$existId]);
    } else {
        $pdo->prepare("INSERT INTO hr_salary (staff_id,company_id,month,year,base_salary,ot_hours,ot_rate,total_ot,total_allowances,deductions,net_pay,paid_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")
            ->execute([$staffId,$companyId,$month,$year,$base,$otHours,$otRate,$totalOt,$allowSum,$deductions,$netPay,$paidAt]);
    }
    header("Location: hr_salary.php?msg=saved&month=$month&year=$year"); exit;
}

$fm  = (int)($_GET["month"] ?? date("n"));
$fy  = (int)($_GET["year"]  ?? date("Y"));
$msg = $_GET["msg"] ?? "";

$allStaff = $pdo->prepare("SELECT u.id,u.name,cs.position,cs.department FROM company_staff cs JOIN users u ON u.id=cs.user_id WHERE cs.company_id=? AND u.status='active' ORDER BY u.name");
$allStaff->execute([$companyId]);
$allStaff = $allStaff->fetchAll(PDO::FETCH_ASSOC);

$rows = $pdo->prepare("SELECT s.*,u.name AS staff_name,cs.position FROM hr_salary s JOIN users u ON u.id=s.staff_id JOIN company_staff cs ON cs.user_id=s.staff_id AND cs.company_id=s.company_id WHERE s.company_id=? AND s.month=? AND s.year=? ORDER BY u.name");
$rows->execute([$companyId,$fm,$fy]);
$rows = $rows->fetchAll(PDO::FETCH_ASSOC);
$doneIds = array_column($rows,"staff_id");

$mn = ["","January","February","March","April","May","June","July","August","September","October","November","December"];
?>
<!DOCTYPE html>
<html lang="lo">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Salary — <?= htmlspecialchars($_SESSION["company_name"]) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{--p:#0f766e;--s:#fff;--bg:#f0f4f8;--b:#e2e8f0;--t:#0f172a;--m:#64748b;--g:#16a34a;--gl:#dcfce7;--r:#dc2626;--rl:#fee2e2;--a:#d97706;--al:#fef3c7;--bl:#2563eb;--bll:#dbeafe;--rad:14px;--sh:0 2px 14px rgba(15,23,42,.09)}
body{font-family:"Inter",Arial,sans-serif;background:var(--bg);color:var(--t);min-height:100vh}
.top-bar{background:var(--s);border-bottom:1px solid var(--b);padding:12px 32px;display:flex;align-items:center;gap:14px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06)}
.back{display:inline-flex;align-items:center;gap:6px;color:var(--m);text-decoration:none;font-size:13px;font-weight:600;padding:6px 12px;border-radius:8px;border:1.5px solid var(--b);transition:all .15s}
.back:hover{border-color:var(--p);color:var(--p)}
h1{font-size:17px;font-weight:800;flex:1}
.pb{padding:24px 32px;max-width:1200px;margin:auto}
.alert{padding:12px 16px;border-radius:10px;margin-bottom:18px;font-size:13px;font-weight:600;background:var(--gl);color:var(--g);border:1.5px solid #86efac}
.fbar{display:flex;align-items:center;gap:10px;margin-bottom:18px;flex-wrap:wrap}
.fbar select{padding:9px 13px;border:1.5px solid var(--b);border-radius:9px;font-size:13px;font-family:inherit;outline:none;background:var(--s)}
.fbar select:focus{border-color:var(--p)}
.btn{display:inline-flex;align-items:center;gap:6px;padding:9px 18px;border-radius:9px;font-size:13px;font-weight:700;font-family:inherit;cursor:pointer;border:none;text-decoration:none;transition:all .15s}
.btn-p{background:linear-gradient(135deg,#084740,#0f766e);color:#fff}
.btn-p:hover{opacity:.9}
.sum-row{display:grid;grid-template-columns:repeat(auto-fill,minmax(175px,1fr));gap:12px;margin-bottom:18px}
.sum-card{background:var(--s);border-radius:12px;padding:14px 18px;box-shadow:var(--sh);border:1px solid var(--b)}
.sum-lbl{font-size:11px;color:var(--m);font-weight:700;text-transform:uppercase;letter-spacing:.4px}
.sum-val{font-size:20px;font-weight:800;margin-top:4px}
.tc{background:var(--s);border-radius:var(--rad);box-shadow:var(--sh);border:1px solid var(--b);overflow:hidden;margin-bottom:20px}
.ch{padding:14px 20px;border-bottom:1px solid var(--b);display:flex;align-items:center;justify-content:space-between}
.ch h2{font-size:15px;font-weight:800}
table{width:100%;border-collapse:collapse}
thead th{background:#f8fafc;padding:10px 14px;text-align:left;font-size:11px;font-weight:700;color:var(--m);text-transform:uppercase;letter-spacing:.5px;border-bottom:1px solid var(--b);white-space:nowrap}
tbody tr{border-bottom:1px solid var(--b);transition:background .1s}
tbody tr:last-child{border-bottom:none}
tbody tr:hover{background:#f8fafc}
td{padding:11px 14px;font-size:13px;vertical-align:middle}
.badge{display:inline-flex;align-items:center;padding:3px 9px;border-radius:999px;font-size:11px;font-weight:700}
.bp{background:var(--gl);color:var(--g)} .bpend{background:var(--al);color:var(--a)}
.bs{padding:5px 11px;border-radius:7px;font-size:12px;font-weight:700;font-family:inherit;cursor:pointer;border:1.5px solid;text-decoration:none;display:inline-flex;align-items:center;gap:4px;transition:all .15s}
.be{border-color:#93c5fd;color:var(--bl);background:var(--bll)} .be:hover{background:var(--bl);color:#fff;border-color:var(--bl)}
.ba{border-color:#86efac;color:var(--g);background:var(--gl)} .ba:hover{background:var(--g);color:#fff;border-color:var(--g)}
.mo{display:none;position:fixed;inset:0;background:rgba(15,23,42,.5);z-index:999;align-items:center;justify-content:center;padding:20px}
.mo.open{display:flex}
.mbox{background:var(--s);border-radius:18px;padding:28px;max-width:500px;width:100%;box-shadow:0 24px 64px rgba(15,23,42,.22);max-height:90vh;overflow-y:auto}
.mbox h3{font-size:16px;font-weight:800;margin-bottom:16px;padding-bottom:12px;border-bottom:1px solid var(--b)}
.fr2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.fg{margin-bottom:13px}
.fg label{display:block;font-size:12px;font-weight:700;margin-bottom:4px}
.fg input,.fg select{width:100%;padding:9px 12px;border:1.5px solid var(--b);border-radius:8px;font-size:13px;font-family:inherit;outline:none;background:#f8fafc}
.fg input:focus,.fg select:focus{border-color:var(--p);background:#fff}
.np{background:linear-gradient(135deg,#084740,#0f766e);color:#fff;border-radius:10px;padding:14px 18px;margin:2px 0 14px}
.np .nl{font-size:11px;opacity:.75;text-transform:uppercase;letter-spacing:.4px}
.np .nv{font-size:22px;font-weight:800;margin-top:4px}
.ma{display:flex;gap:10px;justify-content:flex-end;margin-top:6px}
.mc{background:#f1f5f9;color:var(--m);border:1.5px solid var(--b);padding:9px 18px;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit}
.ms{background:linear-gradient(135deg,#084740,#0f766e);color:#fff;border:none;padding:9px 22px;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit}
.empty{text-align:center;padding:40px;color:var(--m);font-size:13px}
@media(max-width:700px){.pb{padding:16px}.top-bar{padding:10px 16px}.fr2{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="top-bar">
    <a class="back" href="dashboard.php">← Dashboard</a>
    <h1>💵 Salary Management</h1>
</div>
<div class="pb">

<?php if ($msg === "saved"): ?>
<div class="alert">✅ Salary record saved for <?= $mn[$fm] ?> <?= $fy ?>.</div>
<?php endif; ?>

<form method="GET" class="fbar">
    <select name="month"><?php for($i=1;$i<=12;$i++): ?><option value="<?=$i?>" <?=$i===$fm?"selected":""?>><?=$mn[$i]?></option><?php endfor; ?></select>
    <select name="year"><?php for($y=date("Y");$y>=date("Y")-3;$y--): ?><option value="<?=$y?>" <?=$y===$fy?"selected":""?>><?=$y?></option><?php endfor; ?></select>
    <button class="btn btn-p" type="submit">View</button>
</form>

<?php
$totalNet=$totalOtA=0; $totalPaid=0;
foreach($rows as $r){ $totalNet+=$r["net_pay"]; $totalOtA+=$r["total_ot"]; if($r["paid_at"]) $totalPaid++; }
?>
<div class="sum-row">
    <div class="sum-card"><div class="sum-lbl">Total Payroll</div><div class="sum-val">₭ <?=number_format($totalNet,0)?></div></div>
    <div class="sum-card"><div class="sum-lbl">Records</div><div class="sum-val"><?=count($rows)?> / <?=count($allStaff)?></div></div>
    <div class="sum-card"><div class="sum-lbl">Paid</div><div class="sum-val" style="color:var(--g)"><?=$totalPaid?></div></div>
    <div class="sum-card"><div class="sum-lbl">Total OT</div><div class="sum-val">₭ <?=number_format($totalOtA,0)?></div></div>
</div>

<div class="tc">
    <div class="ch"><h2>📋 <?=$mn[$fm]?> <?=$fy?> — Records</h2></div>
    <table>
        <thead><tr><th>Staff</th><th>Base</th><th>OT Hrs</th><th>OT Pay</th><th>Allowances</th><th>Deductions</th><th>Net Pay</th><th>Status</th><th></th></tr></thead>
        <tbody>
        <?php if(empty($rows)): ?>
            <tr><td colspan="9"><div class="empty">No records this period. Add below.</div></td></tr>
        <?php else: foreach($rows as $r): ?>
        <tr>
            <td><div style="font-weight:700"><?=htmlspecialchars($r["staff_name"])?></div><div style="font-size:11px;color:var(--m)"><?=htmlspecialchars($r["position"]??"")?></div></td>
            <td>₭ <?=number_format((float)$r["base_salary"],0)?></td>
            <td><?=number_format((float)$r["ot_hours"],1)?></td>
            <td>₭ <?=number_format((float)$r["total_ot"],0)?></td>
            <td>₭ <?=number_format((float)$r["total_allowances"],0)?></td>
            <td style="color:var(--r)">- ₭ <?=number_format((float)$r["deductions"],0)?></td>
            <td style="font-weight:800;color:var(--p);font-size:14px">₭ <?=number_format((float)$r["net_pay"],0)?></td>
            <td><?php if($r["paid_at"]): ?><span class="badge bp">✅ Paid</span><?php else: ?><span class="badge bpend">⏳ Pending</span><?php endif; ?></td>
            <td><button class="bs be" onclick='openModal(<?=htmlspecialchars(json_encode($r))?>)'>✏️ Edit</button></td>
        </tr>
        <?php endforeach; endif; ?>
        </tbody>
    </table>
</div>

<?php $missing=array_filter($allStaff,fn($s)=>!in_array($s["id"],$doneIds)); ?>
<?php if(!empty($missing)): ?>
<div class="tc">
    <div class="ch"><h2>➕ Add Records</h2><span style="font-size:12px;color:var(--m)"><?=count($missing)?> without records</span></div>
    <table>
        <thead><tr><th>Staff</th><th>Department</th><th></th></tr></thead>
        <tbody>
        <?php foreach($missing as $s): ?>
        <tr>
            <td><div style="font-weight:700"><?=htmlspecialchars($s["name"])?></div><div style="font-size:11px;color:var(--m)"><?=htmlspecialchars($s["position"]??"")?></div></td>
            <td style="color:var(--m)"><?=htmlspecialchars($s["department"]??"—")?></td>
            <td><button class="bs ba" onclick='openModal({staff_id:<?=$s["id"]?>,staff_name:<?=json_encode($s["name"])?>,month:<?=$fm?>,year:<?=$fy?>,base_salary:0,ot_hours:0,ot_rate:0,deductions:0,paid_at:null})'>➕ Add</button></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

</div>

<!-- Modal -->
<div class="mo" id="modal">
<div class="mbox">
    <h3>💵 Salary Record</h3>
    <form method="POST" id="sform">
        <input type="hidden" name="save_salary" value="1">
        <input type="hidden" name="staff_id" id="fsi">
        <input type="hidden" name="month"    id="fmo">
        <input type="hidden" name="year"     id="fyr">
        <div class="fg"><label>Staff</label><input type="text" id="fsn" readonly style="background:#f1f5f9;color:var(--m)"></div>
        <div class="fr2">
            <div class="fg"><label>Period</label><input type="text" id="fpe" readonly style="background:#f1f5f9;color:var(--m)"></div>
            <div class="fg"><label>Base Salary (₭)</label><input type="number" name="base_salary" id="fbs" min="0" step="1000" oninput="cn()"></div>
        </div>
        <div class="fr2">
            <div class="fg"><label>OT Hours</label><input type="number" name="ot_hours" id="foh" min="0" step="0.5" oninput="cn()"></div>
            <div class="fg"><label>OT Rate / hr (₭)</label><input type="number" name="ot_rate" id="for_" min="0" step="1000" oninput="cn()"></div>
        </div>
        <div class="fg"><label>Deductions (₭)</label><input type="number" name="deductions" id="fde" min="0" step="1000" oninput="cn()"></div>
        <div class="np"><div class="nl">Estimated Net Pay</div><div class="nv" id="np">₭ 0</div></div>
        <div class="fg" style="display:flex;align-items:center;gap:10px">
            <input type="checkbox" name="mark_paid" id="fpd" style="width:auto">
            <label for="fpd" style="margin:0;font-size:13px;font-weight:600">Mark as Paid</label>
        </div>
        <div class="ma">
            <button type="button" class="mc" onclick="document.getElementById('modal').classList.remove('open')">Cancel</button>
            <button type="submit" class="ms">💾 Save</button>
        </div>
    </form>
</div>
</div>

<script>
const mn=<?=json_encode($mn)?>;
function openModal(r){
    document.getElementById('fsi').value=r.staff_id;
    document.getElementById('fsn').value=r.staff_name||'';
    document.getElementById('fmo').value=r.month||<?=$fm?>;
    document.getElementById('fyr').value=r.year||<?=$fy?>;
    document.getElementById('fpe').value=(mn[r.month||<?=$fm?>]||'')+' '+(r.year||<?=$fy?>);
    document.getElementById('fbs').value=r.base_salary||0;
    document.getElementById('foh').value=r.ot_hours||0;
    document.getElementById('for_').value=r.ot_rate||0;
    document.getElementById('fde').value=r.deductions||0;
    document.getElementById('fpd').checked=!!r.paid_at;
    cn();
    document.getElementById('modal').classList.add('open');
}
function cn(){
    const b=parseFloat(document.getElementById('fbs').value)||0;
    const h=parseFloat(document.getElementById('foh').value)||0;
    const r=parseFloat(document.getElementById('for_').value)||0;
    const d=parseFloat(document.getElementById('fde').value)||0;
    document.getElementById('np').textContent='₭ '+Math.max(0,b+h*r-d).toLocaleString('en-US',{maximumFractionDigits:0});
}
document.getElementById('modal').addEventListener('click',function(e){if(e.target===this)this.classList.remove('open')});
</script>
</body>
</html>