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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $action = post('action');
    // FIX (07 Jul 2026): validate posted employee id(s) belong to the
    // current org before writing muster records for them.
    $orgCompanies = orgCompanyIds($db);
    if ($action === 'regularize') {
        $empId   = postInt('employee_id');
        $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/attendance/regularization.php'); exit;
        }
        $date    = post('muster_date');
        $status  = post('status');
        $inTime  = post('in_time')  ?: null;
        $outTime = post('out_time') ?: null;
        $remarks = post('remarks');

        $existing = $db->fetchOne("SELECT id,is_locked FROM muster WHERE employee_id=? AND muster_date=?", [$empId,$date]);
        if ($existing && $existing['is_locked']) {
            setFlash('error', 'This record is locked and cannot be modified.');
        } elseif ($existing) {
            $db->execute("UPDATE muster SET status=?,in_time=?,out_time=?,remarks=?,modified_by=? WHERE id=?",
                [$status,$inTime,$outTime,$remarks,currentUser()['id'],$existing['id']]);
            setFlash('success', 'Attendance regularized successfully.');
        } else {
            $db->execute("INSERT INTO muster (employee_id,muster_date,status,in_time,out_time,remarks,modified_by) VALUES (?,?,?,?,?,?,?)",
                [$empId,$date,$status,$inTime,$outTime,$remarks,currentUser()['id']]);
            setFlash('success', 'Attendance record created successfully.');
        }
    } elseif ($action === 'bulk') {
        $empIds  = $_POST['emp_ids'] ?? [];
        $date    = post('bulk_date');
        $status  = post('bulk_status');
        $count   = 0;
        foreach ($empIds as $empId) {
            $empId = intval($empId);
            if (!$empId) continue;
            $target = $db->fetchOne("SELECT company_id FROM employees WHERE id=?", [$empId]);
            if (!$target || !in_array($target['company_id'], $orgCompanies)) continue;
            $existing = $db->fetchOne("SELECT id,is_locked FROM muster WHERE employee_id=? AND muster_date=?", [$empId,$date]);
            if ($existing && $existing['is_locked']) continue;
            if ($existing) {
                $db->execute("UPDATE muster SET status=?,modified_by=? WHERE id=?",[$status,currentUser()['id'],$existing['id']]);
            } else {
                $db->execute("INSERT INTO muster (employee_id,muster_date,status,modified_by) VALUES (?,?,?,?)",[$empId,$date,$status,currentUser()['id']]);
            }
            $count++;
        }
        setFlash('success', "Bulk regularization done for $count employees.");
    }
    header('Location: ' . BASE_URL . '/modules/attendance/regularization.php'); exit;
}

$month     = intval($_GET['month'] ?? date('n'));
$year      = intval($_GET['year']  ?? date('Y'));
$selEmp    = cleanInt($_GET['emp']  ?? 0);
$selDate   = $_GET['date'] ?? '';
// FIX: scope dropdown to org, and reject ?emp=<other org's employee>.
[$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);
if ($selEmp && !in_array($selEmp, array_column($employees, 'id'))) { $selEmp = 0; }

// Load existing record for the selected employee & date
$existing  = ($selEmp && $selDate) ? $db->fetchOne("SELECT * FROM muster WHERE employee_id=? AND muster_date=?", [$selEmp,$selDate]) : null;

// Load month's muster for selected employee
$monthMuster = [];
if ($selEmp) {
    $rows = $db->fetchAll("SELECT * FROM muster WHERE employee_id=? AND MONTH(muster_date)=? AND YEAR(muster_date)=? ORDER BY muster_date", [$selEmp,$month,$year]);
    foreach ($rows as $r) $monthMuster[$r['muster_date']] = $r;
}

