<?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"];
$companyName = $_SESSION["company_name"] ?? "";

/* ── Generate payslip ── */
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["gen_payslip"])) {
    $salaryId = (int)$_POST["salary_id"];

    /* verify belongs to this company */
    $sal = $pdo->prepare("SELECT * FROM hr_salary WHERE id=? AND company_id=?");
    $sal->execute([$salaryId,$companyId]);
    $sal = $sal->fetch(PDO::FETCH_ASSOC);

    if ($sal) {
        /* upsert payslip */
        $chk = $pdo->prepare("SELECT id FROM hr_payslips WHERE salary_id=? AND company_id=?");
        $chk->execute([$salaryId,$companyId]);
        $existId = $chk->fetchColumn();
        if (!$existId) {
            $pdo->prepare("INSERT INTO hr_payslips (staff_id,company_id,salary_id,month,year,generated_at) VALUES (?,?,?,?,?,NOW())")
                ->execute([$sal["staff_id"],$companyId,$salaryId,$sal["month"],$sal["year"]]);
        }
    }
    header("Location: hr_payslips.php?msg=generated&month={$sal['month']}&year={$sal['year']}"); exit;
}

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

/* Salary records with payslip status */
$rows = $pdo->prepare("
    SELECT s.*, u.name AS staff_name, cs.position, cs.department,
           p.id AS payslip_id, p.generated_at
    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
    LEFT JOIN hr_payslips p ON p.salary_id=s.id AND p.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);

$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>Payslips — <?= htmlspecialchars($companyName) ?></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;--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:1100px;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;transition:all .15s}
.btn-p{background:linear-gradient(135deg,#084740,#0f766e);color:#fff}.btn-p:hover{opacity:.9}
.tc{background:var(--s);border-radius:var(--rad);box-shadow:var(--sh);border:1px solid var(--b);overflow:hidden}
.ch{padding:14px 20px;border-bottom:1px solid var(--b);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px}
.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;padding:3px 9px;border-radius:999px;font-size:11px;font-weight:700}
.bg{background:var(--gl);color:var(--g)} .ba{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}
.bgen{border-color:#86efac;color:var(--g);background:var(--gl)}.bgen:hover{background:var(--g);color:#fff;border-color:var(--g)}
.bview{border-color:#93c5fd;color:#2563eb;background:#eff6ff}.bview:hover{background:#2563eb;color:#fff;border-color:#2563eb}
.empty{text-align:center;padding:40px;color:var(--m);font-size:13px}
@media(max-width:700px){.pb{padding:16px}.top-bar{padding:10px 16px}}
</style>
</head>
<body>
<div class="top-bar">
    <a class="back" href="dashboard.php">← Dashboard</a>
    <h1>🧾 Payslip Generation</h1>
</div>
<div class="pb">

<?php if($msg==="generated"): ?><div class="alert">✅ Payslip generated 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>

<div class="tc">
    <div class="ch">
        <h2>🧾 <?=$mn[$fm]?> <?=$fy?> — Payslips</h2>
        <span style="font-size:12px;color:var(--m)"><?=count(array_filter($rows,fn($r)=>$r["payslip_id"]))?> / <?=count($rows)?> generated</span>
    </div>
    <table>
        <thead><tr><th>Staff</th><th>Net Pay</th><th>Base</th><th>OT</th><th>Allowances</th><th>Deductions</th><th>Payslip</th><th>Generated</th></tr></thead>
        <tbody>
        <?php if(empty($rows)): ?>
            <tr><td colspan="8"><div class="empty">No salary records for this period. Add salary records first.</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"]??"")?>
                <?php if($r["department"]): ?> · <?=htmlspecialchars($r["department"])?><?php endif; ?></div>
            </td>
            <td style="font-weight:800;color:var(--p);font-size:14px">₭ <?=number_format((float)$r["net_pay"],0)?></td>
            <td>₭ <?=number_format((float)$r["base_salary"],0)?></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>
                <?php if($r["payslip_id"]): ?>
                    <span class="badge bg">✅ Done</span>
                <?php else: ?>
                    <form method="POST" style="display:inline">
                        <input type="hidden" name="gen_payslip" value="1">
                        <input type="hidden" name="salary_id"   value="<?=$r["id"]?>">
                        <button class="bs bgen" type="submit">🧾 Generate</button>
                    </form>
                <?php endif; ?>
            </td>
            <td style="font-size:12px;color:var(--m)">
                <?php if($r["payslip_id"]): ?>
                    <?=date("d M Y",strtotime($r["generated_at"]))?>
                    <br><a class="bs bview" href="print_payslip.php?id=<?=$r["payslip_id"]?>" target="_blank" style="margin-top:4px">🖨️ View</a>
                <?php else: ?>—<?php endif; ?>
            </td>
        </tr>
        <?php endforeach; endif; ?>
        </tbody>
    </table>
</div>

</div>
<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>