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

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    verifyCsrf();
    $action = post("action") ?: "save";

    if ($action === "delete") {
        $id = postInt("id");
        // Don't allow deleting a head that's already used by an ADB rule —
        // that would leave the rule pointing at nothing.
        $inUse = $db->fetchValue("SELECT COUNT(*) FROM adb_rules WHERE tds_head_id=?", [$id]);
        if ($inUse > 0) {
            setFlash("error", "Can't delete — this section is used by $inUse ADB rule(s). Delete those first.");
        } else {
            $db->execute("DELETE FROM tds_heads WHERE id=?", [$id]);
            setFlash("success", "TDS head deleted.");
        }
        header("Location: " . BASE_URL . "/modules/tds/tds_heads.php"); exit;
    }

    $id = postInt("id");
    if ($id) $db->execute("UPDATE tds_heads SET section=?,name=?,max_limit=?,is_old_regime=?,is_new_regime=?,description=?,is_active=? WHERE id=?",
        [post("section"),post("name"),post("max_limit"),postInt("old_regime"),postInt("new_regime"),post("description"),postInt("is_active"),$id]);
    else $db->execute("INSERT INTO tds_heads (section,name,max_limit,is_old_regime,is_new_regime,description,is_active) VALUES (?,?,?,?,?,?,?)",
        [post("section"),post("name"),post("max_limit"),postInt("old_regime"),postInt("new_regime"),post("description"),1]);
    setFlash("success","TDS head saved.");
    header("Location: ".BASE_URL."/modules/tds/tds_heads.php"); exit;
}

$editId = cleanInt($_GET["edit"]??0);
$edit   = $editId ? $db->fetchOne("SELECT * FROM tds_heads WHERE id=?",[$editId]) : null;
$heads  = $db->fetchAll("SELECT * FROM tds_heads ORDER BY section,name");

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-list-details me-2"></i><?=$edit?"Edit":"Add"?> TDS Head</div>
      <form method="POST">
        <?=csrfField()?>
        <?php if($edit): ?><input type="hidden" name="id" value="<?=$edit["id"]?>"><?php endif; ?>
        <div class="mb-2"><label class="pc-label">Section</label><input type="text" name="section" class="form-control form-control-sm" value="<?=clean($edit["section"]??"")?>" placeholder="80C" required></div>
        <div class="mb-2"><label class="pc-label">Name / Description</label><input type="text" name="name" class="form-control form-control-sm" value="<?=clean($edit["name"]??"")?>" required></div>
        <div class="mb-2"><label class="pc-label">Max Limit (₹, 0=unlimited)</label><input type="number" name="max_limit" class="form-control form-control-sm" value="<?=$edit["max_limit"]??0?>"></div>
        <div class="mb-2"><label class="pc-label">Details / Notes</label><textarea name="description" class="form-control form-control-sm" rows="2"><?=clean($edit["description"]??"")?></textarea></div>
        <div class="row g-2 mb-3">
          <div class="col form-check ps-4"><input type="checkbox" name="old_regime" value="1" class="form-check-input" id="or" <?=($edit["is_old_regime"]??1)?"checked":""?>><label class="form-check-label small" for="or">Old Regime</label></div>
          <div class="col form-check ps-4"><input type="checkbox" name="new_regime" value="1" class="form-check-input" id="nr" <?=($edit["is_new_regime"]??0)?"checked":""?>><label class="form-check-label small" for="nr">New Regime</label></div>
          <div class="col form-check ps-4"><input type="checkbox" name="is_active" value="1" class="form-check-input" id="ia" <?=($edit["is_active"]??1)?"checked":""?>><label class="form-check-label small" for="ia">Active</label></div>
        </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">
      <div class="pc-card-title">All TDS Sections</div>
      <table class="pc-table">
        <thead><tr><th>Section</th><th>Name</th><th>Max Limit</th><th>Old</th><th>New</th><th>Status</th><th></th></tr></thead>
        <tbody>
        <?php foreach($heads as $h): ?>
        <tr>
          <td><code class="fw-bold"><?=clean($h["section"])?></code></td>
          <td><?=clean($h["name"])?></td>
          <td><?=$h["max_limit"]>0?"₹".number_format($h["max_limit"]):"Unlimited"?></td>
          <td><?=$h["is_old_regime"]?'<i class="ti ti-check text-success"></i>':"—"?></td>
          <td><?=$h["is_new_regime"]?'<i class="ti ti-check text-success"></i>':"—"?></td>
          <td><?=statusBadge($h["is_active"]?"active":"inactive")?></td>
          <td class="text-nowrap">
            <a href="?edit=<?=$h["id"]?>" class="btn btn-xs btn-outline-primary py-0 px-1">Edit</a>
            <form method="POST" class="d-inline" onsubmit="return confirm('Delete this TDS head?')">
              <?=csrfField()?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=$h["id"]?>">
              <button class="btn btn-xs btn-outline-danger py-0 px-1">Del</button>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php include __DIR__ . "/../../includes/footer.php"; ?>