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

$role      = $_SESSION["role"];
$companyId = (int)$_SESSION["company_id"];
$id        = (int)($_GET["id"] ?? 0);

$query = "
    SELECT p.*, s.base_salary, s.ot_hours, s.ot_rate, s.total_ot,
           s.total_allowances, s.deductions, s.net_pay, s.paid_at,
           u.name AS staff_name, u.email AS staff_email,
           cs.position, cs.department, cs.joined_date,
           c.name AS company_name
    FROM hr_payslips p
    JOIN hr_salary s  ON s.id = p.salary_id
    JOIN users u      ON u.id = p.staff_id
    JOIN company_staff cs ON cs.user_id=p.staff_id AND cs.company_id=p.company_id
    JOIN companies c  ON c.id = p.company_id
    WHERE p.id=? AND p.company_id=?
";
$params = [$id, $companyId];
if ($role === "staff") { $query .= " AND p.staff_id=?"; $params[] = $_SESSION["user_id"]; }

$st = $pdo->prepare($query);
$st->execute($params);
$ps = $st->fetch(PDO::FETCH_ASSOC);
if (!$ps) { echo "<p style='font-family:sans-serif;padding:40px;color:red'>Payslip not found or access denied.</p>"; exit; }

$allows = $pdo->prepare("SELECT type,amount FROM hr_allowances WHERE staff_id=? AND company_id=? AND is_recurring=1 ORDER BY type");
$allows->execute([$ps["staff_id"], $companyId]);
$allows = $allows->fetchAll(PDO::FETCH_ASSOC);

