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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    // Update separation leave_encashment or log separately
    $empId = postInt('employee_id'); $ltId = postInt('leave_type_id'); $days = floatval(post('days')); $amt = floatval(post('amount'));
    // FIX (07 Jul 2026): confirm target employee belongs to current org.
    $target = $db->fetchOne("SELECT company_id FROM employees WHERE id=?", [$empId]);
    if (!$target || !in_array($target['company_id'], orgCompanyIds($db))) {
        setFlash('error', 'Employee not found.');
        header('Location: '.BASE_URL.'/modules/payroll/leave_encashment.php'); exit;
    }
    // Deduct from balance
    $db->execute("UPDATE employee_leave_balance SET used=used+? WHERE employee_id=? AND leave_type_id=? AND year=YEAR(NOW())", [$days,$empId,$ltId]);
    setFlash('success','Leave encashment of ₹'.number_format($amt,2).' processed for '.$days.' days.');
    header('Location: '.BASE_URL.'/modules/payroll/leave_encashment.php'); exit;
}

[$orgClause, $orgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id,CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $orgClause ORDER BY first_name", $orgParams);
$selEmp    = cleanInt($_GET['emp'] ?? 0);
// FIX: reject ?emp=<other org's employee>.
if ($selEmp && !in_array($selEmp, array_column($employees, 'id'))) { $selEmp = 0; }
$balances  = $selEmp ? $db->fetchAll("SELECT lb.*,lt.name AS leave_name,lt.code,lt.encashable FROM employee_leave_balance lb JOIN leave_types lt ON lt.id=lb.leave_type_id WHERE lb.employee_id=? AND lb.year=YEAR(NOW()) AND lt.encashable=1", [$selEmp]) : [];
$salary    = $selEmp ? $db->fetchOne("SELECT gross_monthly FROM employee_salary WHERE employee_id=?",[$selEmp]) : null;
$perDay    = $salary ? round($salary['gross_monthly']/26, 2) : 0;

include __DIR__ . '/../../includes/header.php';
?>
<div class="pc-card mb-3">
  <form method="GET" class="d-flex gap-2">
    <div><label class="pc-label">Employee</label>
      <select name="emp" class="form-select form-select-sm" style="width:280px" onchange="this.form.submit()">
        <option value="">Select Employee</option>
        <?php foreach($employees as $e): ?><option value="<?=$e['id']?>" <?=$selEmp==$e['id']?'selected':''?>><?=clean($e['label'])?></option><?php endforeach; ?>
      </select></div>
  </form>
</div>
<?php if($selEmp && $balances): ?>
<div class="row g-3">
  <?php foreach($balances as $b):
    $avail = $b['allocated'] - $b['used'] + ($b['carry_forward']??0);
  ?>
  <div class="col-md-4">
    <div class="pc-card">
      <div class="fw-bold mb-2"><?=clean($b['leave_name'])?> (<?=clean($b['code'])?>)</div>
      <div class="d-flex justify-content-between small mb-1"><span class="text-muted">Available Days</span><span class="fw-bold"><?=$avail?></span></div>
      <div class="d-flex justify-content-between small mb-3"><span class="text-muted">Per Day Value</span><span class="fw-bold">₹<?=number_format($perDay,2)?></span></div>
      <form method="POST">
        <?=csrfField()?>
        <input type="hidden" name="employee_id" value="<?=$selEmp?>">
        <input type="hidden" name="leave_type_id" value="<?=$b['leave_type_id']?>">
        <div class="mb-2"><label class="pc-label">Days to Encash</label>
          <input type="number" name="days" class="form-control form-control-sm" min="1" max="<?=$avail?>" step="0.5" id="days_<?=$b['id']?>" oninput="calcAmt(<?=$b['id']?>,<?=$perDay?>)"></div>
        <div class="mb-3"><label class="pc-label">Amount (₹)</label>
          <input type="number" name="amount" class="form-control form-control-sm" id="amt_<?=$b['id']?>" readonly></div>
        <button class="btn btn-pc btn-sm w-100" <?=$avail<=0?'disabled':''?>>Process Encashment</button>
      </form>
    </div>
  </div>
  <?php endforeach; ?>
</div>
<?php elseif($selEmp): ?><div class="alert alert-info">No encashable leave types with balance found.</div><?php endif; ?>
<script>
function calcAmt(id, perDay) {
  var d = parseFloat(document.getElementById('days_'+id).value)||0;
  document.getElementById('amt_'+id).value = (d*perDay).toFixed(2);
}
</script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>