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

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    verifyCsrf();
    $action = $_POST["action"] ?? "";
    if ($action === "save") {
        $id = postInt("id");
        if ($id) $db->execute("UPDATE tax_slabs SET financial_year=?,regime=?,income_from=?,income_to=?,tax_rate=?,is_active=? WHERE id=?",
            [post("fy"),post("regime"),post("income_from"),post("income_to"),post("tax_rate"),postInt("is_active"),$id]);
        else $db->execute("INSERT INTO tax_slabs (financial_year,regime,income_from,income_to,tax_rate,is_active) VALUES (?,?,?,?,?,?)",
            [post("fy"),post("regime"),post("income_from"),post("income_to"),post("tax_rate"),1]);
        setFlash("success","Tax slab saved.");
    } elseif ($action === "delete") {
        $db->execute("DELETE FROM tax_slabs WHERE id=?", [postInt("id")]);
        setFlash("success","Deleted.");
    }
    header("Location: ".BASE_URL."/modules/tds/tax_slab.php"); exit;
}

$editId = cleanInt($_GET["edit"]??0);
$edit   = $editId ? $db->fetchOne("SELECT * FROM tax_slabs WHERE id=?",[$editId]) : null;
$slabs  = $db->fetchAll("SELECT * FROM tax_slabs ORDER BY financial_year DESC,regime,income_from");
$fys    = $db->fetchAll("SELECT DISTINCT financial_year FROM tax_slabs ORDER BY financial_year DESC");
$selFY  = $_GET["fy"] ?? ($fys[0]["financial_year"] ?? date("Y")."-".(date("Y")+1));
$byRegime = ["new"=>[],"old"=>[]];
foreach($slabs as $s) if($s["financial_year"]===$selFY) $byRegime[$s["regime"]][] = $s;

include __DIR__ . "/../../includes/header.php";
?>
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-percentage me-2"></i><?=$edit?"Edit":"Add"?> Tax Slab</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="save">
        <?php if($edit): ?><input type="hidden" name="id" value="<?=$edit["id"]?>"><?php endif; ?>
        <div class="mb-2"><label class="pc-label">Financial Year</label><input type="text" name="fy" class="form-control form-control-sm" value="<?=clean($edit["financial_year"]??$selFY)?>" placeholder="2026-27" required></div>
        <div class="mb-2"><label class="pc-label">Regime</label>
          <select name="regime" class="form-select form-select-sm"><option value="new" <?=($edit["regime"]??"")==="new"?"selected":""?>>New Regime</option><option value="old" <?=($edit["regime"]??"")==="old"?"selected":""?>>Old Regime</option></select></div>
        <div class="mb-2"><label class="pc-label">Income From (₹)</label><input type="number" name="income_from" class="form-control form-control-sm" value="<?=$edit["income_from"]??0?>" required></div>
        <div class="mb-2"><label class="pc-label">Income To (₹)</label><input type="number" name="income_to" class="form-control form-control-sm" value="<?=$edit["income_to"]??0?>" required></div>
        <div class="mb-2"><label class="pc-label">Tax Rate (%)</label><input type="number" name="tax_rate" class="form-control form-control-sm" step="0.01" value="<?=$edit["tax_rate"]??0?>" required></div>
        <div class="mb-3 form-check"><input type="checkbox" name="is_active" value="1" class="form-check-input" id="a" <?=($edit["is_active"]??1)?"checked":""?>><label class="form-check-label small" for="a">Active</label></div>
        <div class="d-flex gap-2"><button class="btn btn-pc btn-sm flex-fill">Save</button><?php if($edit): ?><a href="?" class="btn btn-outline-secondary btn-sm">Cancel</a><?php endif; ?></div>
      </form>
    </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">FY</label>
        <select name="fy" class="form-select form-select-sm" onchange="this.form.submit()">
          <?php foreach($fys as $f): ?><option value="<?=$f["financial_year"]?>" <?=$selFY===$f["financial_year"]?"selected":""?>><?=$f["financial_year"]?></option><?php endforeach; ?>
        </select></div></form>
    </div>
    <?php foreach(["new"=>"New Regime (FY $selFY)","old"=>"Old Regime (FY $selFY)"] as $regime=>$label): ?>
    <div class="pc-card mb-3">
      <div class="pc-card-title"><?=$label?></div>
      <table class="pc-table">
        <thead><tr><th>Income Range</th><th>Tax Rate</th><th>Status</th><th></th></tr></thead>
        <tbody>
        <?php foreach($byRegime[$regime] as $s): ?>
        <tr>
          <td>₹<?=number_format($s["income_from"])?> – <?=$s["income_to"]>=99999999?"Above":"₹".number_format($s["income_to"])?></td>
          <td class="fw-bold"><?=$s["tax_rate"]?>%</td>
          <td><?=statusBadge($s["is_active"]?"active":"inactive")?></td>
          <td>
            <a href="?edit=<?=$s["id"]?>&fy=<?=$selFY?>" class="btn btn-xs btn-outline-primary py-0 px-1">Edit</a>
            <form method="POST" class="d-inline" onsubmit="return confirm('Delete?')">
              <?=csrfField()?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=$s["id"]?>">
              <button class="btn btn-xs btn-outline-danger py-0 px-1">Del</button>
            </form>
          </td>
        </tr>
        <?php endforeach; if(!$byRegime[$regime]): ?><tr><td colspan="4" class="text-center text-muted">No slabs</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<?php include __DIR__ . "/../../includes/footer.php"; ?>
