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

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    verifyCsrf();
    $action = $_POST["action"] ?? "";
    if ($action === "setup") {
        // FIX (07 Jul 2026): this had no role check — any logged-in
        // employee could change the ESI contribution rates for everyone.
        requireRole('superadmin','admin','hr','management');
        $db->execute("UPDATE esi_setup SET employee_rate=?,employer_rate=?,wage_ceiling=?,is_active=1 WHERE id=1",
            [post("emp_pct"),post("er_pct"),post("ceiling")]);
        setFlash("success","ESI setup updated.");
    }
    header("Location: ".BASE_URL."/modules/statutory/esi.php"); exit;
}

$setup    = $db->fetchOne("SELECT * FROM esi_setup");
$month    = intval($_GET["month"] ?? date("n"));
$year     = intval($_GET["year"]  ?? date("Y"));
// FIX: scope to current org.
[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
$details  = $db->fetchAll("SELECT pd.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name,e.employee_id AS emp_code,e.esic_number FROM payroll_details pd JOIN employees e ON e.id=pd.employee_id JOIN payroll_runs pr ON pr.id=pd.payroll_run_id WHERE pr.month=? AND pr.year=? AND pd.esi_employee>0 AND $orgClause ORDER BY e.first_name", array_merge([$month,$year], $orgParams));
$totals   = ["emp"=>0,"er"=>0,"gross"=>0];
foreach($details as $d) { $totals["emp"]+=$d["esi_employee"]; $totals["er"]+=$d["esi_employer"]; $totals["gross"]+=$d["gross_salary"]; }

include __DIR__ . "/../../includes/header.php";
?>
<div class="row g-3 mb-3">
  <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon blue" style="width:42px;height:42px;font-size:20px"><i class="ti ti-users"></i></div><div class="pc-stat-val"><?=count($details)?></div><div class="pc-stat-label">ESI Employees</div></div></div>
  <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon green" style="width:42px;height:42px;font-size:20px"><i class="ti ti-user"></i></div><div class="pc-stat-val">₹<?=number_format($totals["emp"],0)?></div><div class="pc-stat-label">Employee Share</div></div></div>
  <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon amber" style="width:42px;height:42px;font-size:20px"><i class="ti ti-building"></i></div><div class="pc-stat-val">₹<?=number_format($totals["er"],0)?></div><div class="pc-stat-label">Employer Share</div></div></div>
  <div class="col-md-3"><div class="pc-stat"><div class="pc-stat-icon brand" style="width:42px;height:42px;font-size:20px"><i class="ti ti-cash"></i></div><div class="pc-stat-val">₹<?=number_format($totals["emp"]+$totals["er"],0)?></div><div class="pc-stat-label">Total Contribution</div></div></div>
</div>

<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-settings me-2"></i>ESI Configuration</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="setup">
        <div class="mb-2"><label class="pc-label">Employee Contribution (%)</label><input type="number" name="emp_pct" class="form-control form-control-sm" step="0.01" value="<?=$setup["employee_rate"]??0.75?>" required></div>
        <div class="mb-2"><label class="pc-label">Employer Contribution (%)</label><input type="number" name="er_pct" class="form-control form-control-sm" step="0.01" value="<?=$setup["employer_rate"]??3.25?>" required></div>
        <div class="mb-3"><label class="pc-label">Wage Ceiling (₹)</label><input type="number" name="ceiling" class="form-control form-control-sm" value="<?=$setup["wage_ceiling"]??21000?>" required></div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-device-floppy me-1"></i>Save Setup</button>
      </form>
    </div>
    <div class="pc-card">
      <div class="pc-card-title">Current Rates</div>
      <div class="d-flex justify-content-between py-2 border-bottom small"><span class="text-muted">Employee Share</span><span class="fw-bold"><?=$setup["employee_rate"]??0.75?>%</span></div>
      <div class="d-flex justify-content-between py-2 border-bottom small"><span class="text-muted">Employer Share</span><span class="fw-bold"><?=$setup["employer_rate"]??3.25?>%</span></div>
      <div class="d-flex justify-content-between py-2 small"><span class="text-muted">Wage Ceiling</span><span class="fw-bold">₹<?=number_format($setup["wage_ceiling"]??21000)?></span></div>
    </div>
  </div>
  <div class="col-md-8">
    <div class="pc-card mb-2">
      <form method="GET" class="d-flex gap-2">
        <div><label class="pc-label">Month</label><select name="month" class="form-select form-select-sm"><?php for($m=1;$m<=12;$m++): ?><option value="<?=$m?>" <?=$month==$m?"selected":""?>><?=date("F",mktime(0,0,0,$m,1))?></option><?php endfor; ?></select></div>
        <div><label class="pc-label">Year</label><select name="year" class="form-select form-select-sm"><?php for($y=date("Y");$y>=date("Y")-3;$y--): ?><option value="<?=$y?>" <?=$year==$y?"selected":""?>><?=$y?></option><?php endfor; ?></select></div>
        <button class="btn btn-pc btn-sm align-self-end"><i class="ti ti-search me-1"></i>View</button>
        <?php if($details): ?><a href="?month=<?=$month?>&year=<?=$year?>&export=1" class="btn btn-sm btn-outline-secondary align-self-end"><i class="ti ti-download me-1"></i>ECR File</a><?php endif; ?>
      </form>
    </div>
    <div class="pc-card">
      <div class="pc-card-title">ESI Register — <?=date("F",mktime(0,0,0,$month,1))?> <?=$year?></div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Employee</th><th>ESIC No.</th><th>Gross Wages</th><th>Emp Share (<?=$setup["employee_rate"]??0.75?>%)</th><th>ER Share (<?=$setup["employer_rate"]??3.25?>%)</th><th>Total</th></tr></thead>
          <tbody>
          <?php foreach($details as $d): ?>
          <tr>
            <td><div class="fw-semibold"><?=clean($d["emp_name"])?></div><small class="text-muted"><?=clean($d["emp_code"])?></small></td>
            <td><?=clean($d["esic_number"]??"—")?></td>
            <td>₹<?=number_format($d["gross_salary"],2)?></td>
            <td>₹<?=number_format($d["esi_employee"],2)?></td>
            <td>₹<?=number_format($d["esi_employer"],2)?></td>
            <td class="fw-bold">₹<?=number_format($d["esi_employee"]+$d["esi_employer"],2)?></td>
          </tr>
          <?php endforeach; if(!$details): ?>
          <tr><td colspan="6" class="text-center text-muted py-3">No ESI data for selected period</td></tr>
          <?php endif; ?>
          </tbody>
          <?php if($details): ?>
          <tfoot><tr style="background:var(--pc-brand-light);font-weight:700">
            <td colspan="2">Total</td>
            <td>₹<?=number_format($totals["gross"],2)?></td>
            <td>₹<?=number_format($totals["emp"],2)?></td>
            <td>₹<?=number_format($totals["er"],2)?></td>
            <td>₹<?=number_format($totals["emp"]+$totals["er"],2)?></td>
          </tr></tfoot>
          <?php endif; ?>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . "/../../includes/footer.php"; ?>