<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/late_penalty_engine.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');
$db   = Database::getInstance();
$user = currentUser();
$page = 'Late Arrival Processing';

$companyId = companyId();
$policy = $db->fetchOne("SELECT * FROM permission_policy WHERE company_id=? LIMIT 1", [$companyId]);
if (!$policy) {
    setFlash('error', 'Set up your Attendance & Permission Policy first (Companies → Policy) before processing late arrivals.');
    header('Location: ' . BASE_URL . '/modules/company/policy.php?company=' . $companyId); exit;
}

$maxPermMins   = (int)round(($policy['max_hours_per_month'] ?? 4) * 60);
$freeLates     = (int)($policy['free_lates_per_month'] ?? 4);
$deductMinsEa  = (int)($policy['late_deduction_minutes'] ?? 30);
$latesPerHalf  = max(1, (int)($policy['lates_per_half_day'] ?? 2));
$lateLeaveType = $policy['late_leave_type_id'] ?: null;
$lopDaysUnit   = ($policy['lop_unit'] ?? 'half_day') === 'full_day' ? 1.0 : 0.5;

$month = postInt('month') ?: (int)date('n');
$year  = postInt('year') ?: (int)date('Y');

$results = null; // filled in after processing, for the results table

if ($_SERVER['REQUEST_METHOD'] === 'POST' && post('action') === 'process') {
    verifyCsrf();
    $results = processLatePenaltiesForCompany($db, $companyId, $month, $year, $user['id']);
    setFlash('success', $results ? count($results) . ' employee(s) processed.' : 'No new unprocessed late days found for that month.');
}

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-md-5">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-clock-exclamation me-2"></i>Process Late Arrivals</div>
      <div class="alert alert-info py-2 px-2 small">
        Applies your company's cascade (Companies → Policy) to every late
        day not yet processed: <strong><?=$freeLates?> free</strong> →
        <strong><?=$deductMinsEa?> min from Permission</strong> →
        <strong>half-day leave every <?=$latesPerHalf?></strong> (auto-picks from
        <a href="<?=BASE_URL?>/modules/company/leave_policy.php?company=<?=$companyId?>">whichever eligible leave type</a> has balance) →
        <strong><?=$lopDaysUnit==1.0?'full-day':'half-day'?> LOP</strong>.
        Safe to run more than once — already-processed days are skipped automatically.
      </div>
      <div class="alert alert-success py-2 px-2 small">
        <i class="ti ti-refresh me-1"></i>This also runs <strong>automatically every month</strong> via a cron job — this button is only for spot-checking or re-running a specific month on demand.
      </div>
      <form method="POST" onsubmit="return confirm('Process late arrivals for this month? This will deduct Permission/Leave and mark LOP days where applicable.');">
        <?=csrfField()?><input type="hidden" name="action" value="process">
        <div class="row g-2">
          <div class="col-6">
            <label class="pc-label">Month</label>
            <select name="month" class="form-select form-select-sm">
              <?php for($m=1;$m<=12;$m++): ?>
              <option value="<?=$m?>" <?=$m==$month?'selected':''?>><?=date('F', mktime(0,0,0,$m,1))?></option>
              <?php endfor; ?>
            </select>
          </div>
          <div class="col-6">
            <label class="pc-label">Year</label>
            <select name="year" class="form-select form-select-sm">
              <?php for($y=(int)date('Y');$y>=(int)date('Y')-2;$y--): ?>
              <option value="<?=$y?>" <?=$y==$year?'selected':''?>><?=$y?></option>
              <?php endfor; ?>
            </select>
          </div>
        </div>
        <button class="btn btn-pc btn-sm w-100 mt-3"><i class="ti ti-play me-1"></i>Calculate &amp; Apply</button>
      </form>
      <div class="mt-3">
        <a href="<?=BASE_URL?>/modules/company/policy.php?company=<?=$companyId?>" class="small"><i class="ti ti-settings me-1"></i>Edit cascade rules</a>
      </div>
    </div>
  </div>

  <div class="col-md-7">
    <?php if ($results !== null): ?>
    <div class="pc-card">
      <div class="pc-card-title">Results — <?=date('F', mktime(0,0,0,$month,1))?> <?=$year?></div>
      <?php if (!$results): ?>
        <div class="text-center text-muted py-4">No new late days to process for this month.</div>
      <?php else: ?>
        <div class="pc-table-wrap">
          <table class="pc-table">
            <thead><tr><th>Employee</th><th class="text-center">Free</th><th class="text-center">Permission</th><th class="text-center">Leave</th><th class="text-center">LOP</th></tr></thead>
            <tbody>
              <?php foreach ($results as $r): ?>
              <tr>
                <td><?=clean($r['name'])?> <span class="text-muted">(<?=clean($r['code'])?>)</span></td>
                <td class="text-center"><?=$r['free']?></td>
                <td class="text-center"><?=$r['permission']?></td>
                <td class="text-center"><?=$r['leave']?></td>
                <td class="text-center"><?=$r['lop'] > 0 ? '<span class="text-danger fw-bold">'.$r['lop'].'</span>' : 0?></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
    <?php else: ?>
    <div class="pc-card text-center text-muted py-5">Pick a month and click "Calculate &amp; Apply" to see results here.</div>
    <?php endif; ?>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
