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

// ADB = Automatic Deduction at Basis — configure TDS auto-rules
$heads = $db->fetchAll("SELECT * FROM tds_heads WHERE is_active=1 ORDER BY section");
// FIX (07 Jul 2026): scope to current org.
[$orgClause, $orgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id,CONCAT(employee_id,' - ',first_name,' ',last_name) AS label,tax_regime FROM employees WHERE status='active' AND $orgClause ORDER BY first_name", $orgParams);
$orgEmpIds = array_column($employees, 'id');

// ── ADB Rule CRUD (30 Jul 2026): actual create/edit/delete for rules ──
[$ruleOrgClause, $ruleOrgParams] = orgScopeClause($db, 'company_id');

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["rule_action"])) {
    verifyCsrf();
    $ruleAction = $_POST["rule_action"];

    if ($ruleAction === "save") {
        $applicableTo = post("applicable_to");
        $basisType    = post("basis_type");
        $data = [
            "company_id"     => companyId(),
            "tds_head_id"    => postInt("tds_head_id"),
            "name"           => post("name"),
            "applicable_to"  => $applicableTo,
            "category_id"    => $applicableTo === "category" ? postInt("category_id") : null,
            "grade_id"       => $applicableTo === "grade" ? postInt("grade_id") : null,
            "basis_type"     => $basisType,
            "flat_amount"    => $basisType === "flat" ? (float)post("flat_amount") : 0,
            "percentage"     => $basisType === "percentage" ? (float)post("percentage") : 0,
            "salary_head_id" => $basisType === "percentage" ? postInt("salary_head_id") : null,
            "financial_year" => post("financial_year"),
            "is_active"      => postInt("is_active"),
        ];
        $id = postInt("rule_id");
        if ($id) {
            // Confirm this rule belongs to the current org before editing it
            $owned = $db->fetchOne("SELECT id FROM adb_rules WHERE id=? AND $ruleOrgClause", array_merge([$id], $ruleOrgParams));
            if (!$owned) { setFlash("error", "Rule not found."); header("Location: " . BASE_URL . "/modules/tds/adb_rules.php"); exit; }
            $set = implode(",", array_map(fn($k) => "$k=?", array_keys($data)));
            $db->execute("UPDATE adb_rules SET $set WHERE id=?", array_merge(array_values($data), [$id]));
            setFlash("success", "ADB rule updated.");
        } else {
            $db->insertRow("adb_rules", $data);
            setFlash("success", "ADB rule created.");
        }
    } elseif ($ruleAction === "delete") {
        $id = postInt("rule_id");
        $owned = $db->fetchOne("SELECT id FROM adb_rules WHERE id=? AND $ruleOrgClause", array_merge([$id], $ruleOrgParams));
        if ($owned) {
            $db->execute("DELETE FROM adb_rules WHERE id=?", [$id]);
            setFlash("success", "ADB rule deleted.");
        } else {
            setFlash("error", "Rule not found.");
        }
    }
    header("Location: " . BASE_URL . "/modules/tds/adb_rules.php"); exit;
}

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["regime_update"])) {
    verifyCsrf();
    // FIX: only update employees that actually belong to this org —
    // otherwise a tampered form could target another org's employee ids.
    foreach (($_POST["regime"] ?? []) as $empId => $regime) {
        if (!in_array((int)$empId, $orgEmpIds)) continue;
        $db->execute("UPDATE employees SET tax_regime=? WHERE id=?", [$regime, $empId]);
    }
    setFlash("success", "Regime assignments saved."); header("Location: " . BASE_URL . "/modules/tds/adb_rules.php"); exit;
}

