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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';
    if ($action === 'save') {
        $id = postInt('id');
        $data = [post('name'),post('code'),post('type'),post('calculation_type'),post('percentage_of')?:'',post('formula')?:'',postInt('is_taxable'),postInt('is_pf_applicable'),postInt('is_esi_applicable'),postInt('display_order'),postInt('is_active')];
        if ($id) {
            $db->execute("UPDATE salary_heads SET name=?,code=?,type=?,calculation_type=?,percentage_of=?,formula=?,is_taxable=?,is_pf_applicable=?,is_esi_applicable=?,display_order=?,is_active=? WHERE id=?", array_merge($data,[$id]));
            setFlash('success','Pay code updated.');
        } else {
            $db->execute("INSERT INTO salary_heads (name,code,type,calculation_type,percentage_of,formula,is_taxable,is_pf_applicable,is_esi_applicable,display_order,is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?)", $data);
            setFlash('success','Pay code added.');
        }
    } elseif ($action === 'toggle') {
        $id = postInt('id'); $current = postInt('current');
        $db->execute("UPDATE salary_heads SET is_active=? WHERE id=?", [$current?0:1,$id]);
        setFlash('success','Status updated.');
    }
    header('Location: '.BASE_URL.'/modules/payroll/paycodes.php'); exit;
}

$editId = cleanInt($_GET['edit'] ?? 0);
$edit   = $editId ? $db->fetchOne("SELECT * FROM salary_heads WHERE id=?",[$editId]) : null;
$heads  = $db->fetchAll("SELECT * FROM salary_heads ORDER BY type, display_order, name");
$grouped = [];
foreach($heads as $h) $grouped[$h['type']][] = $h;

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title"><?=$edit?'Edit Pay Code':'Add Pay Code'?></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">Name</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">Code</label><input type="text" name="code" class="form-control form-control-sm" value="<?=clean($edit['code']??'')?>" style="text-transform:uppercase" required></div>
        <div class="mb-2"><label class="pc-label">Type</label>
          <select name="type" class="form-select form-select-sm" required>
            <?php foreach(['earning'=>'Earning','deduction'=>'Deduction','employer_contribution'=>'Employer Contribution'] as $v=>$l): ?>
            <option value="<?=$v?>" <?=($edit['type']??'')===$v?'selected':''?>><?=$l?></option>
            <?php endforeach; ?>
          </select></div>
        <div class="mb-2"><label class="pc-label">Calculation Type</label>
          <select name="calculation_type" class="form-select form-select-sm" id="calcType" onchange="toggleCalc()">
            <?php foreach(['fixed'=>'Fixed Amount','percentage'=>'Percentage','formula'=>'Formula'] as $v=>$l): ?>
            <option value="<?=$v?>" <?=($edit['calculation_type']??'')===$v?'selected':''?>><?=$l?></option>
            <?php endforeach; ?>
          </select></div>
        <div id="pctOf" class="mb-2" style="display:none"><label class="pc-label">Percentage Of</label><input type="text" name="percentage_of" class="form-control form-control-sm" value="<?=clean($edit['percentage_of']??'')?>" placeholder="e.g. BASIC"></div>
        <div id="formulaField" class="mb-2" style="display:none"><label class="pc-label">Formula</label><textarea name="formula" class="form-control form-control-sm" rows="2" placeholder="e.g. BASIC * 0.4"><?=clean($edit['formula']??'')?></textarea></div>
        <div class="mb-2"><label class="pc-label">Display Order</label><input type="number" name="display_order" class="form-control form-control-sm" value="<?=$edit['display_order']??0?>"></div>
        <div class="row g-2 mb-3">
          <div class="col"><div class="form-check"><input type="checkbox" name="is_taxable" value="1" class="form-check-input" id="t1" <?=($edit['is_taxable']??0)?'checked':''?>><label class="form-check-label small" for="t1">Taxable</label></div></div>
          <div class="col"><div class="form-check"><input type="checkbox" name="is_pf_applicable" value="1" class="form-check-input" id="t2" <?=($edit['is_pf_applicable']??0)?'checked':''?>><label class="form-check-label small" for="t2">PF</label></div></div>
          <div class="col"><div class="form-check"><input type="checkbox" name="is_esi_applicable" value="1" class="form-check-input" id="t3" <?=($edit['is_esi_applicable']??0)?'checked':''?>><label class="form-check-label small" for="t3">ESI</label></div></div>
          <div class="col"><div class="form-check"><input type="checkbox" name="is_active" value="1" class="form-check-input" id="t4" <?=($edit['is_active']??1)?'checked':''?>><label class="form-check-label small" for="t4">Active</label></div></div>
        </div>
        <div class="d-flex gap-2">
          <button class="btn btn-pc btn-sm flex-fill"><i class="ti ti-device-floppy me-1"></i>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">
    <?php foreach(['earning'=>'Earnings','deduction'=>'Deductions','employer_contribution'=>'Employer Contributions'] as $type=>$label): ?>
    <div class="pc-card mb-3">
      <div class="pc-card-title"><?=$label?></div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>#</th><th>Name</th><th>Code</th><th>Calc</th><th>Taxable</th><th>PF</th><th>ESI</th><th>Status</th><th>Actions</th></tr></thead>
          <tbody>
          <?php foreach($grouped[$type]??[] as $i=>$h): ?>
          <tr>
            <td><?=$h['display_order']?></td>
            <td class="fw-semibold"><?=clean($h['name'])?></td>
            <td><code><?=clean($h['code'])?></code></td>
            <td><?=ucfirst($h['calculation_type'])?><?=$h['calculation_type']==='percentage'?' ('.$h['percentage_of'].')':''?></td>
            <td><?=$h['is_taxable']?'<i class="ti ti-check text-success"></i>':'<i class="ti ti-x text-danger"></i>'?></td>
            <td><?=$h['is_pf_applicable']?'<i class="ti ti-check text-success"></i>':'—'?></td>
            <td><?=$h['is_esi_applicable']?'<i class="ti ti-check text-success"></i>':'—'?></td>
            <td><?=statusBadge($h['is_active']?'active':'inactive')?></td>
            <td>
              <a href="?edit=<?=$h['id']?>" class="btn btn-xs btn-outline-primary py-0 px-1" style="font-size:10px">Edit</a>
              <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="toggle"><input type="hidden" name="id" value="<?=$h['id']?>"><input type="hidden" name="current" value="<?=$h['is_active']?>"><button class="btn btn-xs <?=$h['is_active']?'btn-outline-danger':'btn-outline-success'?> py-0 px-1" style="font-size:10px"><?=$h['is_active']?'Disable':'Enable'?></button></form>
            </td>
          </tr>
          <?php endforeach; if(empty($grouped[$type])): ?><tr><td colspan="9" class="text-center text-muted">None</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<script>
function toggleCalc(){
  var v=document.getElementById('calcType').value;
  document.getElementById('pctOf').style.display=v==='percentage'?'block':'none';
  document.getElementById('formulaField').style.display=v==='formula'?'block':'none';
}
toggleCalc();
</script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
