<?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'] ?? 1);
// FIX (07 Jul 2026): confirm this company belongs to the current org —
// otherwise any org's admin could view/edit another org's attendance
// & permission policy just by changing ?company=.
if (!in_array($companyId, orgCompanyIds($db))) {
    setFlash('error','Company not found.'); header('Location: index.php'); exit;
}
$company   = $db->fetchOne("SELECT * FROM companies WHERE id=?", [$companyId]);
if (!$company) { setFlash('error','Company not found.'); header('Location: index.php'); exit; }
$page = 'Attendance & Permission Policy — '.clean($company['name']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $data = [
        'max_hours_per_month'    => post('max_hours_per_month'),
        'min_duration_minutes'   => postInt('min_duration_minutes'),
        'max_duration_minutes'   => postInt('max_duration_minutes'),
        'late_grace_minutes'     => postInt('late_grace_minutes'),
        'free_lates_per_month'   => postInt('free_lates_per_month'),
        'late_deduction_minutes' => postInt('late_deduction_minutes'),
        'lates_per_half_day'     => postInt('lates_per_half_day'),
        'late_leave_type_id'     => postInt('late_leave_type_id') ?: null,
        'lop_unit'               => post('lop_unit') === 'full_day' ? 'full_day' : 'half_day',
        'permission_leave_type_id'=> postInt('permission_leave_type_id') ?: null,
        'lop_leave_type_id'      => postInt('lop_leave_type_id') ?: null,
    ];
    $existing = $db->fetchOne("SELECT id FROM permission_policy WHERE company_id=?", [$companyId]);
    if ($existing) {
        $db->updateRow('permission_policy', array_merge($data,['company_id'=>$companyId]), $existing['id']);
    } else {
        $db->insertRow('permission_policy', array_merge($data,['company_id'=>$companyId]));
    }
    setFlash('success','Policy updated successfully.');
    header('Location: policy.php?company='.$companyId); exit;
}

