<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin(); requireRole('superadmin','admin','hr','management');
$db = Database::getInstance();
$page = 'Holiday Calendar';

// ── CSV template download ───────────────────────────────────
if (isset($_GET['template'])) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="holiday_calendar_template.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['name','holiday_date','location_id','is_national']);
    fputcsv($out, ['Independence Day','2026-08-15','','1']);
    fputcsv($out, ['Founders Day','2026-09-05','3','0']);
    fclose($out); exit;
}

$bulkResult = null;

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

    if ($action === 'save') {
        $id = postInt('id');
        $data = [
            'name'         => post('name'),
            'holiday_date' => post('holiday_date'),
            'location_id'  => postInt('location_id') ?: null,
            'is_national'  => postInt('is_national'),
            'is_active'    => isset($_POST['is_active']) ? 1 : 0,
        ];
        if ($id) {
            $db->updateRow('holiday_calendar', $data, $id);
            setFlash('success', 'Holiday updated.');
        } else {
            $db->insertRow('holiday_calendar', $data);
            setFlash('success', 'Holiday added.');
        }
        // Auto-mark attendance: every active employee (scoped to this org,
        // and to the chosen location if one was picked) gets a 'PH' muster
        // row for this date, unless they already have an attendance entry.
        if ($data['is_active']) {
            $marked = markHolidayAttendance($db, $data['holiday_date'], $data['location_id']);
            if ($marked) setFlash('success', "Holiday saved — attendance auto-marked as Holiday for $marked employee(s).");
        }
    } elseif ($action === 'delete') {
        $db->execute("DELETE FROM holiday_calendar WHERE id=?", [postInt('id')]);
        setFlash('success', 'Holiday removed. Note: attendance already marked as Holiday for that date is left as-is — edit it in Muster Management if needed.');
    } elseif ($action === 'toggle') {
        $db->execute("UPDATE holiday_calendar SET is_active=? WHERE id=?", [postInt('active'), postInt('id')]);
        setFlash('success', 'Status updated.');
    } elseif ($action === 'mark_attendance') {
        // Backfill button for holidays added/edited before this feature existed.
        $h = $db->fetchOne("SELECT holiday_date, location_id FROM holiday_calendar WHERE id=?", [postInt('id')]);
        if ($h) {
            $marked = markHolidayAttendance($db, $h['holiday_date'], $h['location_id']);
            setFlash('success', $marked ? "Attendance marked as Holiday for $marked employee(s)." : 'No employees needed updating — everyone already has an attendance entry for that date.');
        }
    } elseif ($action === 'bulk_upload') {
        $file = $_FILES['bulk_file'] ?? null;
        if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
            setFlash('error', 'Upload failed. Please try again.');
        } else {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            if (!in_array($ext, ['csv','txt'])) {
                setFlash('error', 'Only CSV files are supported.');
            } else {
                $validLocations = array_column($db->fetchAll("SELECT id FROM locations WHERE is_active=1"), 'id');
                $handle    = fopen($file['tmp_name'], 'r');
                $header    = fgetcsv($handle);
                $processed = 0; $marked = 0; $errors = []; $rowNum = 1;

                while (($row = fgetcsv($handle)) !== false) {
                    $rowNum++;
                    if (count(array_filter($row, fn($v) => trim((string)$v) !== '')) === 0) continue;
                    [$name, $date, $locId, $isNat] = array_pad($row, 4, '');
                    $name = trim($name); $date = trim($date); $locId = trim($locId);

                    if (!$name)  { $errors[] = "Row $rowNum: holiday name is required."; continue; }
                    if (!$date || !strtotime($date)) { $errors[] = "Row $rowNum: invalid or missing holiday_date."; continue; }
                    $date = date('Y-m-d', strtotime($date));
                    $locId = ($locId !== '' && in_array((int)$locId, $validLocations)) ? (int)$locId : null;

                    try {
                        // Dedupe on (date, location) so re-uploading the same
                        // template doesn't create duplicate holiday rows.
                        $existing = $locId
                            ? $db->fetchValue("SELECT id FROM holiday_calendar WHERE holiday_date=? AND location_id=?", [$date, $locId])
                            : $db->fetchValue("SELECT id FROM holiday_calendar WHERE holiday_date=? AND location_id IS NULL", [$date]);
                        $hData = ['name'=>$name, 'holiday_date'=>$date, 'location_id'=>$locId, 'is_national'=>$isNat!=='' ? (int)!!$isNat : 0, 'is_active'=>1];
                        if ($existing) {
                            $db->updateRow('holiday_calendar', $hData, (int)$existing);
                        } else {
                            $db->insertRow('holiday_calendar', $hData);
                        }
                        $marked += markHolidayAttendance($db, $date, $locId);
                        $processed++;
                    } catch (Throwable $e) {
                        $errors[] = "Row $rowNum: " . $e->getMessage();
                    }
                }
                fclose($handle);
                $bulkResult = ['processed' => $processed, 'marked' => $marked, 'errors' => $errors];
                auditLog('BULK_UPLOAD', 'holiday_calendar', 0);
            }
        }
    }

    if ($action !== 'bulk_upload') {
        header('Location: ' . BASE_URL . '/modules/configuration/holidays.php?year=' . (intval($_GET['year'] ?? date('Y')))); exit;
    }
}

