<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');
$db        = Database::getInstance();
$companyId = cleanInt($_GET['company'] ?? companyId());

if (!in_array($companyId, orgCompanyIds($db))) {
    setFlash('error','Company not found.'); header('Location: ' . BASE_URL . '/modules/company/index.php'); exit;
}
$company = $db->fetchOne("SELECT * FROM companies WHERE id=?", [$companyId]);
if (!$company) { setFlash('error','Company not found.'); header('Location: ' . BASE_URL . '/modules/company/index.php'); exit; }
$page = 'Leave Policy — ' . clean($company['name']);

$leaveMigrationMissing = false;
try {
    $db->fetchOne("SELECT 1 FROM company_leave_policy LIMIT 1");
} catch (Throwable $e) {
    $leaveMigrationMissing = true;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$leaveMigrationMissing) {
    verifyCsrf();
    $leaveTypeIds = $_POST['leave_type_id'] ?? [];
    foreach ($leaveTypeIds as $ltId) {
        $ltId = (int)$ltId;
        $accrual    = (post("accrual_$ltId") === 'monthly') ? 'monthly' : 'yearly';
        $carryFwd   = post("carry_forward_$ltId") ? 1 : 0;
        $maxCarry   = postInt("max_carry_forward_$ltId");
        $encashable = post("encashable_$ltId") ? 1 : 0;
        $encashRate = (float)(post("encashment_rate_$ltId") ?: 100);
        $useForLate = post("use_for_late_$ltId") ? 1 : 0;
        $latePriority = postInt("late_priority_$ltId");

        $db->execute(
            "INSERT INTO company_leave_policy
                (company_id,leave_type_id,accrual_period,carry_forward,max_carry_forward,encashable,encashment_rate_percent,use_for_late_deduction,late_deduction_priority,is_active)
             VALUES (?,?,?,?,?,?,?,?,?,1)
             ON DUPLICATE KEY UPDATE
                accrual_period=VALUES(accrual_period), carry_forward=VALUES(carry_forward),
                max_carry_forward=VALUES(max_carry_forward), encashable=VALUES(encashable),
                encashment_rate_percent=VALUES(encashment_rate_percent),
                use_for_late_deduction=VALUES(use_for_late_deduction),
                late_deduction_priority=VALUES(late_deduction_priority), is_active=1",
            [$companyId, $ltId, $accrual, $carryFwd, $maxCarry, $encashable, $encashRate, $useForLate, $latePriority]
        );
    }
    setFlash('success', 'Leave policy updated.');
    header('Location: ' . BASE_URL . '/modules/company/leave_policy.php?company=' . $companyId); exit;
}

$leaveTypes = $db->fetchAll("SELECT * FROM leave_types WHERE is_active=1 ORDER BY name");
$policyMap = [];
if (!$leaveMigrationMissing) {
    $rows = $db->fetchAll("SELECT * FROM company_leave_policy WHERE company_id=?", [$companyId]);
    foreach ($rows as $r) { $policyMap[$r['leave_type_id']] = $r; }
}

include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-card">
  <div class="pc-card-title"><i class="ti ti-calendar-due me-2"></i>Leave Policy — <?=clean($company['name'])?></div>

  <?php if ($leaveMigrationMissing): ?>
    <div class="alert alert-danger py-2 px-2 small mb-0">
      Run <code>migration_company_leave_policy.sql</code> against your database first, then reload this page.
    </div>
  <?php else: ?>

  <div class="alert alert-info py-2 px-2 small">
    <i class="ti ti-info-circle me-1"></i>Every leave type can behave differently for THIS company. Set each one's:
    <strong>Accrual</strong> (full year upfront, or a bit every month),
    <strong>Carry Forward</strong> (unused leave rolls to next year, up to a max),
    <strong>Encashable</strong> (unused leave is paid out instead of lost), and whether it's one of the leave types the
    <a href="<?=BASE_URL?>/modules/attendance/late_processing.php">Late Arrival cascade</a> can automatically deduct from.
    Leave neither Carry Forward nor Encashable checked, and it simply lapses (use it or lose it) — matches "that month's leave must be used within that month" behavior when Accrual is set to Monthly.
  </div>

  <form method="POST">
    <?=csrfField()?>
    <div class="pc-table-wrap">
      <table class="pc-table align-middle">
        <thead>
          <tr>
            <th>Leave Type</th>
            <th class="text-center">Accrual</th>
            <th class="text-center">Carry Forward</th>
            <th class="text-center">Max Carry (days)</th>
            <th class="text-center">Encashable</th>
            <th class="text-center">Encash Rate %</th>
            <th class="text-center">Use for Late Deduction</th>
            <th class="text-center">Priority</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($leaveTypes as $lt): $p = $policyMap[$lt['id']] ?? null; ?>
          <tr>
            <input type="hidden" name="leave_type_id[]" value="<?=$lt['id']?>">
            <td class="fw-semibold"><?=clean($lt['name'])?> <span class="text-muted">(<?=clean($lt['code'])?>)</span></td>
            <td class="text-center">
              <select name="accrual_<?=$lt['id']?>" class="form-select form-select-sm">
                <option value="yearly" <?=(!$p||$p['accrual_period']=='yearly')?'selected':''?>>Yearly</option>
                <option value="monthly" <?=($p&&$p['accrual_period']=='monthly')?'selected':''?>>Monthly</option>
              </select>
            </td>
            <td class="text-center"><input type="checkbox" name="carry_forward_<?=$lt['id']?>" value="1" <?=($p&&$p['carry_forward'])?'checked':''?>></td>
            <td class="text-center"><input type="number" name="max_carry_forward_<?=$lt['id']?>" class="form-control form-control-sm" style="width:80px;display:inline-block" min="0" value="<?=$p['max_carry_forward']??0?>"></td>
            <td class="text-center"><input type="checkbox" name="encashable_<?=$lt['id']?>" value="1" <?=($p&&$p['encashable'])?'checked':''?>></td>
            <td class="text-center"><input type="number" name="encashment_rate_<?=$lt['id']?>" class="form-control form-control-sm" style="width:70px;display:inline-block" min="0" max="100" value="<?=$p['encashment_rate_percent']??100?>"></td>
            <td class="text-center"><input type="checkbox" name="use_for_late_<?=$lt['id']?>" value="1" <?=($p&&$p['use_for_late_deduction'])?'checked':''?>></td>
            <td class="text-center"><input type="number" name="late_priority_<?=$lt['id']?>" class="form-control form-control-sm" style="width:60px;display:inline-block" min="0" value="<?=$p['late_deduction_priority']??0?>" title="Lower number = tried first"></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <button class="btn btn-pc btn-sm mt-3"><i class="ti ti-check me-1"></i>Save Leave Policy</button>
  </form>

  <div class="alert alert-warning py-2 px-2 small mt-3 mb-0">
    <i class="ti ti-clock-hour-4 me-1"></i>Monthly accrual, carry-forward, encashment and lapsing are all applied automatically at month-end by a cron job (<code>cron/process_monthly_leave_accrual.php</code>) — nothing to click manually once this is set up. See that file's comments for the one-time cPanel Cron Job setup.
  </div>
  <?php endif; ?>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
