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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = $_POST['action'] ?? '';
    $orgCompanies = orgCompanyIds($db);
    if ($action === 'save') {
        $empId = postInt('employee_id');
        // 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'], $orgCompanies)) {
            setFlash('error', 'Employee not found.');
            header('Location: '.BASE_URL.'/modules/payroll/arrears.php'); exit;
        }
        $db->execute("INSERT INTO arrear_calculations (employee_id,from_month,from_year,to_month,to_year,arrear_amount,reason,status) VALUES (?,?,?,?,?,?,?,'pending')",
            [$empId,postInt('from_month'),postInt('from_year'),postInt('to_month'),postInt('to_year'),post('arrear_amount'),post('reason')]);
        setFlash('success','Arrear record saved successfully.');
    } elseif ($action === 'approve' || $action === 'delete') {
        // FIX: confirm the arrear record's employee belongs to current org.
        $rec = $db->fetchOne(
            "SELECT a.id FROM arrear_calculations a JOIN employees e ON e.id=a.employee_id WHERE a.id=? AND e.company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            array_merge([postInt('id')], $orgCompanies)
        );
        if (!$rec) {
            setFlash('error', 'Record not found.');
        } elseif ($action === 'approve') {
            $db->execute("UPDATE arrear_calculations SET status='approved' WHERE id=?", [postInt('id')]);
            setFlash('success','Arrear approved.');
        } else {
            $db->execute("DELETE FROM arrear_calculations WHERE id=? AND status='pending'", [postInt('id')]);
            setFlash('success','Deleted.');
        }
    }
    header('Location: '.BASE_URL.'/modules/payroll/arrears.php'); exit;
}

[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
$arrears   = $db->fetchAll("SELECT a.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name,e.employee_id AS emp_code FROM arrear_calculations a JOIN employees e ON e.id=a.employee_id WHERE $orgClause ORDER BY a.created_at DESC", $orgParams);
[$empOrgClause, $empOrgParams] = orgScopeClause($db, 'company_id');
$employees = $db->fetchAll("SELECT id,CONCAT(employee_id,' - ',first_name,' ',last_name) AS label FROM employees WHERE status='active' AND $empOrgClause ORDER BY first_name", $empOrgParams);
$months    = ['January','February','March','April','May','June','July','August','September','October','November','December'];

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-calculator me-2"></i>New Arrear Entry</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="save">
        <div class="mb-2"><label class="pc-label">Employee</label>
          <select name="employee_id" class="form-select form-select-sm" required>
            <option value="">Select</option>
            <?php foreach($employees as $e): ?><option value="<?=$e['id']?>"><?=clean($e['label'])?></option><?php endforeach; ?>
          </select></div>
        <div class="pc-section-divider">Arrear Period</div>
        <div class="row g-2 mb-2">
          <div class="col"><label class="pc-label">From Month</label>
            <select name="from_month" class="form-select form-select-sm"><?php foreach($months as $i=>$m): ?><option value="<?=$i+1?>"><?=$m?></option><?php endforeach; ?></select></div>
          <div class="col"><label class="pc-label">From Year</label>
            <select name="from_year" class="form-select form-select-sm"><?php for($y=date('Y');$y>=date('Y')-5;$y--): ?><option value="<?=$y?>"><?=$y?></option><?php endfor; ?></select></div>
        </div>
        <div class="row g-2 mb-2">
          <div class="col"><label class="pc-label">To Month</label>
            <select name="to_month" class="form-select form-select-sm"><?php foreach($months as $i=>$m): ?><option value="<?=$i+1?>" <?=$i+1==date('n')?'selected':''?>><?=$m?></option><?php endforeach; ?></select></div>
          <div class="col"><label class="pc-label">To Year</label>
            <select name="to_year" class="form-select form-select-sm"><?php for($y=date('Y');$y>=date('Y')-5;$y--): ?><option value="<?=$y?>" <?=$y==date('Y')?'selected':''?>><?=$y?></option><?php endfor; ?></select></div>
        </div>
        <div class="mb-2"><label class="pc-label">Arrear Amount (₹)</label><input type="number" name="arrear_amount" class="form-control form-control-sm" step="0.01" required></div>
        <div class="mb-3"><label class="pc-label">Reason</label><textarea name="reason" class="form-control form-control-sm" rows="2" required></textarea></div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-device-floppy me-1"></i>Save Arrear</button>
      </form>
    </div>
  </div>
  <div class="col-md-8">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-list me-2"></i>Arrear Records</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Employee</th><th>Period</th><th>Amount</th><th>Reason</th><th>Status</th><th>Action</th></tr></thead>
          <tbody>
          <?php foreach($arrears as $a): ?>
          <tr>
            <td><div class="fw-semibold"><?=clean($a['emp_name'])?></div><small class="text-muted"><?=clean($a['emp_code'])?></small></td>
            <td><?=$months[$a['from_month']-1].' '.$a['from_year']?> → <?=$months[$a['to_month']-1].' '.$a['to_year']?></td>
            <td class="fw-bold">₹<?=number_format($a['arrear_amount'],2)?></td>
            <td><?=clean($a['reason'])?></td>
            <td><?=statusBadge($a['status'])?></td>
            <td>
              <?php if($a['status']==='pending'): ?>
              <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="approve"><input type="hidden" name="id" value="<?=$a['id']?>"><button class="btn btn-xs btn-success py-0 px-2">Approve</button></form>
              <form method="POST" class="d-inline" onsubmit="return confirm('Delete?')"><?=csrfField()?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=$a['id']?>"><button class="btn btn-xs btn-danger py-0 px-2">Del</button></form>
              <?php else: ?>—<?php endif; ?>
            </td>
          </tr>
          <?php endforeach; if(!$arrears): ?><tr><td colspan="6" class="text-center text-muted py-3">No arrear records</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>