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

$selDate = get('date') ?: date('Y-m-d');
$dept    = cleanInt($_GET['dept'] ?? 0);

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

    if ($action === 'bulk_mark') {
        $markDate = post('mark_date');
        $empIds   = $_POST['emp_ids'] ?? [];
        $statuses = $_POST['statuses'] ?? [];
        $inTimes  = $_POST['in_times'] ?? [];
        $outTimes = $_POST['out_times'] ?? [];
        // FIX (07 Jul 2026): the list of ids is posted from a form field,
        // which can be tampered with — verify every id actually belongs
        // to the current organization before writing anything.
        $orgCompanies = orgCompanyIds($db);
        $validIds = $orgCompanies ? array_column($db->fetchAll(
            "SELECT id FROM employees WHERE company_id IN (" . implode(',', array_fill(0,count($orgCompanies),'?')) . ")",
            $orgCompanies
        ), 'id') : [];

        $db->beginTransaction();
        try {
            foreach ($empIds as $i => $empId) {
                $empId = (int)$empId;
                if (!in_array($empId, $validIds)) continue;
                $status = $statuses[$i] ?? 'P';
                $inT  = $inTimes[$i] ?? null;
                $outT = $outTimes[$i] ?? null;
                $workHours = 0;
                if ($inT && $outT) {
                    $workHours = round((strtotime($markDate.' '.$outT) - strtotime($markDate.' '.$inT)) / 3600, 2);
                }
                $existing = $db->fetchValue("SELECT id FROM muster WHERE employee_id=? AND muster_date=?", [$empId,$markDate]);
                if ($existing) {
                    $db->execute(
                        "UPDATE muster SET status=?,in_time=?,out_time=?,work_hours=?,modified_by=? WHERE employee_id=? AND muster_date=?",
                        [$status,$inT,$outT,$workHours,currentUser()['id'],$empId,$markDate]
                    );
                } else {
                    $db->insertRow('muster', [
                        'employee_id'=>$empId,'muster_date'=>$markDate,'status'=>$status,
                        'in_time'=>$inT,'out_time'=>$outT,'work_hours'=>$workHours,
                    ]);
                }
            }
            $db->commit();
            setFlash('success','Attendance marked for '.count($empIds).' employees.');
        } catch (Exception $e) {
            $db->rollback();
            setFlash('error','Error: '.$e->getMessage());
        }
        header("Location: marking.php?date=$markDate&dept=$dept"); exit;
    }

    if ($action === 'import_biometric') {
        // Parse biometric file (CSV: employee_id,date,time,direction)
        if (!empty($_FILES['bio_file']['name'])) {
            $file = $_FILES['bio_file']['tmp_name'];
            $rows = array_map('str_getcsv', file($file));
            $imported = 0;
            $db->beginTransaction();
            try {
                foreach ($rows as $row) {
                    if (count($row) < 4 || $row[0] === 'employee_id') continue;
                    [$empCode, $logDate, $logTime, $direction] = $row;
                    // FIX: employee codes (e.g. EMP1001) are only unique
                    // within an organization now, not globally — scope the
                    // lookup so this can't match a different org's employee.
                    [$bioClause, $bioParams] = orgScopeClause($db, 'company_id');
                    $empId = $db->fetchValue("SELECT id FROM employees WHERE employee_id=? AND $bioClause", array_merge([trim($empCode)], $bioParams));
                    if (!$empId) continue;
                    $db->insertRow('attendance_log', [
                        'employee_id' => (int)$empId,
                        'log_date'    => trim($logDate),
                        'in_time'     => $direction === 'IN' ? trim($logDate).' '.trim($logTime) : null,
                        'out_time'    => $direction === 'OUT' ? trim($logDate).' '.trim($logTime) : null,
                        'source'      => 'biometric',
                    ]);
                    $imported++;
                }
                $db->commit();
                setFlash('success', "Imported $imported biometric records. Click 'Process' to update muster.");
            } catch (Exception $e) {
                $db->rollback();
                setFlash('error', 'Import error: '.$e->getMessage());
            }
        }
        header("Location: marking.php?date=$selDate"); exit;
    }

    if ($action === 'process_biometric') {
        $procDate = post('proc_date') ?: date('Y-m-d');
        processAttendanceFromLog($procDate, $db);
        setFlash('success','Biometric attendance processed for '.$procDate);
        header("Location: marking.php?date=$procDate"); exit;
    }
}

