<?php
/* ============================================================================
 *  staff/payslip_print.php — professional, printable payslip(s) for the staff.
 *  Renders one A4 payslip per selected month (page-break between) with the
 *  company logo and a full earnings/deductions breakdown. Save as PDF for banks.
 *  Usage: payslip_print.php?ids=12,13   (hr_salary row ids belonging to the user)
 * ==========================================================================*/
session_start();
if (!isset($_SESSION["user_id"]) || empty($_SESSION["company_id"])) {
    header("Location: ../auth/login.php"); exit;
}
require_once '../config/database.php';

$userId    = (int)$_SESSION["user_id"];
$companyId = (int)$_SESSION["company_id"];

/* selected payslip ids (from checkbox array or comma list) */
$ids = [];
if (isset($_GET['ids'])) {
    $raw = is_array($_GET['ids']) ? $_GET['ids'] : explode(',', (string)$_GET['ids']);
    $ids = array_values(array_filter(array_map('intval', $raw)));
}
if (!$ids) { die('No payslip selected.'); }

/* staff + company info */
$info = $pdo->prepare("SELECT u.name, u.phone, cs.position, cs.department, cs.staff_code, cs.bank_name, cs.bank_account, c.name AS company_name
                       FROM company_staff cs JOIN users u ON u.id=cs.user_id JOIN companies c ON c.id=cs.company_id
                       WHERE cs.user_id=? AND cs.company_id=? LIMIT 1");
$info->execute([$userId, $companyId]);
$info = $info->fetch(PDO::FETCH_ASSOC) ?: [];
$companyName = $info['company_name'] ?? ($_SESSION['company_name'] ?? 'Company');

/* cycle start day (to resolve loan period) */
$cycleStart = 1;
try { $c=$pdo->prepare("SELECT cycle_start_day FROM att_rules WHERE company_id=? LIMIT 1"); $c->execute([$companyId]); $cv=$c->fetchColumn(); if($cv)$cycleStart=max(1,(int)$cv);} catch(Throwable $e){}

$in = implode(',', array_fill(0, count($ids), '?'));
$st = $pdo->prepare("SELECT * FROM hr_salary WHERE company_id=? AND staff_id=? AND id IN ($in) ORDER BY year, month");
$st->execute(array_merge([$companyId,$userId], $ids));
$slips = $st->fetchAll(PDO::FETCH_ASSOC);
if (!$slips) { die('Payslip not found.'); }

$mn = ["","January","February","March","April","May","June","July","August","September","October","November","December"];
function kip($n){ return number_format((float)$n,0); }

function periodFor($cycleStart,$m,$y){
    if ($cycleStart<=1){ $ps=sprintf('%04d-%02d-01',$y,$m); return [$ps, date('Y-m-t',strtotime($ps))]; }
    $ps=sprintf('%04d-%02d-%02d',$y,$m,$cycleStart); return [$ps, date('Y-m-d',strtotime($ps.' +1 month -1 day'))];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Payslip — <?= htmlspecialchars($info['name'] ?? '') ?></title>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700;800&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","Noto Sans Lao",Arial,sans-serif;background:#e9eef4;color:#0f172a;}
    .toolbar{position:sticky;top:0;background:#0f766e;color:#fff;padding:12px 18px;display:flex;justify-content:space-between;align-items:center;gap:10px;}
    .toolbar .t{font-weight:800;font-size:15px;}
    .toolbar button,.toolbar a{background:#fff;color:#0f766e;border:none;padding:9px 16px;border-radius:8px;font-weight:800;font-size:13px;cursor:pointer;text-decoration:none;font-family:inherit;}
    .sheet{max-width:780px;margin:18px auto;background:#fff;padding:38px 40px;box-shadow:0 6px 24px rgba(15,23,42,.12);}
    .ph{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:3px solid #0f766e;padding-bottom:16px;margin-bottom:20px;}
    .ph .co{display:flex;align-items:center;gap:14px;}
    .ph .logo{width:64px;height:64px;object-fit:contain;border-radius:10px;}
    .ph .cn{font-size:20px;font-weight:800;color:#0f766e;line-height:1.2;}
    .ph .cs{font-size:12px;color:#64748b;margin-top:3px;}
    .ph .title{text-align:right;}
    .ph .title .pt{font-size:22px;font-weight:800;letter-spacing:1px;color:#0f172a;}
    .ph .title .pp{font-size:13px;color:#64748b;margin-top:4px;}
    .meta{display:grid;grid-template-columns:1fr 1fr;gap:6px 24px;font-size:13px;margin-bottom:22px;}
    .meta .row{display:flex;justify-content:space-between;border-bottom:1px dotted #e2e8f0;padding:5px 0;}
    .meta .k{color:#64748b;font-weight:600;}.meta .v{font-weight:700;text-align:right;}
    .cols{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:18px;}
    .box{border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;}
    .box h3{font-size:12px;text-transform:uppercase;letter-spacing:.6px;padding:10px 14px;color:#fff;}
    .box.earn h3{background:#15803d;}.box.ded h3{background:#b91c1c;}
    .box .li{display:flex;justify-content:space-between;padding:9px 14px;font-size:13px;border-top:1px solid #f1f5f9;}
    .box .li .a{font-weight:700;}
    .box .sum{display:flex;justify-content:space-between;padding:11px 14px;font-weight:800;font-size:13px;background:#f8fafc;border-top:2px solid #e2e8f0;}
    .net{background:#0f766e;color:#fff;border-radius:10px;padding:16px 20px;display:flex;justify-content:space-between;align-items:center;margin-bottom:26px;}
    .net .l{font-size:13px;text-transform:uppercase;letter-spacing:.6px;opacity:.85;}
    .net .v{font-size:26px;font-weight:800;}
    .sign{display:grid;grid-template-columns:1fr 1fr;gap:50px;margin-top:40px;}
    .sign .s{border-top:1px solid #94a3b8;padding-top:6px;font-size:12px;color:#64748b;text-align:center;}
    .foot{margin-top:24px;font-size:10px;color:#94a3b8;text-align:center;}
    @media print{
        body{background:#fff;}
        .toolbar{display:none;}
        .sheet{box-shadow:none;margin:0;max-width:none;padding:24px 28px;page-break-after:always;}
        .sheet:last-child{page-break-after:auto;}
    }
</style>
</head>
<body>

<div class="toolbar">
    <span class="t">🧾 Payslip — <?= count($slips) ?> month(s)</span>
    <div>
        <a href="my_payslips.php">← Back</a>
        <button onclick="window.print()">⬇ Download / Print PDF</button>
    </div>
</div>

<?php foreach ($slips as $s):
    $m=(int)$s['month']; $y=(int)$s['year'];
    [$ps,$pe] = periodFor($cycleStart,$m,$y);
    /* loan repaid this period */
    $loan = 0;
    try { $lq=$pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM hr_loan_payments WHERE staff_id=? AND company_id=? AND period_start=?"); $lq->execute([$userId,$companyId,$ps]); $loan=(float)$lq->fetchColumn(); } catch(Throwable $e){}
    $base=(float)$s['base_salary']; $ot=(float)$s['total_ot']; $allow=(float)$s['total_allowances'];
    $gross=$base+$ot+$allow;
    $late=(float)($s['late_deduction']??0); $absd=(float)($s['absence_deduction']??0);
    $totalDed=(float)$s['deductions'];
    $other=max(0,$totalDed-$late-$absd-$loan);
    $net=(float)$s['net_pay'];
?>
<div class="sheet">
    <div class="ph">
        <div class="co">
            <img class="logo" src="../assets/7.png" alt="">
            <div>
                <div class="cn"><?= htmlspecialchars($companyName) ?></div>
                <div class="cs">Payslip / ໃບແຈ້ງເງິນເດືອນ</div>
            </div>
        </div>
        <div class="title">
            <div class="pt">PAYSLIP</div>
            <div class="pp"><?= $mn[$m] ?> <?= $y ?></div>
            <div class="pp"><?= date('d/m/Y',strtotime($ps)) ?> – <?= date('d/m/Y',strtotime($pe)) ?></div>
        </div>
    </div>

    <div class="meta">
        <div class="row"><span class="k">Employee</span><span class="v"><?= htmlspecialchars($info['name'] ?? '') ?></span></div>
        <div class="row"><span class="k">Staff ID</span><span class="v"><?= htmlspecialchars($info['staff_code'] ?: '—') ?></span></div>
        <div class="row"><span class="k">Position</span><span class="v"><?= htmlspecialchars($info['position'] ?: '—') ?></span></div>
        <div class="row"><span class="k">Department</span><span class="v"><?= htmlspecialchars($info['department'] ?: '—') ?></span></div>
        <div class="row"><span class="k">Bank</span><span class="v"><?= htmlspecialchars($info['bank_name'] ?: '—') ?></span></div>
        <div class="row"><span class="k">Account No.</span><span class="v"><?= htmlspecialchars($info['bank_account'] ?: '—') ?></span></div>
    </div>

    <div class="cols">
        <div class="box earn">
            <h3>Earnings</h3>
            <div class="li"><span>Base salary</span><span class="a">₭ <?= kip($base) ?></span></div>
            <div class="li"><span>Overtime<?= (float)$s['ot_hours']>0 ? ' ('.rtrim(rtrim(number_format((float)$s['ot_hours'],1),'0'),'.').'h)' : '' ?></span><span class="a">₭ <?= kip($ot) ?></span></div>
            <div class="li"><span>Allowances</span><span class="a">₭ <?= kip($allow) ?></span></div>
            <div class="sum"><span>Gross</span><span>₭ <?= kip($gross) ?></span></div>
        </div>
        <div class="box ded">
            <h3>Deductions</h3>
            <div class="li"><span>Late<?= (int)($s['late_minutes']??0)>0 ? ' ('.(int)$s['late_minutes'].'′)' : '' ?></span><span class="a">₭ <?= kip($late) ?></span></div>
            <div class="li"><span>Absence<?= (int)($s['days_absent']??0)>0 ? ' ('.(int)$s['days_absent'].'d)' : '' ?></span><span class="a">₭ <?= kip($absd) ?></span></div>
            <div class="li"><span>Loan repayment</span><span class="a">₭ <?= kip($loan) ?></span></div>
            <?php if ($other>0): ?><div class="li"><span>Other</span><span class="a">₭ <?= kip($other) ?></span></div><?php endif; ?>
            <div class="sum"><span>Total</span><span>₭ <?= kip($totalDed) ?></span></div>
        </div>
    </div>

    <div class="net">
        <span class="l">Net Pay / ເງິນເດືອນສຸດທິ</span>
        <span class="v">₭ <?= kip($net) ?></span>
    </div>

    <div class="sign">
        <div class="s">Employee signature</div>
        <div class="s">Authorised by</div>
    </div>

    <div class="foot">Generated <?= date('d/m/Y H:i') ?> · <?= htmlspecialchars($companyName) ?> · Powered by Seven Digital</div>
</div>
<?php endforeach; ?>

<script>
window.addEventListener('load', function(){ setTimeout(function(){ window.print(); }, 400); });
</script>
</body>
</html>