<?php
// /sbm/public/attendance.php
declare(strict_types=1);
ini_set('display_errors','1'); // prod me 0 kar dena
error_reporting(E_ALL);

date_default_timezone_set('Asia/Kolkata');

require __DIR__ . '/session_boot.php';

if (empty($_SESSION['user_id'])) {
  header('Location: executive_login.php');
  exit;
}

require __DIR__ . '/../includes/db.php';
try { $pdo->exec("SET time_zone = '+05:30'"); } catch (Throwable $e) {}

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

$nowDate = date('Y-m-d');
$nowTime = date('H:i');

// Fetch executive (header)
$me = null;
if (!empty($_SESSION['user_id'])) {
  $stmt = $pdo->prepare('SELECT id, full_name FROM executives WHERE id = :id');
  $stmt->execute([':id' => $_SESSION['user_id']]);
  $me = $stmt->fetch(PDO::FETCH_ASSOC);
}

/* ------------------ read today's history (multiple cycles) ------------------ */
$checkins  = [];
$checkouts = [];

if (!empty($_SESSION['user_id'])) {
  $q = $pdo->prepare("
    SELECT action, created_at
    FROM attendance_logs
    WHERE executive_id = :eid
      AND DATE(created_at) = CURDATE()
    ORDER BY id ASC
  ");
  $q->execute([':eid' => $_SESSION['user_id']]);
  foreach ($q->fetchAll(PDO::FETCH_ASSOC) as $r) {
    if ($r['action'] === 'checkin')  { $checkins[]  = $r['created_at']; }
    if ($r['action'] === 'checkout') { $checkouts[] = $r['created_at']; }
  }
}

$lastIn  = $checkins  ? end($checkins)  : null;
$lastOut = $checkouts ? end($checkouts) : null;

// find the last action to toggle buttons
$lastAction = null;
if ($checkins || $checkouts) {
  $merged = [];
  foreach ($checkins as $t)  { $merged[] = ['checkin',  $t]; }
  foreach ($checkouts as $t) { $merged[] = ['checkout', $t]; }
  usort($merged, fn($a,$b) => strcmp($a[1], $b[1]));
  $lastAction = end($merged)[0]; // 'checkin' or 'checkout'
}

// Only one button active at a time
$canCheckIn  = ($lastAction !== 'checkin');  // enable if last was NOT checkin
$canCheckOut = ($lastAction === 'checkin');  // enable only if last was checkin (i.e., currently "in")
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Attendance - WS</title>

  <link rel="icon" type="image/png" href="favicon-ws.png">
<link rel="stylesheet" href="assets/style.css">
<style>
  .wrap{background:#fff;border:1px solid #e5e7eb;border-radius:14px;box-shadow:0 6px 16px rgba(0,0,0,.05);padding:16px}
  .row{display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap}
  .muted{color:#6b7280}.big{font-weight:700}
  .btn{padding:10px 14px;border-radius:10px;border:1px solid #111827;background:#111827;color:#fff;font-weight:700;transition:.2s;cursor:pointer}
  .btn:hover:not([disabled]){background:#000;transform:scale(1.02)}
  .btn[disabled]{background:#d1d5db;border-color:#c0c4c7;color:#6b7280;cursor:not-allowed}
  .ghost{background:#fff;color:#111827;border:1px solid #111827}
  .ghost:hover{background:#f3f4f6}
  .hint{color:#6b7280;font-size:.9rem}.ok{color:#065f46}.warn{color:#b45309}
  .spinner{display:inline-block;width:14px;height:14px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;vertical-align:-2px;animation:spin 0.6s linear infinite;margin-right:6px}
  @keyframes spin{to{transform:rotate(360deg)}}
  table{width:100%;border-collapse:collapse;margin-top:12px}
  td,th{border:1px solid #ddd;padding:6px;text-align:center}
  th{background:#f3f4f6}
  .flash-ok{background:#ecfdf5;border:1px solid #a7f3d0;color:#065f46;padding:10px 12px;border-radius:10px;margin:10px 0}
</style>
</head>
<body>
     <!-- 👉 Home button directly above the card -->
<div class="home-above-card">
  <a class="home-btn" href="home.php">Home</a>
</div>
<style>
    /* Home button outside centered lane — aligns with container left */
.home-above-card {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin: 0 0 10px 0;
  padding-left: 4px;  /* match your container’s left padding */
}

/* Green button style (same everywhere) */
.home-btn {
  background: linear-gradient(135deg, #2fa84f, #1f7a39);
  color: #fff;
  text-decoration: none;
  border: 0;
  padding: 8px 16px;
  border-radius: 10px;
  font-weight: 700;
  box-shadow: 0 2px 4px rgba(31, 122, 57, 0.2);
  transition: filter 0.2s;
}
.home-btn:hover {
  filter: brightness(1.08);
}



</style>
<main class="container">
   
  <header class="page-header">
    <h1 class="title">Attendance</h1>
    <div class="muted">Executive: <?= htmlspecialchars($me['full_name'] ?? '—') ?></div>
  </header>
 

  <!-- Flash message (if redirected with success) -->
  <?php if (!empty($_SESSION['flash'])): ?>
    <div class="flash-ok"><?= htmlspecialchars($_SESSION['flash']) ?></div>
    <?php unset($_SESSION['flash']); ?>
  <?php endif; ?>

  <div class="wrap" role="status" aria-live="polite">
    <div class="row">
      <div>
        <div class="big">Today: <?= htmlspecialchars($nowDate) ?></div>
        <div class="muted">Current time: <span id="now-time"><?= htmlspecialchars($nowTime) ?></span></div>
      </div>
      <div style="display:flex;gap:8px;flex-wrap:wrap">
        <!--<a href="index.php" class="btn ghost">Back to Index</a>
        <a href="work_portal.php" class="btn ghost">Work</a>-->
        <a href="logout.php" class="btn" style="background:#ef4444;border-color:#ef4444">Logout</a>
      </div>
    </div>

    <hr style="margin:12px 0;border:none;border-top:1px solid #eee">

    <!-- Only one active at a time -->
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
      <!-- Check-in -->
      <form id="form-in"  method="post" action="attendance_submit.php" autocomplete="off" novalidate>
        <input type="hidden" name="action" value="checkin">
        <input type="hidden" name="lat"  id="in_lat">
        <input type="hidden" name="lng"  id="in_lng">
        <input type="hidden" name="acc"  id="in_acc">
        <input type="hidden" name="addr" id="in_addr">
        <button class="btn" id="btn-in" type="submit" <?= $canCheckIn ? '' : 'disabled'; ?>>Check-in</button>
        <div class="hint" id="hint-in" style="margin-top:6px">
          <?php
            if ($lastIn) echo '<span class="ok">Last check-in at '.$lastIn.'</span>';
            else echo 'No check-ins yet today';
          ?>
        </div>
      </form>

      <!-- Check-out -->
      <form id="form-out" method="post" action="attendance_submit.php" autocomplete="off" novalidate>
        <input type="hidden" name="action" value="checkout">
        <input type="hidden" name="lat"  id="out_lat">
        <input type="hidden" name="lng"  id="out_lng">
        <input type="hidden" name="acc"  id="out_acc">
        <input type="hidden" name="addr" id="out_addr">
        <button class="btn" id="btn-out" type="submit" <?= $canCheckOut ? '' : 'disabled'; ?>>Check-out</button>
        <div class="hint" id="hint-out" style="margin-top:6px">
          <?php
            if (!$canCheckOut) echo 'Checkout will enable after a check-in';
            elseif ($lastOut)  echo '<span class="ok">Last check-out at '.$lastOut.'</span>';
            else               echo 'No check-outs yet today';
          ?>
        </div>
      </form>
    </div>

    <p class="hint" style="margin-top:10px">
      Location is captured when you press the button (HTTPS only). Keep GPS enabled and allow location permission.
    </p>

    <?php if ($checkins || $checkouts): ?>
      <h3 style="margin-top:16px;font-weight:600">Today&rsquo;s Attendance History</h3>
      <table>
        <tr><th>#</th><th>Action</th><th>Time (IST)</th></tr>
        <?php
          $rows = [];
          foreach ($checkins as $c)  $rows[] = ['Check-in',  $c];
          foreach ($checkouts as $c) $rows[] = ['Check-out', $c];
          usort($rows, fn($a,$b)=>strcmp($a[1],$b[1]));
          $i=1;
          foreach ($rows as $r) {
            echo "<tr><td>{$i}</td><td>{$r[0]}</td><td>{$r[1]}</td></tr>";
            $i++;
          }
        ?>
      </table>
    <?php endif; ?>
  </div>
</main>

<?php $cfg = @require __DIR__ . '/../includes/config.php'; ?>
<script>
// live clock (IST from client)
setInterval(()=>{
  const el=document.getElementById('now-time'); if(!el) return;
  try {
    const d = new Date();
    el.textContent = d.toLocaleTimeString();
  } catch(e) {}
},1000);

// ----------- Geolocation + Reverse Geocode -----------
async function reverseGeocode(lat, lng){
  const GOOGLE_KEY = <?= json_encode($cfg['google_key'] ?? '') ?>;
  try{
    if (GOOGLE_KEY) {
      const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${GOOGLE_KEY}`;
      const r = await fetch(url);
      const j = await r.json();
      const addr = (j.results && j.results[0] && j.results[0].formatted_address) ? j.results[0].formatted_address : '';
      return addr || '';
    } else {
      const controller = new AbortController();
      const t = setTimeout(()=>controller.abort(), 6000);
      const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}`;
      const r = await fetch(url, {
        headers: { 'Accept-Language':'en', 'User-Agent':'WS-Attendance/1.0 (+bizorm.com)' },
        signal: controller.signal
      });
      clearTimeout(t);
      const j = await r.json();
      return (j.display_name || '') + '';
    }
  }catch(e){
    return ''; // fail soft — coords will still be sent
  }
}

function getGeoOnce(){
  return new Promise((resolve, reject)=>{
    if (!navigator.geolocation) return reject(new Error('Geolocation not supported'));
    navigator.geolocation.getCurrentPosition(
      pos => resolve({
        lat: pos.coords.latitude,
        lng: pos.coords.longitude,
        acc: pos.coords.accuracy ?? null
      }),
      err => reject(err),
      { enableHighAccuracy:true, timeout:15000, maximumAge:0 }
    );
  });
}

async function fillGeo(prefix, $btn, $hint){
  try{
    $btn.setAttribute('disabled','disabled');
    $btn.dataset.originalText = $btn.textContent;
    $btn.innerHTML = '<span class="spinner"></span>Getting location…';

    if ($hint) $hint.textContent = 'Requesting GPS permission…';

    const g = await getGeoOnce();
    if ($hint) $hint.textContent = 'Got coordinates. Resolving address…';
    const addr = await reverseGeocode(g.lat, g.lng);

    document.getElementById(prefix+'_lat').value  = g.lat ?? '';
    document.getElementById(prefix+'_lng').value  = g.lng ?? '';
    document.getElementById(prefix+'_acc').value  = g.acc ?? '';
    document.getElementById(prefix+'_addr').value = addr ?? '';

    // require at least lat/lng
    return !!g.lat && !!g.lng;
  }catch(e){
    alert('Unable to get location. Please allow GPS (site must be HTTPS) and try again.');
    return false;
  }finally{
    // Button stays disabled only if we proceed with submit; otherwise restore
  }
}

// Bind submit guards (prevent race: only submit after fields are set)
[
  {fid:'form-in',  prefix:'in',  btn:'btn-in',  hint:'hint-in'},
  {fid:'form-out', prefix:'out', btn:'btn-out', hint:'hint-out'}
].forEach(({fid,prefix,btn,hint})=>{
  const f = document.getElementById(fid);
  if(!f) return;
  const $btn  = document.getElementById(btn);
  const $hint = document.getElementById(hint);

  f.addEventListener('submit', async (e)=>{
    e.preventDefault(); // stop native submit first
    if ($btn.hasAttribute('data-submitting')) return; // guard double clicks
    const ok = await fillGeo(prefix, $btn, $hint);
    if(!ok){
      // restore button if failed
      $btn.removeAttribute('disabled');
      $btn.textContent = $btn.dataset.originalText || $btn.textContent;
      return false;
    }
    $btn.setAttribute('data-submitting','1');
    if ($hint) $hint.textContent = 'Submitting…';
    f.submit(); // submit only after fields are filled
  });
});
</script>
</body>
</html>