$policy     = $db->fetchOne("SELECT * FROM permission_policy WHERE company_id=?", [$companyId]);
$leaveTypes = $db->fetchAll("SELECT id,name,code FROM leave_types WHERE is_active=1 ORDER BY name");
include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-md-6">
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-clock-exclamation me-2"></i>Permission Policy — <?=clean($company['name'])?></div>
      <form method="POST">
        <?=csrfField()?>
        <div class="pc-section-divider">Monthly Permission Quota</div>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="pc-label">Max Permission Hours / Month</label>
            <div class="input-group input-group-sm">
              <input type="number" name="max_hours_per_month" class="form-control" step="0.5" min="0.5" max="24" value="<?=$policy['max_hours_per_month']??4?>">
              <span class="input-group-text">hrs</span>
            </div>
            <div class="form-text">Total permission an employee can take per month (e.g. 4 hrs = 240 mins). Can split as: min 30 min, max 2 hrs per request.</div>
          </div>
          <div class="col-md-3">
            <label class="pc-label">Min per Request</label>
            <div class="input-group input-group-sm">
              <input type="number" name="min_duration_minutes" class="form-control" min="15" max="120" value="<?=$policy['min_duration_minutes']??30?>">
              <span class="input-group-text">min</span>
            </div>
          </div>
          <div class="col-md-3">
            <label class="pc-label">Max per Request</label>
            <div class="input-group input-group-sm">
              <input type="number" name="max_duration_minutes" class="form-control" min="30" max="480" value="<?=$policy['max_duration_minutes']??120?>">
              <span class="input-group-text">min</span>
            </div>
          </div>
        </div>

        <div class="pc-section-divider">Late Coming Rules — Cascading Penalty</div>
        <div class="alert alert-info py-2 px-2 small mb-3">
          <i class="ti ti-info-circle me-1"></i>How a late arrival is penalized, in order, per employee per month:
          <strong>1)</strong> first few lates are free &rarr;
          <strong>2)</strong> after that, minutes are deducted from their Permission quota &rarr;
          <strong>3)</strong> once Permission runs out, every few lates deducts half a day of Leave &rarr;
          <strong>4)</strong> if Leave also runs out, it's marked LOP. Every number below is yours to set.
        </div>
        <div class="row g-3">
          <div class="col-md-4">
            <label class="pc-label">Grace Period</label>
            <div class="input-group input-group-sm">
              <input type="number" name="late_grace_minutes" class="form-control" min="0" max="60" value="<?=$policy['late_grace_minutes']??15?>">
              <span class="input-group-text">min</span>
            </div>
            <div class="form-text">Arriving within this many minutes of shift start isn't "late" at all. Set to 0 if even 1 minute late should count.</div>
          </div>
          <div class="col-md-4">
            <label class="pc-label">① Free Lates / Month</label>
            <div class="input-group input-group-sm">
              <input type="number" name="free_lates_per_month" class="form-control" min="0" max="31" value="<?=$policy['free_lates_per_month']??4?>">
              <span class="input-group-text">lates</span>
            </div>
            <div class="form-text">First this many lates each month have no penalty at all.</div>
          </div>
          <div class="col-md-4">
            <label class="pc-label">② Minutes Deducted / Late</label>
            <div class="input-group input-group-sm">
              <input type="number" name="late_deduction_minutes" class="form-control" min="1" max="240" value="<?=$policy['late_deduction_minutes']??30?>">
              <span class="input-group-text">min</span>
            </div>
            <div class="form-text">Once free lates are used up, each further late deducts this many minutes from their monthly Permission quota (above).</div>
          </div>
          <div class="col-md-6">
            <label class="pc-label">③ Lates per Half-Day Leave Deduction</label>
            <div class="input-group input-group-sm">
              <input type="number" name="lates_per_half_day" class="form-control" min="1" max="31" value="<?=$policy['lates_per_half_day']??2?>">
              <span class="input-group-text">lates</span>
            </div>
            <div class="form-text">Once the Permission quota is fully used, every this-many further lates deducts half a day (0.5) from Leave balance.</div>
          </div>
          <div class="col-md-6">
            <label class="pc-label">③ Leave Type to Deduct From</label>
            <select name="late_leave_type_id" class="form-select form-select-sm">
              <option value="">None (skip straight to LOP once Permission runs out)</option>
              <?php foreach($leaveTypes as $lt): ?>
              <option value="<?=$lt['id']?>" <?=($policy['late_leave_type_id']??'')==$lt['id']?'selected':''?>><?=clean($lt['name'])?> (<?=clean($lt['code'])?>)</option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">④ If this leave type's balance also runs out, the day is marked LOP automatically — no separate setting needed for that.</div>
          </div>
          <div class="col-md-6">
            <label class="pc-label">④ LOP Amount (when leave balance is exhausted too)</label>
            <select name="lop_unit" class="form-select form-select-sm">
              <option value="half_day" <?=($policy['lop_unit']??'half_day')=='half_day'?'selected':''?>>Half Day (0.5) — matches the leave tier it follows</option>
              <option value="full_day" <?=($policy['lop_unit']??'half_day')=='full_day'?'selected':''?>>Full Day (1.0) — stricter penalty</option>
            </select>
            <div class="form-text">How much is docked each time the cascade reaches LOP.</div>
          </div>
        </div>

        <div class="pc-section-divider">Leave Types for Deduction</div>
        <div class="row g-3">
          <div class="col-md-6">
            <label class="pc-label">Permission Deduction Leave Type</label>
            <select name="permission_leave_type_id" class="form-select form-select-sm">
              <option value="">None (no leave deduction)</option>
              <?php foreach($leaveTypes as $lt): ?>
              <option value="<?=$lt['id']?>" <?=($policy['permission_leave_type_id']??'')==$lt['id']?'selected':''?>><?=clean($lt['name'])?> (<?=clean($lt['code'])?>)</option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">Used when permission exceeds monthly quota</div>
          </div>
          <div class="col-md-6">
            <label class="pc-label">LOP Leave Type</label>
            <select name="lop_leave_type_id" class="form-select form-select-sm">
              <option value="">None</option>
              <?php foreach($leaveTypes as $lt): ?>
              <option value="<?=$lt['id']?>" <?=($policy['lop_leave_type_id']??'')==$lt['id']?'selected':''?>><?=clean($lt['name'])?> (<?=clean($lt['code'])?>)</option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">Applied when late rule triggers LOP</div>
          </div>
        </div>

        <div class="mt-3"><button class="btn btn-pc"><i class="ti ti-device-floppy me-1"></i>Save Policy</button></div>
      </form>
    </div>
  </div>

  <div class="col-md-6">
    <!-- Policy Summary Card -->
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-info-circle me-2"></i>How This Works</div>
      <div class="small text-muted" style="line-height:2">
        <div class="mb-2">📋 <strong>Permission Quota:</strong> Each employee gets <strong><?=$policy['max_hours_per_month']??4?> hrs</strong> of permission per month. They can split it — minimum <strong><?=$policy['min_duration_minutes']??30?> min</strong> per request, maximum <strong><?=$policy['max_duration_minutes']??120?> min</strong>.</div>
        <div class="mb-2">⏰ <strong>Grace:</strong> Arriving within <strong><?=$policy['late_grace_minutes']??15?> min</strong> of shift start isn't late.</div>
        <div class="mb-2">① <strong>Free lates:</strong> First <strong><?=$policy['free_lates_per_month']??4?></strong> lates/month, no penalty.</div>
        <div class="mb-2">② <strong>Then Permission:</strong> Each further late deducts <strong><?=$policy['late_deduction_minutes']??30?> min</strong> from their Permission quota above.</div>
        <div class="mb-2">③ <strong>Then Leave:</strong> Once Permission is used up, every <strong><?=$policy['lates_per_half_day']??2?></strong> further lates deducts <strong>half a day</strong> of <?=$policy['late_leave_type_id']?clean($db->fetchValue("SELECT name FROM leave_types WHERE id=?",[$policy['late_leave_type_id']])):'the selected leave type'?>.</div>
        <div>🔴 <strong>Then LOP:</strong> Once that leave balance also runs out, the day is marked LOP automatically.</div>
      </div>
    </div>
    <!-- Current Policy Values -->
    <div class="pc-card">
      <div class="pc-card-title">Current Policy at a Glance</div>
      <?php $rows = [
        ['Max Permission/Month', ($policy['max_hours_per_month']??4).' hrs'],
        ['Min per Request', ($policy['min_duration_minutes']??30).' min'],
        ['Max per Request', ($policy['max_duration_minutes']??120).' min'],
        ['Grace Period', ($policy['late_grace_minutes']??15).' min'],
        ['① Free lates/month', ($policy['free_lates_per_month']??4)],
        ['② Minutes deducted/late', ($policy['late_deduction_minutes']??30).' min'],
        ['③ Lates per half-day leave', ($policy['lates_per_half_day']??2)],
      ]; foreach($rows as [$k,$v]): ?>
      <div class="d-flex justify-content-between py-2 border-bottom" style="font-size:12.5px">
        <span class="text-muted"><?=$k?></span>
        <span class="fw-bold" style="color:var(--pc-brand)"><?=$v?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>