$mn = ["","January","February","March","April","May","June","July","August","September","October","November","December"];
$month = $mn[(int)$ps["month"]] . " " . $ps["year"];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Payslip — <?= htmlspecialchars($ps["staff_name"]) ?> — <?= $month ?></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}
body{font-family:"Inter",Arial,sans-serif;background:#f0f4f8;color:#0f172a;padding:32px 16px}
.slip{background:#fff;border-radius:16px;max-width:680px;margin:auto;box-shadow:0 4px 24px rgba(15,23,42,.12);overflow:hidden}
.slip-header{background:linear-gradient(135deg,#042f2e,#0f766e);color:#fff;padding:28px 32px;display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:16px}
.co-name{font-size:20px;font-weight:800;margin-bottom:4px}
.co-sub{font-size:13px;opacity:.75}
.slip-title{text-align:right}
.slip-title h2{font-size:18px;font-weight:800;margin-bottom:4px}
.slip-title .period{font-size:13px;opacity:.75}
.slip-title .slip-no{font-size:11px;opacity:.6;margin-top:4px}
.staff-section{padding:20px 32px;border-bottom:1px solid #e2e8f0;display:grid;grid-template-columns:1fr 1fr;gap:12px}
.info-row .lbl{font-size:11px;color:#64748b;font-weight:600;text-transform:uppercase;letter-spacing:.3px;margin-bottom:2px}
.info-row .val{font-size:13px;font-weight:600}
.pay-section{padding:24px 32px}
.pay-section h3{font-size:13px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-bottom:12px}
.pay-table{width:100%;border-collapse:collapse;margin-bottom:24px}
.pay-table td{padding:10px 0;font-size:13px;border-bottom:1px solid #f1f5f9}
.pay-table tr:last-child td{border-bottom:none}
.pay-table .amount{text-align:right;font-weight:600;font-variant-numeric:tabular-nums}
.pay-table .subtotal td{font-weight:700;border-top:1.5px solid #e2e8f0;border-bottom:none;padding-top:14px}
.deduct{color:#dc2626}
.net-section{background:linear-gradient(135deg,#042f2e,#0f766e);margin:0 32px 24px;border-radius:12px;padding:18px 24px;display:flex;justify-content:space-between;align-items:center;color:#fff;flex-wrap:wrap;gap:10px}
.net-lbl{font-size:12px;opacity:.75;text-transform:uppercase;letter-spacing:.5px}
.net-val{font-size:28px;font-weight:800}
.net-status{font-size:12px;margin-top:4px;opacity:.85}
.slip-footer{padding:16px 32px;border-top:1px solid #e2e8f0;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;background:#f8fafc}
.footer-note{font-size:11px;color:#94a3b8}
.print-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 18px;border-radius:8px;background:linear-gradient(135deg,#042f2e,#0f766e);color:#fff;border:none;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit}
@media print{body{background:#fff;padding:0}.slip{box-shadow:none;border-radius:0}.print-btn{display:none}}
@media(max-width:500px){.staff-section{grid-template-columns:1fr}.slip-header{flex-direction:column}.slip-title{text-align:left}}
</style>
</head>
<body>
<div class="slip">

    <div class="slip-header">
        <div>
            <div class="co-name"><?= htmlspecialchars($ps["company_name"]) ?></div>
            <div class="co-sub">Official Payslip</div>
        </div>
        <div class="slip-title">
            <h2>PAYSLIP</h2>
            <div class="period"><?= $month ?></div>
            <div class="slip-no">ID: <?= str_pad($ps["id"], 6, "0", STR_PAD_LEFT) ?></div>
        </div>
    </div>

    <div class="staff-section">
        <div class="info-row"><div class="lbl">Employee Name</div><div class="val"><?= htmlspecialchars($ps["staff_name"]) ?></div></div>
        <div class="info-row"><div class="lbl">Email</div><div class="val"><?= htmlspecialchars($ps["staff_email"]) ?></div></div>
        <div class="info-row"><div class="lbl">Position</div><div class="val"><?= htmlspecialchars($ps["position"] ?: "—") ?></div></div>
        <div class="info-row"><div class="lbl">Department</div><div class="val"><?= htmlspecialchars($ps["department"] ?: "—") ?></div></div>
        <div class="info-row"><div class="lbl">Pay Period</div><div class="val"><?= $month ?></div></div>
        <div class="info-row"><div class="lbl">Date Joined</div><div class="val"><?= $ps["joined_date"] ? date("d M Y", strtotime($ps["joined_date"])) : "—" ?></div></div>
    </div>

    <div class="pay-section">
        <h3>Earnings</h3>
        <table class="pay-table">
            <tr><td>Basic Salary</td><td class="amount">₭ <?= number_format((float)$ps["base_salary"],0) ?></td></tr>
            <?php if((float)$ps["ot_hours"]>0): ?>
            <tr><td>Overtime (<?= number_format((float)$ps["ot_hours"],1) ?> hrs × ₭ <?= number_format((float)$ps["ot_rate"],0) ?>)</td><td class="amount">₭ <?= number_format((float)$ps["total_ot"],0) ?></td></tr>
            <?php endif; ?>
            <?php foreach($allows as $al): ?>
            <tr><td><?= htmlspecialchars($al["type"]) ?> Allowance</td><td class="amount">₭ <?= number_format((float)$al["amount"],0) ?></td></tr>
            <?php endforeach; ?>
            <?php if(empty($allows)&&(float)$ps["total_allowances"]>0): ?>
            <tr><td>Allowances</td><td class="amount">₭ <?= number_format((float)$ps["total_allowances"],0) ?></td></tr>
            <?php endif; ?>
            <tr class="subtotal"><td>Total Earnings</td><td class="amount">₭ <?= number_format((float)$ps["base_salary"]+(float)$ps["total_ot"]+(float)$ps["total_allowances"],0) ?></td></tr>
        </table>

        <h3>Deductions</h3>
        <table class="pay-table">
            <?php if((float)$ps["deductions"]>0): ?>
            <tr><td>Deductions</td><td class="amount deduct">- ₭ <?= number_format((float)$ps["deductions"],0) ?></td></tr>
            <?php else: ?>
            <tr><td style="color:#94a3b8">No deductions</td><td class="amount" style="color:#94a3b8">₭ 0</td></tr>
            <?php endif; ?>
            <tr class="subtotal"><td>Total Deductions</td><td class="amount deduct">- ₭ <?= number_format((float)$ps["deductions"],0) ?></td></tr>
        </table>
    </div>

    <div class="net-section">
        <div>
            <div class="net-lbl">Net Pay</div>
            <div class="net-val">₭ <?= number_format((float)$ps["net_pay"],0) ?></div>
            <div class="net-status"><?= $ps["paid_at"] ? "✅ Paid on ".date("d M Y",strtotime($ps["paid_at"])) : "⏳ Payment pending" ?></div>
        </div>
        <div style="text-align:right;opacity:.7;font-size:13px">Generated<br><?= date("d M Y",strtotime($ps["generated_at"])) ?></div>
    </div>

    <div class="slip-footer">
        <div class="footer-note">Computer-generated payslip. No signature required.<br><?= htmlspecialchars($ps["company_name"]) ?> · Powered by Seven Digital</div>
        <button class="print-btn" onclick="window.print()">🖨️ Print Payslip</button>
    </div>

</div>
</body>
</html>