<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');
$db = Database::getInstance();
$page = 'Gratuity Setup';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $exists = $db->fetchOne("SELECT id FROM gratuity_setup LIMIT 1");
    $data = [
        'min_service_years'   => postInt('min_service_years'),
        'max_gratuity_amount' => post('max_gratuity_amount'),
        'formula'             => post('formula'),
        'is_active'           => 1,
    ];
    if ($exists) $db->updateRow('gratuity_setup', $data, $exists['id']);
    else $db->insertRow('gratuity_setup', $data);
    setFlash('success', 'Gratuity setup saved.');
    header('Location: ' . BASE_URL . '/modules/configuration/gratuity_setup.php'); exit;
}

$setup = $db->fetchOne("SELECT * FROM gratuity_setup LIMIT 1");
$eligibleCount = $db->fetchOne("SELECT COUNT(*) AS c FROM employees WHERE status='active' AND TIMESTAMPDIFF(YEAR,date_of_joining,NOW()) >= ?", [$setup['min_service_years'] ?? 5]);

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-md-6">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-award me-2"></i>Gratuity Configuration</div>
      <form method="POST">
        <?=csrfField()?>
        <div class="row g-3">
          <div class="col-md-6"><label class="pc-label">Minimum Service (Years)</label>
            <input type="number" name="min_service_years" class="form-control form-control-sm" value="<?=$setup['min_service_years']??5?>" required>
            <div class="form-text">As per Payment of Gratuity Act, 1972 — default is 5 years.</div></div>
          <div class="col-md-6"><label class="pc-label">Maximum Gratuity Amount (₹)</label>
            <input type="number" name="max_gratuity_amount" class="form-control form-control-sm" value="<?=$setup['max_gratuity_amount']??2000000?>" required>
            <div class="form-text">Statutory cap — currently ₹20,00,000.</div></div>
          <div class="col-12"><label class="pc-label">Calculation Formula</label>
            <select name="formula" class="form-select form-select-sm">
              <option value="15/26" <?=($setup['formula']??'')==='15/26'?'selected':''?>>15/26 × Last Basic × Years of Service (Standard)</option>
              <option value="15/30" <?=($setup['formula']??'')==='15/30'?'selected':''?>>15/30 × Last Basic × Years of Service (Seasonal Establishments)</option>
            </select></div>
        </div>
        <div class="mt-3"><button class="btn btn-pc btn-sm"><i class="ti ti-device-floppy me-1"></i>Save Gratuity Setup</button></div>
      </form>
    </div>
  </div>
  <div class="col-md-6">
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-info-circle me-2"></i>Current Configuration</div>
      <div class="d-flex justify-content-between py-2 border-bottom small"><span class="text-muted">Minimum Service Required</span><span class="fw-bold"><?=$setup['min_service_years']??5?> years</span></div>
      <div class="d-flex justify-content-between py-2 border-bottom small"><span class="text-muted">Maximum Payout</span><span class="fw-bold">₹<?=number_format($setup['max_gratuity_amount']??2000000)?></span></div>
      <div class="d-flex justify-content-between py-2 small"><span class="text-muted">Formula</span><span class="fw-bold"><?=clean($setup['formula']??'15/26')?></span></div>
    </div>
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-users me-2"></i>Impact Summary</div>
      <div class="pc-stat-val mb-1"><?=$eligibleCount['c']??0?></div>
      <div class="pc-stat-label">employees currently eligible for gratuity based on the configured minimum service period.</div>
      <a href="<?=BASE_URL?>/modules/payroll/gratuity.php" class="btn btn-pc btn-sm w-100 mt-3"><i class="ti ti-calculator me-1"></i>View Gratuity Calculations</a>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
