<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db     = Database::getInstance();
$page   = 'Permission Management';
$user   = currentUser();
$isHR   = in_array($user['role'], ['superadmin','admin','hr','manager','supervisor','hod','management']);

// FIX (07 Jul 2026): this used to hardcode company_id=1, so EVERY
// organization was using company id 1's ("GlobalTech", the original
// seed company) permission policy regardless of their own settings.
// Use the current user's own company now.
$policy = $db->fetchOne("SELECT * FROM permission_policy WHERE company_id=? LIMIT 1", [companyId()]);
$maxMins = ($policy['max_hours_per_month']??4) * 60;
$minDur  = $policy['min_duration_minutes']??30;
$maxDur  = $policy['max_duration_minutes']??120;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = post('action');

    if ($action === 'apply') {
        $empId   = $user['emp_id'] ?: postInt('employee_id');
        $date    = post('permission_date');
        $from    = post('from_time');
        $to      = post('to_time');
        $reason  = post('reason');

        // Calculate duration
        $fromTs  = strtotime("$date $from");
        $toTs    = strtotime("$date $to");
        $durMins = ($toTs - $fromTs) / 60;

        if ($durMins < $minDur) {
            setFlash('error', "Minimum permission duration is $minDur minutes.");
        } elseif ($durMins > $maxDur) {
            setFlash('error', "Maximum permission duration per request is $maxDur minutes.");
        } else {
            // Check monthly quota
            $month = date('n', strtotime($date));
            $year  = date('Y', strtotime($date));
            $used  = $db->fetchOne("SELECT COALESCE(SUM(duration_minutes),0) AS total FROM permission_requests WHERE employee_id=? AND MONTH(permission_date)=? AND YEAR(permission_date)=? AND status!='rejected'", [$empId,$month,$year]);
            $usedMins = $used['total']??0;

            if ($usedMins + $durMins > $maxMins) {
                $remaining = $maxMins - $usedMins;
                setFlash('error', "Permission quota exceeded. Remaining: ".($remaining>0?$remaining.' mins':'0 mins')." of {$maxMins} mins/month.");
            } else {
                $db->execute("INSERT INTO permission_requests (employee_id,permission_date,from_time,to_time,duration_minutes,reason) VALUES (?,?,?,?,?,?)",
                    [$empId,$date,$from,$to,$durMins,$reason]);
                $newReqId = $db->lastInsertId();
                $applicantName = $db->fetchValue("SELECT CONCAT(first_name,' ',last_name) FROM employees WHERE id=?", [$empId]);
                notifyReportingHead($db, $empId, 'Permission Request', "$applicantName requested permission on $date ($from – $to).", 'permission', $newReqId);
                notifyAllSuperadmins($db, $empId, 'Permission Request', "$applicantName requested permission on $date ($from – $to).", 'permission', $newReqId);
                setFlash('success', "Permission request submitted for $date ($from – $to, $durMins mins).");
            }
        }
    } elseif (($action === 'approve' || $action === 'reject') && $isHR) {
        // FIX (07 Jul 2026): confirm the request belongs to an employee in
        // the current organization before touching it — otherwise a
        // manager could approve/reject another organization's requests
        // just by guessing an id.
        $reqOwner = $db->fetchOne(
            "SELECT pr.id FROM permission_requests pr JOIN employees e ON e.id=pr.employee_id WHERE pr.id=? AND e.company_id IN (" . implode(',', array_fill(0,count(orgCompanyIds($db)),'?')) . ")",
            array_merge([postInt('id')], orgCompanyIds($db))
        );
        if ($reqOwner) {
            $newStatus = $action === 'approve' ? 'approved' : 'rejected';
            $db->execute("UPDATE permission_requests SET status=?,approved_by=? WHERE id=?", [$newStatus,$user['id'],postInt('id')]);
            $prEmpId = (int)$db->fetchValue("SELECT employee_id FROM permission_requests WHERE id=?", [postInt('id')]);
            notify($db, $prEmpId, 'Permission ' . ucfirst($newStatus), "Your permission request was $newStatus.", 'permission', postInt('id'));
            notifyAllSuperadmins($db, $prEmpId, 'Permission ' . ucfirst($newStatus), "Permission request for employee #$prEmpId was $newStatus.", 'permission', postInt('id'));
            setFlash('success', 'Permission ' . $newStatus . '.');
        } else {
            setFlash('error', 'Request not found.');
        }
    }
    header('Location: ' . BASE_URL . '/modules/attendance/permission.php'); exit;
}