$ruleEditId = cleanInt($_GET["edit"] ?? 0);
$ruleEdit   = $ruleEditId ? $db->fetchOne("SELECT * FROM adb_rules WHERE id=? AND $ruleOrgClause", array_merge([$ruleEditId], $ruleOrgParams)) : null;
$rules      = $db->fetchAll(
    "SELECT ar.*, th.section, th.name AS head_name, c.name AS category_name, g.name AS grade_name, sh.name AS salary_head_name
       FROM adb_rules ar
       LEFT JOIN tds_heads th ON th.id = ar.tds_head_id
       LEFT JOIN categories c ON c.id = ar.category_id
       LEFT JOIN grades g ON g.id = ar.grade_id
       LEFT JOIN salary_heads sh ON sh.id = ar.salary_head_id
      WHERE ar.$ruleOrgClause ORDER BY ar.financial_year DESC, ar.name",
    $ruleOrgParams
);
$categories  = $db->fetchAll("SELECT id,name FROM categories WHERE is_active=1 ORDER BY name");
$grades      = $db->fetchAll("SELECT id,name FROM grades WHERE is_active=1 ORDER BY name");
$salaryHeads = $db->fetchAll("SELECT id,name FROM salary_heads WHERE is_active=1 ORDER BY name");
$curFY       = date('n') >= 4 ? date('Y') . '-' . substr(date('Y') + 1, 2) : (date('Y') - 1) . '-' . substr(date('Y'), 2);

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-adjustments me-2"></i><?= $ruleEdit ? "Edit" : "Add" ?> ADB Rule</div>
      <p class="text-muted small mb-3">Automatically applies a TDS-section deduction to matching employees during TDS calculation — either a fixed amount or a % of a chosen salary head.</p>
      <form method="POST">
        <?= csrfField() ?><input type="hidden" name="rule_action" value="save">
        <?php if ($ruleEdit): ?><input type="hidden" name="rule_id" value="<?= $ruleEdit["id"] ?>"><?php endif; ?>

        <div class="mb-2"><label class="pc-label">Rule Name</label>
          <input type="text" name="name" class="form-control form-control-sm" placeholder="e.g. Standard 80C for all staff" value="<?= clean($ruleEdit["name"] ?? "") ?>" required>
        </div>

        <div class="mb-2"><label class="pc-label">TDS Section</label>
          <select name="tds_head_id" class="form-select form-select-sm" required>
            <option value="">Select section</option>
            <?php foreach ($heads as $h): ?>
              <option value="<?= $h["id"] ?>" <?= ($ruleEdit["tds_head_id"] ?? "") == $h["id"] ? "selected" : "" ?>><?= clean($h["section"]) ?> — <?= clean($h["name"]) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="mb-2"><label class="pc-label">Financial Year</label>
          <input type="text" name="financial_year" class="form-control form-control-sm" placeholder="2026-27" value="<?= clean($ruleEdit["financial_year"] ?? $curFY) ?>" required>
        </div>

        <div class="mb-2"><label class="pc-label">Applicable To</label>
          <select name="applicable_to" id="applicableTo" class="form-select form-select-sm" onchange="pcAdbToggleScope()">
            <option value="all" <?= ($ruleEdit["applicable_to"] ?? "all") === "all" ? "selected" : "" ?>>All Employees</option>
            <option value="category" <?= ($ruleEdit["applicable_to"] ?? "") === "category" ? "selected" : "" ?>>Specific Category</option>
            <option value="grade" <?= ($ruleEdit["applicable_to"] ?? "") === "grade" ? "selected" : "" ?>>Specific Grade</option>
          </select>
        </div>
        <div class="mb-2" id="scopeCategory" style="display:none">
          <label class="pc-label">Category</label>
          <select name="category_id" class="form-select form-select-sm">
            <?php foreach ($categories as $c): ?><option value="<?= $c["id"] ?>" <?= ($ruleEdit["category_id"] ?? "") == $c["id"] ? "selected" : "" ?>><?= clean($c["name"]) ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="mb-2" id="scopeGrade" style="display:none">
          <label class="pc-label">Grade</label>
          <select name="grade_id" class="form-select form-select-sm">
            <?php foreach ($grades as $g): ?><option value="<?= $g["id"] ?>" <?= ($ruleEdit["grade_id"] ?? "") == $g["id"] ? "selected" : "" ?>><?= clean($g["name"]) ?></option><?php endforeach; ?>
          </select>
        </div>

        <div class="mb-2"><label class="pc-label">Basis</label>
          <select name="basis_type" id="basisType" class="form-select form-select-sm" onchange="pcAdbToggleBasis()">
            <option value="flat" <?= ($ruleEdit["basis_type"] ?? "flat") === "flat" ? "selected" : "" ?>>Fixed Amount</option>
            <option value="percentage" <?= ($ruleEdit["basis_type"] ?? "") === "percentage" ? "selected" : "" ?>>% of Salary Head</option>
          </select>
        </div>
        <div class="mb-2" id="basisFlat">
          <label class="pc-label">Amount (₹)</label>
          <input type="number" step="0.01" name="flat_amount" class="form-control form-control-sm" value="<?= $ruleEdit["flat_amount"] ?? 0 ?>">
        </div>
        <div class="mb-2" id="basisPct" style="display:none">
          <label class="pc-label">Percentage (%)</label>
          <input type="number" step="0.01" name="percentage" class="form-control form-control-sm" value="<?= $ruleEdit["percentage"] ?? 0 ?>">
          <label class="pc-label mt-2">Of Salary Head</label>
          <select name="salary_head_id" class="form-select form-select-sm">
            <?php foreach ($salaryHeads as $sh): ?><option value="<?= $sh["id"] ?>" <?= ($ruleEdit["salary_head_id"] ?? "") == $sh["id"] ? "selected" : "" ?>><?= clean($sh["name"]) ?></option><?php endforeach; ?>
          </select>
        </div>

        <div class="mb-3 form-check">
          <input type="checkbox" name="is_active" value="1" class="form-check-input" id="raIsActive" <?= ($ruleEdit["is_active"] ?? 1) ? "checked" : "" ?>>
          <label class="form-check-label small" for="raIsActive">Active</label>
        </div>

        <div class="d-flex gap-2">
          <button class="btn btn-pc btn-sm flex-fill">Save Rule</button>
          <?php if ($ruleEdit): ?><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">ADB Rules</div>
      <table class="pc-table">
        <thead><tr><th>Name</th><th>Section</th><th>Applies To</th><th>Basis</th><th>FY</th><th>Status</th><th></th></tr></thead>
        <tbody>
        <?php foreach ($rules as $r): ?>
        <tr>
          <td><?= clean($r["name"]) ?></td>
          <td><code><?= clean($r["section"] ?? "-") ?></code></td>
          <td><?= $r["applicable_to"] === "all" ? "All Employees" : ($r["applicable_to"] === "category" ? "Category: " . clean($r["category_name"] ?? "-") : "Grade: " . clean($r["grade_name"] ?? "-")) ?></td>
          <td><?= $r["basis_type"] === "flat" ? "₹" . number_format($r["flat_amount"], 2) : $r["percentage"] . "% of " . clean($r["salary_head_name"] ?? "-") ?></td>
          <td><?= clean($r["financial_year"]) ?></td>
          <td><?= statusBadge($r["is_active"] ? "active" : "inactive") ?></td>
          <td class="text-nowrap">
            <a href="?edit=<?= $r["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 ADB rule?')">
              <?= csrfField() ?><input type="hidden" name="rule_action" value="delete"><input type="hidden" name="rule_id" value="<?= $r["id"] ?>">
              <button class="btn btn-xs btn-outline-danger py-0 px-1">Del</button>
            </form>
          </td>
        </tr>
        <?php endforeach; if (!$rules): ?><tr><td colspan="7" class="text-center text-muted">No ADB rules yet — add one on the left.</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="row g-3 mt-1">
  <div class="col-md-6">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-settings-2 me-2"></i>TDS Regime Assignment</div>
      <p class="text-muted small mb-3">Assign Old or New tax regime to employees. This controls which deductions apply during TDS calculation.</p>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="regime_update" value="1">
        <table class="pc-table">
          <thead><tr><th>Employee</th><th>Current Regime</th><th>Change To</th></tr></thead>
          <tbody>
          <?php foreach($employees as $e): ?>
          <tr>
            <td><?=clean($e["label"])?></td>
            <td><?=statusBadge($e["tax_regime"]==="new"?"active":"pending")?> <?=ucfirst($e["tax_regime"])?></td>
            <td><select name="regime[<?=$e["id"]?>]" class="form-select form-select-sm"><option value="new" <?=$e["tax_regime"]==="new"?"selected":""?>>New Regime</option><option value="old" <?=$e["tax_regime"]==="old"?"selected":""?>>Old Regime</option></select></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        <div class="mt-3"><button class="btn btn-pc btn-sm"><i class="ti ti-device-floppy me-1"></i>Save Assignments</button></div>
      </form>
    </div>
  </div>
  <div class="col-md-6">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-info-circle me-2"></i>Regime Comparison</div>
      <table class="pc-table">
        <thead><tr><th>Section</th><th>Deduction</th><th>Old Regime</th><th>New Regime</th></tr></thead>
        <tbody>
        <?php foreach($heads as $h): ?>
        <tr>
          <td><code><?=clean($h["section"])?></code></td>
          <td><?=clean($h["name"])?> <?=$h["max_limit"]>0?"(₹".number_format($h["max_limit"]).")":""?></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>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
function pcAdbToggleScope() {
  const v = document.getElementById('applicableTo').value;
  document.getElementById('scopeCategory').style.display = v === 'category' ? '' : 'none';
  document.getElementById('scopeGrade').style.display = v === 'grade' ? '' : 'none';
}
function pcAdbToggleBasis() {
  const v = document.getElementById('basisType').value;
  document.getElementById('basisFlat').style.display = v === 'flat' ? '' : 'none';
  document.getElementById('basisPct').style.display = v === 'percentage' ? '' : 'none';
}
pcAdbToggleScope();
pcAdbToggleBasis();
</script>
<?php include __DIR__ . "/../../includes/footer.php"; ?>