<?php
require_once __DIR__ . "/../../config/config.php";
require_once __DIR__ . "/../../includes/functions.php";
startSession(); requireLogin();
$db = Database::getInstance();
$page = "Form 16";

$fy        = $_GET["fy"] ?? (date("Y")."-".(date("Y")+1));
$selEmp    = cleanInt($_GET["emp"] ?? 0);
// FIX (07 Jul 2026): Form 16 exposes PAN/Aadhaar — scope the dropdown to
// the current org and reject ?emp=<other org's employee>.
[$orgClause, $orgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id,CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $orgClause ORDER BY first_name", $orgParams);
if ($selEmp && !in_array($selEmp, array_column($employees, 'id'))) { $selEmp = 0; }

$empData = null; $tdsRows = []; $totalTDS = 0; $totalIncome = 0;
if($selEmp) {
    $empData = $db->fetchOne("SELECT e.*,CONCAT(e.first_name,' ',e.last_name) AS full_name FROM employees e WHERE e.id=?",[$selEmp]);
    $tdsRows = $db->fetchAll("SELECT * FROM tds_calculations WHERE employee_id=? AND financial_year=? ORDER BY month",[$selEmp,$fy]);
    foreach($tdsRows as $r) { $totalTDS += $r["tds_this_month"]; $totalIncome += $r["gross_income"]; }
}
$decls = $selEmp ? $db->fetchAll("SELECT d.*,t.section,t.name AS head_name FROM investment_declarations d JOIN tds_heads t ON t.id=d.tds_head_id WHERE d.employee_id=? AND d.financial_year=? AND d.status='verified'",[$selEmp,$fy]) : [];
$totalDecl = array_sum(array_column($decls,"declared_amount"));

include __DIR__ . "/../../includes/header.php";
?>
<div class="pc-card mb-3">
  <form method="GET" class="d-flex gap-2">
    <div><label class="pc-label">Employee</label><select name="emp" class="form-select form-select-sm" style="width:260px"><option value="">Select</option><?php foreach($employees as $e): ?><option value="<?=$e["id"]?>" <?=$selEmp==$e["id"]?"selected":""?>><?=clean($e["label"])?></option><?php endforeach; ?></select></div>
    <div><label class="pc-label">Financial Year</label><select name="fy" class="form-select form-select-sm"><?php for($y=date("Y");$y>=date("Y")-3;$y--): $o=$y."-".($y+1); ?><option value="<?=$o?>" <?=$fy===$o?"selected":""?>><?=$o?></option><?php endfor; ?></select></div>
    <button class="btn btn-pc btn-sm align-self-end">Generate</button>
  </form>
</div>

<?php if($empData && $tdsRows): ?>
<!-- Form 16 Preview -->
<div class="pc-card" id="form16Print">
  <div class="pc-payslip-header d-flex justify-content-between align-items-start">
    <div><h5 class="mb-1 fw-bold">FORM 16 — Certificate of Tax Deducted at Source</h5><div class="opacity-75 small">Under Section 203 of the Income Tax Act, 1961</div></div>
    <div class="text-end opacity-90 small">FY: <?=clean($fy)?><br>AY: <?=(intval(explode("-",$fy)[1])+1)."-".(intval(explode("-",$fy)[1])+2)?></div>
  </div>
  <div class="pc-payslip-body">
    <div class="row g-3 mb-3">
      <div class="col-md-6"><div class="pc-section-divider">Employee Details</div>
        <?php foreach([["Name",$empData["full_name"]],["Employee ID",$empData["employee_id"]],["PAN",$empData["pan_number"]??"—"],["Aadhaar",$empData["aadhaar_number"]??"—"]] as [$k,$v]): ?>
        <div class="pc-payslip-row"><span class="text-muted"><?=$k?></span><span><?=clean($v)?></span></div>
        <?php endforeach; ?>
      </div>
      <div class="col-md-6"><div class="pc-section-divider">Summary</div>
        <div class="pc-payslip-row"><span class="text-muted">Gross Income</span><span class="fw-bold">₹<?=number_format($totalIncome,2)?></span></div>
        <div class="pc-payslip-row"><span class="text-muted">Total Deductions</span><span class="fw-bold">₹<?=number_format($totalDecl,2)?></span></div>
        <div class="pc-payslip-row"><span class="text-muted">Net Taxable</span><span class="fw-bold">₹<?=number_format($totalIncome-$totalDecl,2)?></span></div>
        <div class="pc-payslip-total"><span>Total TDS Deducted</span><span>₹<?=number_format($totalTDS,2)?></span></div>
      </div>
    </div>
    <div class="pc-section-divider">Month-wise TDS</div>
    <table class="pc-table"><thead><tr><th>Month</th><th>Gross</th><th>Taxable Income</th><th>Tax Liability</th><th>TDS This Month</th><th>TDS YTD</th></tr></thead>
    <tbody><?php $mNames=["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; foreach($tdsRows as $r): ?>
    <tr><td><?=$mNames[$r["month"]]." ".$r["year"]?></td><td>₹<?=number_format($r["gross_income"],2)?></td><td>₹<?=number_format($r["net_taxable_income"],2)?></td><td>₹<?=number_format($r["tax_liability"],2)?></td><td class="fw-bold">₹<?=number_format($r["tds_this_month"],2)?></td><td>₹<?=number_format($r["tds_deducted_ytd"],2)?></td></tr>
    <?php endforeach; ?></tbody></table>
    <?php if($decls): ?>
    <div class="pc-section-divider">Investment Declarations</div>
    <?php foreach($decls as $d): ?><div class="pc-payslip-row"><span><code><?=clean($d["section"])?></code> <?=clean($d["head_name"])?></span><span>₹<?=number_format($d["declared_amount"],2)?></span></div><?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>
<div class="mt-3"><button onclick="window.print()" class="btn btn-pc btn-sm"><i class="ti ti-printer me-1"></i>Print Form 16</button></div>
<?php elseif($selEmp): ?><div class="alert alert-info">No TDS data found for FY <?=clean($fy)?>.</div><?php endif; ?>
<?php include __DIR__ . "/../../includes/footer.php"; ?>