$daysInMonth = date('t', mktime(0,0,0,$month,1,$year));
$months      = ['','January','February','March','April','May','June','July','August','September','October','November','December'];
$statuses    = ['P'=>'Present','A'=>'Absent','H'=>'Half Day','L'=>'Leave','WO'=>'Week Off','PH'=>'Public Holiday','CO'=>'Comp Off','LOP'=>'LOP','OD'=>'On Duty'];
$statusColors= ['P'=>'#dcfce7','A'=>'#fee2e2','H'=>'#fef9c3','L'=>'#dbeafe','WO'=>'#f3f4f6','PH'=>'#e0f2fe','CO'=>'#ede9fe','LOP'=>'#fde8d8','OD'=>'#ede9fe'];
$statusText  = ['P'=>'#166534','A'=>'#991b1b','H'=>'#854d0e','L'=>'#1e40af','WO'=>'#6b7280','PH'=>'#0c4a6e','CO'=>'#5b21b6','LOP'=>'#9a3412','OD'=>'#7c3aed'];

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <!-- Left: Regularization Form -->
  <div class="col-md-4">
    <div class="pc-card mb-3">
      <div class="pc-card-title"><i class="ti ti-edit me-2"></i>Regularize Attendance</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="regularize">
        <div class="mb-2"><label class="pc-label">Employee</label>
          <select name="employee_id" class="form-select form-select-sm" required 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>
        <div class="mb-2"><label class="pc-label">Date</label>
          <input type="date" name="muster_date" class="form-control form-control-sm"
                 value="<?=clean($selDate ?: $existing['muster_date'] ?? date('Y-m-d'))?>" required
                 max="<?=date('Y-m-d')?>">
        </div>
        <div class="mb-2"><label class="pc-label">Status</label>
          <select name="status" class="form-select form-select-sm" required>
            <?php foreach($statuses as $v=>$l): ?>
            <option value="<?=$v?>" <?=($existing['status']??'')===$v?'selected':''?>><?=$l?></option>
            <?php endforeach; ?>
          </select></div>
        <div class="row g-2 mb-2">
          <div class="col"><label class="pc-label">In Time</label>
            <input type="time" name="in_time" class="form-control form-control-sm" value="<?=clean($existing['in_time']??'09:00')?>"></div>
          <div class="col"><label class="pc-label">Out Time</label>
            <input type="time" name="out_time" class="form-control form-control-sm" value="<?=clean($existing['out_time']??'18:00')?>"></div>
        </div>
        <div class="mb-3"><label class="pc-label">Remarks</label>
          <input type="text" name="remarks" class="form-control form-control-sm" value="<?=clean($existing['remarks']??'')?>" placeholder="Reason for regularization">
        </div>
        <?php if($existing && $existing['is_locked']): ?>
        <div class="alert alert-warning py-2 small mb-2"><i class="ti ti-lock me-1"></i>This record is locked</div>
        <?php endif; ?>
        <button class="btn btn-pc btn-sm w-100" <?=($existing['is_locked']??0)?'disabled':''?>>
          <i class="ti ti-check me-1"></i><?=$existing?'Update':'Create'?> Record
        </button>
      </form>
    </div>

    <!-- Bulk Regularize -->
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-list-check me-2"></i>Bulk Regularize</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="bulk">
        <div class="mb-2"><label class="pc-label">Date</label>
          <input type="date" name="bulk_date" class="form-control form-control-sm" value="<?=date('Y-m-d')?>" required max="<?=date('Y-m-d')?>">
        </div>
        <div class="mb-2"><label class="pc-label">Mark All As</label>
          <select name="bulk_status" class="form-select form-select-sm">
            <?php foreach($statuses as $v=>$l): ?>
            <option value="<?=$v?>" <?=$v==='WO'?'selected':''?>><?=$l?></option>
            <?php endforeach; ?>
          </select></div>
        <div class="mb-3">
          <label class="pc-label">Select Employees</label>
          <div style="max-height:180px;overflow-y:auto;border:1px solid var(--pc-border);border-radius:var(--r-sm);padding:6px">
            <label class="form-check small mb-1">
              <input type="checkbox" onclick="document.querySelectorAll('.bulk-emp').forEach(c=>c.checked=this.checked)"> <strong>Select All</strong>
            </label>
            <?php foreach($employees as $e): ?>
            <label class="form-check small mb-0">
              <input type="checkbox" name="emp_ids[]" value="<?=$e['id']?>" class="form-check-input bulk-emp"> <?=clean($e['label'])?>
            </label>
            <?php endforeach; ?>
          </div>
        </div>
        <button class="btn btn-outline-secondary btn-sm w-100"><i class="ti ti-list-check me-1"></i>Apply Bulk</button>
      </form>
    </div>
  </div>

  <!-- Right: Calendar view -->
  <div class="col-md-8">
    <div class="pc-card mb-2">
      <form method="GET" class="d-flex gap-2 align-items-end">
        <?php if($selEmp): ?><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')-2;$y--): ?>
            <option value="<?=$y?>" <?=$y===$year?'selected':''?>><?=$y?></option>
            <?php endfor; ?>
          </select></div>
      </form>
    </div>

    <?php if($selEmp): ?>
    <div class="pc-card">
      <div class="pc-card-title">
        <?=$months[$month]?> <?=$year?> — Click any day to regularize
      </div>
      <!-- Legend -->
      <div class="d-flex flex-wrap gap-1 mb-3">
        <?php foreach($statuses as $code=>$label): ?>
        <span style="font-size:10px;padding:2px 7px;border-radius:10px;background:<?=$statusColors[$code]?>;color:<?=$statusText[$code]?>;font-weight:600"><?=$code?> = <?=$label?></span>
        <?php endforeach; ?>
      </div>
      <!-- Calendar grid -->
      <div style="display:grid;grid-template-columns:repeat(7,1fr);gap:4px">
        <?php foreach(['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] as $d): ?>
        <div style="text-align:center;font-size:10px;font-weight:700;color:var(--pc-text2);padding:4px"><?=$d?></div>
        <?php endforeach; ?>
        <?php
        $firstDay = date('N', mktime(0,0,0,$month,1,$year));
        for($i=1;$i<$firstDay;$i++) echo '<div></div>';
        for($d=1;$d<=$daysInMonth;$d++):
            $dateStr = sprintf('%04d-%02d-%02d',$year,$month,$d);
            $rec     = $monthMuster[$dateStr] ?? null;
            $st      = $rec['status'] ?? null;
            $isToday = $dateStr===date('Y-m-d');
            $isFuture= $dateStr>date('Y-m-d');
            $bgColor = $st ? ($statusColors[$st]??'#fff') : ($isFuture?'#fff':'#fff9e6');
            $txColor = $st ? ($statusText[$st]??'#333') : ($isFuture?'#d1d5db':'#92400e');
            $border  = $isToday?'2px solid var(--pc-brand)':'1px solid #e5e7eb';
        ?>
        <div onclick="<?=!$isFuture?"location='?emp=$selEmp&date=$dateStr&month=$month&year=$year'":''?>"
             style="background:<?=$bgColor?>;color:<?=$txColor?>;border-radius:6px;padding:6px 3px;text-align:center;font-size:11px;border:<?=$border?>;cursor:<?=$isFuture?'default':'pointer'?>;transition:box-shadow .1s"
             title="<?=$dateStr.($rec?' | '.$statuses[$st??'A'].' | In:'.($rec['in_time']??'—').' Out:'.($rec['out_time']??'—'):'')?>">
          <div style="font-weight:700"><?=$d?></div>
          <?php if($st): ?><div style="font-size:9px;font-weight:800"><?=$st?></div><?php endif; ?>
          <?php if($rec && $rec['in_time']): ?><div style="font-size:8px"><?=substr($rec['in_time'],0,5)?></div><?php endif; ?>
        </div>
        <?php endfor; ?>
      </div>
      <!-- Summary counts -->
      <?php
      $counts = array_fill_keys(array_keys($statuses),0);
      foreach($monthMuster as $r) if(isset($counts[$r['status']])) $counts[$r['status']]++;
      ?>
      <div class="d-flex flex-wrap gap-2 mt-3 pt-2 border-top">
        <?php foreach($counts as $code=>$cnt): if(!$cnt) continue; ?>
        <div class="d-flex align-items-center gap-1" style="font-size:12px">
          <span style="width:22px;height:22px;display:inline-flex;align-items:center;justify-content:center;border-radius:4px;font-size:9px;font-weight:800;background:<?=$statusColors[$code]?>;color:<?=$statusText[$code]?>"><?=$code?></span>
          <span><?=$cnt?></span>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php else: ?>
    <div class="pc-card"><div class="text-muted text-center py-5"><i class="ti ti-user-search" style="font-size:32px;opacity:0.3"></i><br>Select an employee to view and regularize attendance</div></div>
    <?php endif; ?>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>