<?php
include "auth.php";
checkPermission(['admin','manager']);
require_once "db.php";

$id = (int)($_GET['advance_id'] ?? 0);
if($id <= 0){ die("Invalid Request"); }

$sql = "
SELECT 
    ap.*,
    e.employee_name,
    e.phone,
    d.title AS designation
FROM advance_pay ap
JOIN employees e ON e.employee_id = ap.employee_id
LEFT JOIN designation d ON d.designation_id = e.designation_id
WHERE ap.advance_id = $id
";

$res = $conn->query($sql);
if(!$res || $res->num_rows==0){
    die("Record not found");
}

$row = $res->fetch_assoc();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Advance Pay Slip</title>

<style>
body{
    font-family: Arial, sans-serif;
    font-size:14px;
}
.print-box{
    max-width:700px;
    margin:auto;
    padding:20px;
    margin-top: 30px;
}
h2{
    text-align:center;
    margin-bottom:5px;
}
p.center{
    text-align:center;
    margin-top:0;
    font-size:13px;
}
table{
    width:100%;
    border-collapse:collapse;
    margin-top:15px;
}
td{
    padding:8px;
    border:1px solid #000;
}
.label{
    font-weight:bold;
    width:35%;
}
.footer{
    margin-top:40px;
    display:flex;
    justify-content:space-between;
}
.signature{
    width:45%;
    text-align:center;
}
.signature div{
    border-top:1px solid #000;
    margin-top:40px;
}
@media print{
    button{display:none;}
}
</style>
</head>

<body onload="window.print()" class="global-print">
    <?php
    include("global/global-print-heading.php");
?>

<div class="print-box">
    <h2>Advance Payment Slip</h2>
    <p class="center">Generated on <?= date('d M Y') ?></p>

    <table>
        <tr>
            <td class="label">Employee Name</td>
            <td><?= htmlspecialchars($row['employee_name']) ?></td>
        </tr>
        <tr>
            <td class="label">Designation</td>
            <td><?= htmlspecialchars($row['designation']) ?></td>
        </tr>
        <tr>
            <td class="label">Phone</td>
            <td><?= htmlspecialchars($row['phone']) ?></td>
        </tr>
        <tr>
            <td class="label">Advance Amount</td>
            <td><?= number_format($row['amount'],2) ?></td>
        </tr>
        <tr>
            <td class="label">Payment Date</td>
            <td><?= htmlspecialchars($row['advance_date'] ?? ''); ?></td>
        </tr>
        <tr>
            <td class="label">Note</td>
            <td><?= nl2br(htmlspecialchars($row['note'])) ?></td>
        </tr>
    </table>

    <div class="footer">
        <div class="signature">
            <div>Employee Signature</div>
        </div>
        <div class="signature">
            <div>Authorized Signature</div>
        </div>
    </div>
</div>
<?php
    include("global/global-print-footer.php");
?>

</body>
</html>
