<?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'),
        'late_to_leave_days'     => postInt('late_to_leave_days'),
        'late_to_lop_days'       => postInt('late_to_lop_days'),
        '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</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">Late within grace = not counted</div>
          </div>
          <div class="col-md-4">
            <label class="pc-label">Late → Deduct Leave (after)</label>
            <div class="input-group input-group-sm">
              <input type="number" name="late_to_leave_days" class="form-control" min="1" max="31" value="<?=$policy['late_to_leave_days']??2?>">
              <span class="input-group-text">days</span>
            </div>
            <div class="form-text">After X lates → deduct 1 leave day</div>
          </div>
          <div class="col-md-4">
            <label class="pc-label">Late → LOP (after)</label>
            <div class="input-group input-group-sm">
              <input type="number" name="late_to_lop_days" class="form-control" min="1" max="31" value="<?=$policy['late_to_lop_days']??3?>">
              <span class="input-group-text">days</span>
            </div>
            <div class="form-text">After X lates with no leave → 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>. Once quota is exhausted, further requests are rejected or deducted from leave.</div>
        <div class="mb-2">⏰ <strong>Late Grace:</strong> Coming late within <strong><?=$policy['late_grace_minutes']??15?> minutes</strong> is not counted as late.</div>
        <div class="mb-2">📅 <strong>Late → Leave:</strong> After <strong><?=$policy['late_to_leave_days']??2?> late arrivals</strong> in a month (beyond grace), 1 leave day is automatically deducted.</div>
        <div>🔴 <strong>Late → LOP:</strong> After <strong><?=$policy['late_to_lop_days']??3?> lates</strong> with no leave balance, the day is marked as LOP.</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'],
        ['Late → Leave after', ($policy['late_to_leave_days']??2).' lates/month'],
        ['Late → LOP after', ($policy['late_to_lop_days']??3).' lates/month'],
      ]; 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'; ?>