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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';
    if ($action === 'setup') {
        $id = postInt('id');
        if ($id) $db->execute("UPDATE bonus_setup SET name=?,type=?,calculation_type=?,percentage_of=?,percentage=?,max_amount=?,financial_year=?,is_active=? WHERE id=?",
            [post('name'),post('type'),post('calc_type'),post('pct_of'),post('percentage'),post('max_amount'),post('fy'),postInt('is_active'),$id]);
        else $db->execute("INSERT INTO bonus_setup (name,type,calculation_type,percentage_of,percentage,max_amount,financial_year,is_active) VALUES (?,?,?,?,?,?,?,?)",
            [post('name'),post('type'),post('calc_type'),post('pct_of'),post('percentage'),post('max_amount'),post('fy'),1]);
        setFlash('success','Bonus setup saved.');
    }
    header('Location: '.BASE_URL.'/modules/payroll/bonus.php'); exit;
}

$setups    = $db->fetchAll("SELECT * FROM bonus_setup ORDER BY id DESC");
$editId    = cleanInt($_GET['edit']??0);
$editSetup = $editId ? $db->fetchOne("SELECT * FROM bonus_setup WHERE id=?",[$editId]) : null;
$currentFY = date('Y').'-'.(date('Y')+1);

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-gift me-2"></i><?=$editSetup?'Edit':'New'?> Bonus Setup</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="setup">
        <?php if($editSetup): ?><input type="hidden" name="id" value="<?=$editSetup['id']?>"><?php endif; ?>
        <div class="mb-2"><label class="pc-label">Bonus Name</label><input type="text" name="name" class="form-control form-control-sm" value="<?=clean($editSetup['name']??'')?>" required></div>
        <div class="mb-2"><label class="pc-label">Type</label>
          <select name="type" class="form-select form-select-sm">
            <?php foreach(['festival'=>'Festival','performance'=>'Performance','annual'=>'Annual'] as $v=>$l): ?><option value="<?=$v?>" <?=($editSetup['type']??'annual')===$v?'selected':''?>><?=$l?></option><?php endforeach; ?>
          </select></div>
        <div class="mb-2"><label class="pc-label">Calculation</label>
          <select name="calc_type" class="form-select form-select-sm">
            <option value="percentage" <?=($editSetup['calculation_type']??'')==='percentage'?'selected':''?>>Percentage of Salary</option>
            <option value="fixed" <?=($editSetup['calculation_type']??'')==='fixed'?'selected':''?>>Fixed Amount</option>
          </select></div>
        <div class="mb-2"><label class="pc-label">Percentage Of</label><input type="text" name="pct_of" class="form-control form-control-sm" value="<?=clean($editSetup['percentage_of']??'BASIC')?>" placeholder="BASIC / GROSS"></div>
        <div class="mb-2"><label class="pc-label">Percentage / Amount</label><input type="number" name="percentage" class="form-control form-control-sm" step="0.01" value="<?=$editSetup['percentage']??8.33?>"></div>
        <div class="mb-2"><label class="pc-label">Max Amount (₹, 0=unlimited)</label><input type="number" name="max_amount" class="form-control form-control-sm" value="<?=$editSetup['max_amount']??0?>"></div>
        <div class="mb-3"><label class="pc-label">Financial Year</label><input type="text" name="fy" class="form-control form-control-sm" value="<?=clean($editSetup['financial_year']??$currentFY)?>" placeholder="2025-26"></div>
        <div class="d-flex gap-2"><button class="btn btn-pc btn-sm flex-fill">Save</button><?php if($editSetup): ?><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">Bonus Configurations</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Name</th><th>Type</th><th>Calculation</th><th>Rate/Amt</th><th>Max</th><th>FY</th><th>Status</th><th></th></tr></thead>
          <tbody>
          <?php foreach($setups as $s): ?>
          <tr>
            <td class="fw-semibold"><?=clean($s['name'])?></td>
            <td><?=ucfirst($s['type'])?></td>
            <td><?=ucfirst($s['calculation_type'])?><?=$s['calculation_type']==='percentage'?' of '.$s['percentage_of']:''?></td>
            <td><?=$s['calculation_type']==='percentage'?$s['percentage'].'%':'₹'.number_format($s['percentage'],2)?></td>
            <td><?=$s['max_amount']>0?'₹'.number_format($s['max_amount']):'—'?></td>
            <td><?=clean($s['financial_year'])?></td>
            <td><?=statusBadge($s['is_active']?'active':'inactive')?></td>
            <td><a href="?edit=<?=$s['id']?>" class="btn btn-xs btn-outline-primary py-0 px-2">Edit</a></td>
          </tr>
          <?php endforeach; if(!$setups): ?><tr><td colspan="8" class="text-center text-muted">No bonus setups</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
