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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    // FIX (07 Jul 2026): this had no role check — any logged-in employee
    // could add/edit/delete Professional Tax slabs affecting everyone.
    requireRole('superadmin','admin','hr','management');
    $action = $_POST['action'] ?? '';
    if ($action === 'slab') {
        $id = postInt('id');
        if ($id) $db->execute("UPDATE pt_slabs SET state=?,income_from=?,income_to=?,monthly_pt=?,is_active=? WHERE id=?",
            [post('state'), post('from'), post('to'), post('amount'), postInt('active'), $id]);
        else $db->execute("INSERT INTO pt_slabs (state,income_from,income_to,monthly_pt,is_active) VALUES (?,?,?,?,?)",
            [post('state'), post('from'), post('to'), post('amount'), 1]);
        setFlash('success', 'PT slab saved.');
    } elseif ($action === 'delete') {
        $db->execute("DELETE FROM pt_slabs WHERE id=?", [postInt('id')]);
        setFlash('success', 'Deleted.');
    }
    header('Location: '.BASE_URL.'/modules/statutory/pt.php'); exit;
}

$editId = cleanInt($_GET['edit'] ?? 0);
$edit   = $editId ? $db->fetchOne("SELECT * FROM pt_slabs WHERE id=?", [$editId]) : null;
$slabs  = $db->fetchAll("SELECT * FROM pt_slabs ORDER BY state, income_from");
$states = array_unique(array_column($slabs, 'state'));
$month  = intval($_GET['month'] ?? date('n'));
$year   = intval($_GET['year']  ?? date('Y'));
// FIX: scope PT deduction register to current org.
[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
$ptData = $db->fetchAll("SELECT pd.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name,e.employee_id AS emp_code,e.state_of_work
    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.professional_tax>0 AND $orgClause
    ORDER BY e.first_name", array_merge([$month, $year], $orgParams));
$totalPT = array_sum(array_column($ptData, 'professional_tax'));

include __DIR__ . '/../../includes/header.php';
?>
<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-building-community me-2"></i><?=$edit ? 'Edit' : 'Add'?> PT Slab</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="slab">
        <?php if ($edit): ?><input type="hidden" name="id" value="<?=$edit['id']?>"><?php endif; ?>
        <div class="mb-2"><label class="pc-label">State</label>
          <input type="text" name="state" class="form-control form-control-sm" value="<?=clean($edit['state'] ?? '')?>" placeholder="e.g. Tamil Nadu" required></div>
        <div class="mb-2"><label class="pc-label">Income From (₹/month)</label>
          <input type="number" name="from" class="form-control form-control-sm" value="<?=$edit['income_from'] ?? 0?>" required></div>
        <div class="mb-2"><label class="pc-label">Income To (₹/month)</label>
          <input type="number" name="to" class="form-control form-control-sm" value="<?=$edit['income_to'] ?? 999999?>" required></div>
        <div class="mb-3"><label class="pc-label">Monthly PT Amount (₹)</label>
          <input type="number" name="amount" class="form-control form-control-sm" step="0.01" value="<?=$edit['monthly_pt'] ?? 0?>" required></div>
        <div class="d-flex gap-2">
          <button class="btn btn-pc btn-sm flex-fill">Save Slab</button>
          <?php if ($edit): ?><a href="?" class="btn btn-outline-secondary btn-sm">Cancel</a><?php endif; ?>
        </div>
      </form>
    </div>

    <div class="pc-card">
      <div class="pc-card-title">PT Slabs</div>
      <?php foreach ($states as $state): ?>
      <div class="pc-section-divider"><?=clean($state)?></div>
      <?php foreach (array_filter($slabs, fn($s) => $s['state'] === $state) as $s): ?>
      <div class="d-flex justify-content-between align-items-center py-1" style="font-size:12px">
        <span>₹<?=number_format($s['income_from'])?>–<?=$s['income_to'] >= 999999 ? 'Above' : '₹'.number_format($s['income_to'])?></span>
        <span class="fw-bold">₹<?=number_format($s['monthly_pt'], 2)?>/month</span>
        <div>
          <a href="?edit=<?=$s['id']?>" 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>
        </div>
      </div>
      <?php endforeach; ?>
      <?php endforeach; ?>
      <?php if (!$slabs): ?><div class="text-muted text-center small py-2">No PT slabs configured</div><?php endif; ?>
    </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>
      </form>
    </div>

    <div class="pc-card">
      <div class="pc-card-title">PT Deduction Register — <?=date('F', mktime(0,0,0,$month,1))?> <?=$year?>
        &nbsp;<span style="font-weight:400;font-size:12px;color:var(--pc-text2)">Total: ₹<?=number_format($totalPT, 2)?></span>
      </div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Employee</th><th>State</th><th>Gross Salary</th><th>PT Amount</th></tr></thead>
          <tbody>
          <?php foreach ($ptData 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['state_of_work'] ?? '—')?></td>
            <td>₹<?=number_format($d['gross_salary'], 2)?></td>
            <td class="fw-bold">₹<?=number_format($d['professional_tax'], 2)?></td>
          </tr>
          <?php endforeach; ?>
          <?php if (!$ptData): ?>
          <tr><td colspan="4" class="text-center text-muted py-3">No PT data for selected period</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>