$year      = intval($_GET['year'] ?? date('Y'));
$editId    = cleanInt($_GET['edit'] ?? 0);
$edit      = $editId ? $db->fetchOne("SELECT * FROM holiday_calendar WHERE id=?", [$editId]) : null;
$locations = $db->fetchAll("SELECT id,name FROM locations WHERE is_active=1 ORDER BY name");
$holidays  = $db->fetchAll("SELECT h.*,l.name AS location_name FROM holiday_calendar h LEFT JOIN locations l ON l.id=h.location_id WHERE YEAR(h.holiday_date)=? ORDER BY h.holiday_date", [$year]);

include __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-md-4">
    <div class="pc-card">
      <div class="pc-card-title"><i class="ti ti-calendar-event me-2"></i><?=$edit?'Edit':'Add'?> Holiday</div>
      <form method="POST">
        <?=csrfField()?><input type="hidden" name="action" value="save">
        <?php if($edit): ?><input type="hidden" name="id" value="<?=$edit['id']?>"><?php endif; ?>
        <div class="mb-2"><label class="pc-label">Holiday Name</label>
          <input type="text" name="name" class="form-control form-control-sm" value="<?=clean($edit['name']??'')?>" required></div>
        <div class="mb-2"><label class="pc-label">Date</label>
          <input type="date" name="holiday_date" class="form-control form-control-sm" value="<?=$edit['holiday_date']??date('Y-m-d')?>" required></div>
        <div class="mb-2"><label class="pc-label">Location (optional)</label>
          <select name="location_id" class="form-select form-select-sm">
            <option value="">All Locations</option>
            <?php foreach($locations as $l): ?><option value="<?=$l['id']?>" <?=($edit['location_id']??'')==$l['id']?'selected':''?>><?=clean($l['name'])?></option><?php endforeach; ?>
          </select></div>
        <div class="mb-2 form-check">
          <input type="checkbox" name="is_national" value="1" class="form-check-input" id="nat" <?=($edit['is_national']??0)?'checked':''?>>
          <label class="form-check-label small" for="nat">National Holiday</label></div>
        <div class="mb-3 form-check">
          <input type="checkbox" name="is_active" value="1" class="form-check-input" id="act" <?=($edit['is_active']??1)?'checked':''?>>
          <label class="form-check-label small" for="act">Active</label></div>
        <div class="d-flex gap-2">
          <button class="btn btn-pc btn-sm flex-fill"><?=$edit?'Update':'Add'?> Holiday</button>
          <?php if($edit): ?><a href="?year=<?=$year?>" class="btn btn-sm btn-outline-secondary">Cancel</a><?php endif; ?>
        </div>
        <div class="small text-muted mt-2"><i class="ti ti-info-circle me-1"></i>Saving an active holiday automatically marks attendance as "Holiday" for every employee who doesn't already have an entry for that date — on both web and mobile.</div>
      </form>
    </div>

    <div class="pc-card mt-3">
      <div class="pc-card-title"><i class="ti ti-file-upload me-2"></i>Bulk Upload Holidays</div>
      <p class="text-muted small mb-2">Upload many holidays at once via CSV. Attendance is auto-marked as Holiday for each date too.</p>
      <a href="?template=1" class="btn btn-outline-secondary btn-sm mb-2"><i class="ti ti-download me-1"></i>Download CSV Template</a>
      <form method="POST" enctype="multipart/form-data">
        <?=csrfField()?><input type="hidden" name="action" value="bulk_upload">
        <div class="mb-2">
          <input type="file" name="bulk_file" accept=".csv,.txt" class="form-control form-control-sm" required>
        </div>
        <button class="btn btn-pc btn-sm w-100"><i class="ti ti-upload me-1"></i>Upload &amp; Process</button>
      </form>
      <div class="alert alert-light border small mt-2 mb-0">
        <strong>Columns:</strong> name, holiday_date, location_id (optional, blank = all locations), is_national (1 or 0).
      </div>
      <?php if ($bulkResult): ?>
      <div class="alert alert-info small mt-2 mb-0">
        <span class="badge bg-success"><?=$bulkResult['processed']?> holiday(s) processed</span>
        <span class="badge bg-purple" style="background:#7c3aed"><?=$bulkResult['marked']?> attendance record(s) auto-marked</span>
        <?php if ($bulkResult['errors']): ?><span class="badge bg-danger"><?=count($bulkResult['errors'])?> error(s)</span><?php endif; ?>
        <?php if ($bulkResult['errors']): ?>
        <ul class="text-danger mb-0 mt-1" style="max-height:150px;overflow-y:auto">
          <?php foreach ($bulkResult['errors'] as $err): ?><li><?=clean($err)?></li><?php endforeach; ?>
        </ul>
        <?php endif; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <div class="col-md-8">
    <div class="pc-card">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <div class="fw-semibold">Holiday Calendar
          <select onchange="location='?year='+this.value" class="form-select form-select-sm d-inline-block ms-2" style="width:90px">
            <?php for($y=date('Y')-1;$y<=date('Y')+2;$y++): ?><option value="<?=$y?>" <?=$y==$year?'selected':''?>><?=$y?></option><?php endfor; ?>
          </select>
        </div>
        <span class="badge" style="background:var(--pc-brand-light);color:var(--pc-brand)"><?=count($holidays)?> Holidays</span>
      </div>
      <div class="pc-table-wrap">
        <table class="pc-table">
          <thead><tr><th>#</th><th>Holiday</th><th>Date</th><th>Day</th><th>Location</th><th>Type</th><th>Status</th><th>Actions</th></tr></thead>
          <tbody>
          <?php foreach($holidays as $i=>$h): ?>
          <tr>
            <td class="text-muted"><?=$i+1?></td>
            <td class="fw-semibold"><?=clean($h['name'])?></td>
            <td><?=fmtDate($h['holiday_date'])?></td>
            <td><?=date('D',strtotime($h['holiday_date']))?></td>
            <td><?=clean($h['location_name']??'All')?></td>
            <td><?=$h['is_national']?'<span class="badge" style="background:var(--pc-blue-bg);color:var(--pc-blue)">National</span>':'<span class="badge" style="background:var(--pc-amber-bg);color:var(--pc-amber)">Regional</span>'?></td>
            <td><?=statusBadge($h['is_active']?'active':'inactive')?></td>
            <td>
              <a href="?edit=<?=$h['id']?>&year=<?=$year?>" class="btn btn-xs btn-outline-primary py-0 px-1">Edit</a>
              <form method="POST" class="d-inline" onsubmit="return confirm('Re-mark attendance as Holiday for everyone missing an entry on this date?')">
                <?=csrfField()?><input type="hidden" name="action" value="mark_attendance"><input type="hidden" name="id" value="<?=$h['id']?>">
                <button class="btn btn-xs btn-outline-success py-0 px-1" title="Mark/refresh attendance for this holiday date"><i class="ti ti-calendar-check" style="font-size:11px"></i></button>
              </form>
              <form method="POST" class="d-inline" onsubmit="return confirm('Delete this holiday?')">
                <?=csrfField()?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=$h['id']?>">
                <button class="btn btn-xs btn-outline-danger py-0 px-1">Del</button>
              </form>
            </td>
          </tr>
          <?php endforeach; if(!$holidays): ?><tr><td colspan="8" class="text-center text-muted py-3">No holidays configured for <?=$year?></td></tr><?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