function processAttendanceFromLog(string $date, Database $db): void {
    // FIX (07 Jul 2026): this used to process EVERY organization's
    // attendance_log rows for the date, not just the current org's —
    // meaning one org's admin could overwrite another org's muster data.
    [$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
    $logs = $db->fetchAll(
        "SELECT al.employee_id, MIN(al.in_time) AS first_in, MAX(al.out_time) AS last_out
           FROM attendance_log al
           JOIN employees e ON e.id = al.employee_id
          WHERE al.log_date=? AND $orgClause
          GROUP BY al.employee_id", array_merge([$date], $orgParams)
    );
    foreach ($logs as $log) {
        $inT  = $log['first_in']  ? date('H:i', strtotime($log['first_in']))  : null;
        $outT = $log['last_out']  ? date('H:i', strtotime($log['last_out']))  : null;
        $wh   = ($inT && $outT) ? round((strtotime("$date $outT") - strtotime("$date $inT"))/3600, 2) : 0;
        $status = $wh >= 4 ? ($wh >= 7 ? 'P' : 'H') : 'A';

        $existing = $db->fetchValue("SELECT id FROM muster WHERE employee_id=? AND muster_date=?", [$log['employee_id'],$date]);
        if ($existing) {
            $db->execute("UPDATE muster SET status=?,in_time=?,out_time=?,work_hours=? WHERE employee_id=? AND muster_date=?",
                [$status,$inT,$outT,$wh,$log['employee_id'],$date]);
        } else {
            $db->insertRow('muster',['employee_id'=>$log['employee_id'],'muster_date'=>$date,'status'=>$status,'in_time'=>$inT,'out_time'=>$outT,'work_hours'=>$wh,'source'=>'biometric']);
        }
    }
}

// Fetch employees with attendance
// FIX: scope to current organization.
[$orgClause2, $orgParams2] = orgScopeClause($db, 'e.company_id');
$whereClause = "e.status = 'active' AND $orgClause2";
$params = $orgParams2;
if ($dept) { $whereClause .= ' AND e.department_id=?'; $params[] = $dept; }

$employees = $db->fetchAll(
    "SELECT e.id, e.employee_id, e.first_name, e.last_name,
            d.name AS dept, s.start_time, s.end_time,
            m.status AS att_status, m.in_time, m.out_time, m.work_hours, m.is_locked
       FROM employees e
  LEFT JOIN departments d ON d.id = e.department_id
  LEFT JOIN shifts s ON s.id = e.shift_id
  LEFT JOIN muster m ON m.employee_id=e.id AND m.muster_date=?
      WHERE $whereClause ORDER BY e.first_name",
    array_merge([$selDate], $params)
);

$departments = $db->fetchAll("SELECT id,name FROM departments WHERE is_active=1 ORDER BY name");

// Summary counts
$summary = ['P'=>0,'A'=>0,'H'=>0,'L'=>0,'WO'=>0,'PH'=>0,'OD'=>0,'null'=>0];
foreach ($employees as $e) {
    $k = $e['att_status'] ?? 'null';
    $summary[$k] = ($summary[$k] ?? 0) + 1;
}

$headerActions = '<a href="regularization.php" class="btn btn-sm btn-outline-secondary"><i class="ti ti-edit me-1"></i>Regularization</a>';
include __DIR__ . '/../../includes/header.php';
?>

<!-- Tabs -->
<div class="pc-tabs mb-3">
  <div class="pc-tab active" onclick="switchAttTab('daily')">Daily Marking</div>
  <div class="pc-tab" onclick="switchAttTab('biometric')">Biometric Import</div>
  <div class="pc-tab" onclick="switchAttTab('summary')">Daily Summary</div>
</div>

<!-- Tab: Daily Marking -->
<div id="attTabDaily">
  <!-- Filters -->
  <div class="pc-card mb-3">
    <form method="GET" class="pc-filters">
      <div><label class="pc-label">Date</label>
        <input type="date" name="date" class="form-control form-control-sm" value="<?= $selDate ?>" max="<?= date('Y-m-d') ?>"></div>
      <div><label class="pc-label">Department</label>
        <select name="dept" class="form-select form-select-sm">
          <option value="">All</option>
          <?php foreach ($departments as $d): ?>
          <option value="<?= $d['id'] ?>" <?= $dept==$d['id']?'selected':'' ?>><?= clean($d['name']) ?></option>
          <?php endforeach; ?>
        </select></div>
      <div style="margin-top:auto"><button class="btn btn-pc btn-sm">Filter</button></div>
    </form>
  </div>

  <!-- Status Summary -->
  <div class="row g-2 mb-3">
    <?php $smry = [['P','Present','success'],['A','Absent','danger'],['H','Half Day','warning'],['L','On Leave','info'],['WO','Week Off','secondary'],['OD','On Duty','od'],['null','Not Marked','light']];
    foreach ($smry as [$k,$lbl,$cls]): ?>
    <div class="col">
      <div class="pc-stat text-center py-2">
        <div class="fw-bold fs-5 <?= $cls === 'od' ? '' : ($cls === 'light' ? 'text-secondary' : 'text-'.$cls) ?>" <?= $cls === 'od' ? 'style="color:#7c3aed"' : '' ?>><?= $summary[$k] ?? 0 ?></div>
        <div style="font-size:10px;color:var(--pc-text2)"><?= $lbl ?></div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- Bulk Attendance Form -->
  <form method="POST" id="bulkForm">
    <?= csrfField() ?>
    <input type="hidden" name="action" value="bulk_mark">
    <input type="hidden" name="mark_date" value="<?= $selDate ?>">
    <input type="hidden" name="dept" value="<?= $dept ?>">

    <div class="pc-card">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="fw-semibold"><?= count($employees) ?> Employees – <?= date('D, d M Y', strtotime($selDate)) ?></div>
        <div class="d-flex gap-2">
          <button type="button" class="btn btn-sm btn-outline-success" onclick="markAll('P')">Mark All Present</button>
          <button type="button" class="btn btn-sm btn-outline-danger" onclick="markAll('A')">Mark All Absent</button>
          <button type="submit" class="btn btn-pc btn-sm"><i class="ti ti-check me-1"></i>Save Attendance</button>
        </div>
      </div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead>
            <tr>
              <th><input type="checkbox" id="chkAll" onchange="toggleAll(this)"></th>
              <th>Employee</th><th>Department</th><th>Shift Time</th>
              <th>Status</th><th>In Time</th><th>Out Time</th><th>Work Hrs</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($employees as $i => $e):
            $locked = $e['is_locked'];
            $curStatus = $e['att_status'] ?? '';
          ?>
          <tr class="<?= $curStatus==='A'?'table-danger':($curStatus==='H'?'table-warning':'') ?>">
            <td><input type="checkbox" name="emp_ids[]" value="<?= $e['id'] ?>" class="emp-chk" checked></td>
            <td>
              <div class="fw-semibold"><?= clean($e['first_name'].' '.$e['last_name']) ?></div>
              <div style="font-size:10px;color:var(--pc-text2)"><?= clean($e['employee_id']) ?></div>
            </td>
            <td><?= clean($e['dept']??'—') ?></td>
            <td style="font-size:11px">
              <?= $e['start_time'] ? date('h:i A',strtotime($e['start_time'])).'–'.date('h:i A',strtotime($e['end_time'])) : '—' ?>
            </td>
            <td>
              <select name="statuses[]" class="form-select form-select-sm status-sel" style="width:100px" onchange="updateRow(this,<?= $i ?>)" <?= $locked?'disabled':'' ?>>
                <?php foreach (['P'=>'Present','A'=>'Absent','H'=>'Half Day','L'=>'Leave','WO'=>'Week Off','PH'=>'Holiday','LOP'=>'LOP','OD'=>'On Duty'] as $v=>$l): ?>
                <option value="<?= $v ?>" <?= $curStatus===$v?'selected':'' ?>><?= $l ?></option>
                <?php endforeach; ?>
              </select>
            </td>
            <td><input type="time" name="in_times[]" class="form-control form-control-sm" style="width:100px" value="<?= $e['in_time']??'' ?>" <?= $locked?'readonly':'' ?>></td>
            <td><input type="time" name="out_times[]" class="form-control form-control-sm" style="width:100px" value="<?= $e['out_time']??'' ?>" <?= $locked?'readonly':'' ?>></td>
            <td class="wh-cell" style="font-size:11px"><?= $e['work_hours'] ? $e['work_hours'].'h' : '—' ?></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </form>
</div>

<!-- Tab: Biometric Import -->
<div id="attTabBiometric" style="display:none">
  <div class="row g-3">
    <div class="col-md-6">
      <div class="pc-card">
        <div class="pc-card-title">Import Biometric File</div>
        <form method="POST" enctype="multipart/form-data">
          <?= csrfField() ?>
          <input type="hidden" name="action" value="import_biometric">
          <div class="mb-3">
            <label class="pc-label">CSV File (Format: employee_id, date, time, IN/OUT)</label>
            <input type="file" name="bio_file" class="form-control form-control-sm" accept=".csv" required>
            <div class="form-text">Example row: EMP-0001, 2026-06-08, 09:02:00, IN</div>
          </div>
          <button type="submit" class="btn btn-pc btn-sm"><i class="ti ti-upload me-1"></i>Import</button>
        </form>
      </div>
    </div>
    <div class="col-md-6">
      <div class="pc-card">
        <div class="pc-card-title">Process Biometric Logs</div>
        <p class="small text-muted mb-3">After importing, process logs to update the muster for a specific date.</p>
        <form method="POST">
          <?= csrfField() ?>
          <input type="hidden" name="action" value="process_biometric">
          <div class="mb-3">
            <label class="pc-label">Process Date</label>
            <input type="date" name="proc_date" class="form-control form-control-sm" value="<?= $selDate ?>">
          </div>
          <button type="submit" class="btn btn-success btn-sm"><i class="ti ti-cpu me-1"></i>Process Attendance</button>
        </form>
      </div>
    </div>
    <div class="col-12">
      <div class="pc-card">
        <div class="pc-card-title">Recent Biometric Logs</div>
        <div class="pc-table-wrap">
          <table class="pc-table">
            <thead><tr><th>Employee</th><th>Date</th><th>In Time</th><th>Out Time</th><th>Source</th></tr></thead>
            <tbody>
            <?php $logs = $db->fetchAll(
              "SELECT al.*, e.employee_id, e.first_name, e.last_name FROM attendance_log al
                JOIN employees e ON e.id=al.employee_id
               WHERE al.source='biometric' ORDER BY al.created_at DESC LIMIT 20");
            foreach ($logs as $l): ?>
            <tr>
              <td><?= clean($l['first_name'].' '.$l['last_name']) ?><br><small><?= clean($l['employee_id']) ?></small></td>
              <td><?= fmtDate($l['log_date']) ?></td>
              <td><?= $l['in_time'] ? date('h:i A',strtotime($l['in_time'])) : '—' ?></td>
              <td><?= $l['out_time'] ? date('h:i A',strtotime($l['out_time'])) : '—' ?></td>
              <td><span class="badge bg-info">Biometric</span></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Tab: Summary -->
<div id="attTabSummary" style="display:none">
  <div class="pc-card">
    <div class="pc-card-title">Daily Attendance Summary – <?= date('d M Y', strtotime($selDate)) ?></div>
    <div class="row g-3">
      <?php $pieData = array_filter($summary, fn($v) => $v > 0);
      foreach ([['P','Present','success'],['A','Absent','danger'],['H','Half Day','warning'],['L','Leave','info'],['WO','Week Off','secondary'],['OD','On Duty','od']] as [$k,$lbl,$cls]): ?>
      <div class="col-md-2 text-center">
        <div style="font-size:32px;font-weight:700;color:var(--pc-brand)"><?= $summary[$k] ?? 0 ?></div>
        <span class="badge <?= $cls === 'od' ? '' : 'bg-'.$cls ?>" <?= $cls === 'od' ? 'style="background:#7c3aed;color:#fff"' : '' ?>><?= $lbl ?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>

<?php $extraJs = "<script>
function switchAttTab(tab) {
  ['daily','biometric','summary'].forEach(t => {
    document.getElementById('attTab'+t.charAt(0).toUpperCase()+t.slice(1)).style.display = t===tab ? '' : 'none';
  });
  document.querySelectorAll('.pc-tab').forEach((el,i) => {
    el.classList.toggle('active', ['daily','biometric','summary'][i] === tab);
  });
}
function markAll(status) {
  document.querySelectorAll('.status-sel').forEach(sel => sel.value = status);
}
function toggleAll(chk) {
  document.querySelectorAll('.emp-chk').forEach(c => c.checked = chk.checked);
}
</script>"; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>