$month     = intval($_GET['month'] ?? date('n'));
$year      = intval($_GET['year']  ?? date('Y'));
$selEmp    = cleanInt($_GET['emp'] ?? ($user['emp_id']??0));
// FIX: scope dropdown to org.
[$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);
$months    = ['','January','February','March','April','May','June','July','August','September','October','November','December'];

// Load requests
// FIX: scope to current org — this used to show every organization's
// permission requests to any HR/manager role with no filter at all.
[$reqOrgClause, $reqOrgParams] = orgScopeClause($db, 'e.company_id');
$whereEmp = $isHR && !$selEmp ? '' : "AND pr.employee_id=".($selEmp?:0);
$requests = $db->fetchAll("SELECT pr.*,CONCAT(e.first_name,' ',e.last_name) AS emp_name,e.employee_id AS emp_code
    FROM permission_requests pr JOIN employees e ON e.id=pr.employee_id
    WHERE MONTH(pr.permission_date)=? AND YEAR(pr.permission_date)=? AND $reqOrgClause $whereEmp
    ORDER BY pr.permission_date DESC", array_merge([$month,$year], $reqOrgParams));

// Monthly usage for selected employee
$myUsed = $selEmp ? $db->fetchOne("SELECT COALESCE(SUM(duration_minutes),0) AS total FROM permission_requests WHERE employee_id=? AND MONTH(permission_date)=? AND YEAR(permission_date)=? AND status!='rejected'", [$selEmp,$month,$year]) : null;
$usedMins = $myUsed['total']??0;
$remaining = max(0, $maxMins - $usedMins);

include __DIR__ . '/../../includes/header.php';
?>
<!-- Stats -->
<?php if ($selEmp): ?>
<div class="row g-3 mb-3">
  <div class="col-md-3"><div class="pc-stat">
    <div class="pc-stat-val" style="font-size:22px;color:var(--pc-brand)"><?=$maxMins/60?> hrs</div>
    <div class="pc-stat-label">Monthly Quota</div>
  </div></div>
  <div class="col-md-3"><div class="pc-stat">
    <div class="pc-stat-val" style="font-size:22px;color:var(--pc-amber)"><?=round($usedMins/60,1)?> hrs</div>
    <div class="pc-stat-label">Used This Month</div>
  </div></div>
  <div class="col-md-3"><div class="pc-stat">
    <div class="pc-stat-val" style="font-size:22px;color:var(--pc-green)"><?=round($remaining/60,1)?> hrs</div>
    <div class="pc-stat-label">Remaining</div>
  </div></div>
  <div class="col-md-3">
    <div class="pc-stat">
      <div class="pc-progress mb-1"><div class="pc-progress-fill" style="width:<?=$maxMins>0?min(100,round($usedMins/$maxMins*100)):0?>%;background:<?=$remaining<30?'var(--pc-red)':'var(--pc-green)'?>"></div></div>
      <div class="pc-stat-label"><?=$maxMins>0?round($usedMins/$maxMins*100):0?>% used</div>
    </div>
  </div>
</div>
<?php endif; ?>

<div class="row g-3">
  <!-- Apply Form -->
  <div class="col-md-4">
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-clock-plus me-2"></i>Apply for Permission</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="apply">
        <?php if ($isHR): ?>
        <div class="mb-2">
          <label class="pc-label">Employee</label>
          <select name="employee_id" class="form-select form-select-sm" 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>
        <?php endif; ?>
        <div class="mb-2">
          <label class="pc-label">Date</label>
          <input type="date" name="permission_date" class="form-control form-control-sm" value="<?=date('Y-m-d')?>" required max="<?=date('Y-m-d', strtotime('+7 days'))?>">
        </div>
        <div class="row g-2 mb-2">
          <div class="col">
            <label class="pc-label">From Time</label>
            <input type="time" name="from_time" id="fromTime" class="form-control form-control-sm" required onchange="calcDuration()">
          </div>
          <div class="col">
            <label class="pc-label">To Time</label>
            <input type="time" name="to_time" id="toTime" class="form-control form-control-sm" required onchange="calcDuration()">
          </div>
        </div>
        <div class="mb-2" id="durDisplay" style="display:none">
          <div class="alert alert-info py-1 px-2 small" id="durText"></div>
        </div>
        <div class="mb-3">
          <label class="pc-label">Reason</label>
          <input type="text" name="reason" class="form-control form-control-sm" required placeholder="Reason for permission">
        </div>
        <div class="alert alert-warning py-1 px-2 small mb-2">
          <i class="ti ti-info-circle me-1"></i>
          Min: <?=$minDur?> min &nbsp;|&nbsp; Max: <?=$maxDur?> min &nbsp;|&nbsp; Remaining: <strong><?=round($remaining/60,1)?> hrs</strong>
        </div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-send me-1"></i>Submit Request</button>
      </form>
    </div>
  </div>

  <!-- Requests Table -->
  <div class="col-md-8">
    <div class="pc-card mb-2">
      <form method="GET" class="d-flex gap-2">
        <?php if ($selEmp && $isHR): ?><input type="hidden" name="emp" value="<?=$selEmp?>"><?php endif; ?>
        <div><label class="pc-label">Month</label>
          <select name="month" class="form-select form-select-sm" onchange="this.form.submit()">
            <?php for($m=1;$m<=12;$m++): ?><option value="<?=$m?>" <?=$m===$month?'selected':''?>><?=$months[$m]?></option><?php endfor; ?>
          </select></div>
        <div><label class="pc-label">Year</label>
          <select name="year" class="form-select form-select-sm" onchange="this.form.submit()">
            <?php for($y=date('Y');$y>=date('Y')-1;$y--): ?><option value="<?=$y?>" <?=$y===$year?'selected':''?>><?=$y?></option><?php endfor; ?>
          </select></div>
      </form>
    </div>
    <div class="pc-card">
      <div class="pc-card-title">Permission Requests — <?=$months[$month]?> <?=$year?> (<?=count($requests)?>)</div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>Employee</th><th>Date</th><th>From</th><th>To</th><th>Duration</th><th>Reason</th><th>Status</th><?php if($isHR): ?><th>Action</th><?php endif; ?></tr></thead>
          <tbody>
          <?php foreach ($requests as $r): ?>
          <tr>
            <td><div class="fw-semibold"><?=clean($r['emp_name'])?></div><small class="text-muted"><?=clean($r['emp_code'])?></small></td>
            <td><?=fmtDate($r['permission_date'])?></td>
            <td><?=substr($r['from_time'],0,5)?></td>
            <td><?=substr($r['to_time'],0,5)?></td>
            <td><span class="badge" style="background:var(--pc-brand-light);color:var(--pc-brand)"><?=$r['duration_minutes']?> min</span></td>
            <td><?=clean($r['reason'])?></td>
            <td><?=statusBadge($r['status'])?></td>
            <?php if($isHR): ?>
            <td>
              <?php if($r['status']==='pending'): ?>
              <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="approve"><input type="hidden" name="id" value="<?=$r['id']?>"><button class="btn btn-xs btn-success py-0 px-1">Approve</button></form>
              <form method="POST" class="d-inline"><?=csrfField()?><input type="hidden" name="action" value="reject"><input type="hidden" name="id" value="<?=$r['id']?>"><button class="btn btn-xs btn-danger py-0 px-1">Reject</button></form>
              <?php else: ?>—<?php endif; ?>
            </td>
            <?php endif; ?>
          </tr>
          <?php endforeach; ?>
          <?php if (!$requests): ?><tr><td colspan="<?=$isHR?8:7?>" class="text-center text-muted py-3">No permission requests this month</td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<script>
function calcDuration() {
  const f=document.getElementById('fromTime').value, t=document.getElementById('toTime').value;
  if(!f||!t) return;
  const mins=Math.round((new Date('2000-01-01T'+t)-new Date('2000-01-01T'+f))/60000);
  const el=document.getElementById('durDisplay'), tx=document.getElementById('durText');
  if(mins<=0){el.style.display='none';return;}
  el.style.display='block';
  const ok=mins>=<?=$minDur?>&&mins<=<?=$maxDur?>;
  tx.className='alert py-1 px-2 small '+(ok?'alert-info':'alert-danger');
  tx.innerHTML='Duration: <strong>'+mins+' min</strong>'+(ok?' ✓ valid':'  ✗ must be <?=$minDur?>–<?=$maxDur?> min');
}
</script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>