<?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';

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

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

// ===== Attendance guard (redirect-aware) =====

try { $pdo->exec("SET time_zone = '+05:30'"); } catch (Throwable $e) {}

try {
  $stmt = $pdo->prepare("
    SELECT action
    FROM attendance_logs
    WHERE executive_id = :eid
      AND DATE(created_at) = CURDATE()
    ORDER BY id DESC
    LIMIT 1
  ");
  $stmt->execute([':eid' => $_SESSION['user_id']]);
  $lastAction = $stmt->fetchColumn();

  if ($lastAction !== 'checkin') {
    // remember which page the user wanted
    $_SESSION['redirect_target'] = basename($_SERVER['PHP_SELF']);
    header('Location: attendance.php');
    exit;
  }
} catch (Throwable $e) {
  // optional: error_log('ATTENDANCE_GUARD_ERR: '.$e->getMessage());
}




// ---- Load assignment safely (so $as always defined) ----
$assignment = [];
$assignFile = __DIR__ . '/require_assignment.php';
if (file_exists($assignFile)) {
  $tmp = require $assignFile; // file must return [ ... ]
  if (is_array($tmp)) $assignment = $tmp;
}
$asDefaults = [
  'state_code'=>'','state_name'=>'',
  'nodal_code'=>'','nodal_name'=>'',
  'district_code'=>'','district_name'=>'',
  'ulb_code'=>'','ulb_name'=>''
];
$as = array_merge($asDefaults, $assignment);

// ---- Page vars ----
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');

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

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

/* ===================== VISIT COUNTS (server truth, sum across tables) ===================== */
$VISIT_TODAY = 0;
$VISIT_ALL   = 0;

try {
  if (!empty($_SESSION['user_id'])) {
    $eid = (int)$_SESSION['user_id'];

    // ðŸ‘‡ yahan apne tables ko sabse pehle rakho (priority order)
    $tables   = ['ws_registrations','registrations','house_visits','visits','forms','survey_entries'];
    $dateCols = ['captured_at','created_at','submitted_at','createdOn','created_on','date_time','timestamp','created'];
    $execCols = ['executive_id','user_id','created_by','exec_id'];

    // small helpers
    $fnTableExists = function(PDO $pdo, $table) {
      $q = $pdo->prepare("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ? LIMIT 1");
      $q->execute([$table]);
      return (bool)$q->fetchColumn();
    };
    $fnColExists = function(PDO $pdo, $table, $col) {
      $q = $pdo->prepare("SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ? LIMIT 1");
      $q->execute([$table, $col]);
      return (bool)$q->fetchColumn();
    };
    $safe = function($s){
      // allow only [a-z0-9_]
      return preg_match('/^[a-z0-9_]+$/i', $s) ? $s : '';
    };

    $sumToday = 0; $sumAll = 0;

    foreach ($tables as $t) {
      if (!$fnTableExists($pdo, $t)) continue;

      // find a usable date col
      $dateCol = null;
      foreach ($dateCols as $dc) { if ($fnColExists($pdo, $t, $dc)) { $dateCol = $dc; break; } }
      if (!$dateCol) continue;

      // find a usable exec col
      $execCol = null;
      foreach ($execCols as $ec) { if ($fnColExists($pdo, $t, $ec)) { $execCol = $ec; break; } }
      if (!$execCol) continue;

      // safety
      $t2 = $safe($t); $d2 = $safe($dateCol); $e2 = $safe($execCol);
      if (!$t2 || !$d2 || !$e2) continue;

      // build SQL (identifiers cannot be bound, so use validated names + backticks)
      $sqlToday = "SELECT COUNT(*) FROM `{$t2}` WHERE `{$e2}` = :eid AND DATE(`{$d2}`) = CURDATE()";
      $sqlAll   = "SELECT COUNT(*) FROM `{$t2}` WHERE `{$e2}` = :eid";

      $stT = $pdo->prepare($sqlToday);
      $stT->execute([':eid'=>$eid]);
      $sumToday += (int)$stT->fetchColumn();

      $stA = $pdo->prepare($sqlAll);
      $stA->execute([':eid'=>$eid]);
      $sumAll += (int)$stA->fetchColumn();
    }

    $VISIT_TODAY = $sumToday;
    $VISIT_ALL   = $sumAll;
  }
} catch (Throwable $e) {
  // fail-soft; keep zeros
  // error_log('VISIT_COUNT_ERR: '.$e->getMessage());
}


/* ===================== ATTENDANCE STATE (mini buttons) ===================== */
$lastAction=null;
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']]);
  $rows = $q->fetchAll(PDO::FETCH_ASSOC);
  if ($rows) {
    $merged=[];
    foreach ($rows as $r) {
      if ($r['action']==='checkin' || $r['action']==='checkout') $merged[] = [$r['action'], $r['created_at']];
    }
    if ($merged) {
      usort($merged, fn($a,$b)=>strcmp($a[1],$b[1]));
      $lastAction = end($merged)[0];
    }
  }
}
$canCheckIn  = ($lastAction !== 'checkin');
$canCheckOut = ($lastAction === 'checkin');
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="icon" type="image/png" href="favicon-ws.png">
  <title>Waste Segregation â€” Revisit</title>
  <link rel="stylesheet" href="assets/style.css">
  <style>
    .topbar{display:flex;gap:12px;align-items:center;justify-content:space-between;margin:6px 0 12px 0}
    .who{line-height:1.2}
    .who .name{font-weight:700}
    .now{font-size:.9rem;color:#6b7280}
    .btn{padding:8px 12px;border-radius:10px;border:1px solid #111827;background:#111827;color:#fff;font-weight:700;cursor:pointer}
    .btn[disabled]{background:#d1d5db;border-color:#c0c4c7;color:#6b7280;cursor:not-allowed}
    .ghost{background:#fff;color:#111827;border:1px solid #111827}
    .btn-logout{text-decoration:none;padding:6px 12px;border-radius:10px;border:1px solid #ef4444;background:#ef4444;color:#fff;font-weight:600}
    .btn-logout:hover{background:#dc2626}
    .visit-stats{display:flex;gap:10px;margin-top:6px}
    .visit-stat{display:flex;align-items:center;gap:8px;background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:6px 10px;font-size:.9rem;box-shadow:0 2px 8px rgba(0,0,0,.03)}
    .visit-stat .label{color:#6b7280}
    .visit-stat .value{font-weight:700}
    .assignment-badge{display:flex;flex-wrap:wrap;gap:8px;align-items:center;background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:10px 12px;margin:10px 0;box-shadow:0 4px 12px rgba(0,0,0,.04)}
    .assignment-badge .chip{padding:6px 10px;border-radius:999px;border:1px solid #d1d5db;background:#f9fafb;font-size:12px}
    .assignment-badge .grow{flex:1}
    .top-error{display:none}
  </style>
</head>
<body>
     <!-- ✅ Home button directly above the form card (not in header) -->
    <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">
      <div class="topbar">
        <div>
          <h1 style="margin:0 0 4px 0">Waste Segregation Revisit</h1>
          <div class="who">
            <div class="name">Executive: <?= htmlspecialchars($me['full_name'] ?? 'â€”') ?></div>
            <div class="now">Today: <span id="now-label"><?= htmlspecialchars("$nowDate $nowTime") ?></span></div>

            <!-- Assignment badge -->
            <div class="assignment-badge" role="status" aria-live="polite">
              <div class="chip">ULB: <?= htmlspecialchars($as['ulb_name']) ?> (<?= htmlspecialchars($as['ulb_code']) ?>)</div>
              <div class="grow"></div>
            </div>

            <!-- Visit counters -->
            <div class="visit-stats" role="status" aria-live="polite">
              <div class="visit-stat">
                <span class="label">House Visited Today</span>
                <span class="value" id="countToday"><?= (int)$VISIT_TODAY ?></span>
              </div>
              <div class="visit-stat">
                <span class="label">Total House Visited</span>
                <span class="value" id="countAll"><?= (int)$VISIT_ALL ?></span>
              </div>
            </div>
          </div>
        </div>

        <!-- Right side: Mini attendance + Logout -->
        <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
          <form id="mini-in" method="post" action="attendance_submit.php" autocomplete="off" novalidate>
            <input type="hidden" name="action" value="checkin">
            <input type="hidden" name="lat"  id="mini_in_lat">
            <input type="hidden" name="lng"  id="mini_in_lng">
            <input type="hidden" name="acc"  id="mini_in_acc">
            <input type="hidden" name="addr" id="mini_in_addr">
            <button class="btn" id="mini_btn_in" type="submit" <?= $canCheckIn ? '' : 'disabled' ?>>Check-in</button>
          </form>
          <form id="mini-out" method="post" action="attendance_submit.php" autocomplete="off" novalidate>
            <input type="hidden" name="action" value="checkout">
            <input type="hidden" name="lat"  id="mini_out_lat">
            <input type="hidden" name="lng"  id="mini_out_lng">
            <input type="hidden" name="acc"  id="mini_out_acc">
            <input type="hidden" name="addr" id="mini_out_addr">
            <button class="btn ghost" id="mini_btn_out" type="submit" <?= $canCheckOut ? '' : 'disabled' ?>>Check-out</button>
          </form>
          <a class="btn-logout" href="logout.php" title="Logout">Logout</a>
        </div>
      </div>

      <div id="top-error" class="top-error"></div>
    </header>

    <!-- ================== OFFICER (Revisit) Form ================== -->
    <form id="officer-form" action="submit.php" method="post" novalidate>
      <input type="hidden" name="flow" value="officer">
      <input type="hidden" name="resident_id" id="resident_id" value="">
      <input type="hidden" name="geo_lat" id="geo_lat_off">
      <input type="hidden" name="geo_lng" id="geo_lng_off">
      <input type="hidden" name="geo_acc" id="geo_acc_off">
      <input type="hidden" name="geo_addr" id="geo_addr_off">
      <input type="hidden" name="geo_village" id="geo_village_off">
      <input type="hidden" name="geo_district" id="geo_district_off">
      <input type="hidden" name="geo_state" id="geo_state_off">
      <input type="hidden" name="geo_country" id="geo_country_off">
      <input type="hidden" name="geo_cc" id="geo_cc_off">
      <input type="hidden" name="captured_at" id="captured_at_off">

      <div class="field full">
        <label for="lookup_phone">Enter Registered Mobile number to Get Details  <span class="req-inline">*</span></label>
        <div style="display:flex;gap:8px;align-items:center">
          <input id="lookup_phone" name="lookup_phone" type="tel" maxlength="10" placeholder="Mobile number (not  include +91)" required>
          <button type="button" id="lookup" class="btn primary">Get Details</button>
        </div>
      </div>

      <!-- Resident data -->
      <div id="resident-data" style="display:none; margin-top:12px">
        <section class="resident-card group-bg">
          <div class="section-title-row"><h3 class="section-title">Resident Details</h3></div>
          <div class="resident-grid">
            <div class="resident-row"><div class="resident-label">Ward</div><div class="resident-value"><div class="value-field" id="r_ward">â€”</div></div></div>
            <div class="resident-row"><div class="resident-label">House No.</div><div class="resident-value"><div class="value-field" id="r_house_no">â€”</div></div></div>
            <div class="resident-row"><div class="resident-label">Name</div><div class="resident-value"><div class="value-field" id="r_name">â€”</div></div></div>
            <div class="resident-row"><div class="resident-label">Mobile number</div><div class="resident-value"><div class="value-field" id="r_phone">â€”</div></div></div>
          </div>
        </section>

        <div id="previous-trainings" style="margin-top:18px"></div>
        <div id="training-list" style="margin-top:8px;"></div>

        <hr style="border:none;border-top:1px solid rgba(10,20,40,0.06);margin:18px 0">

        <!-- This visit -->
        <div id="next-training-section" class="next-training group-bg" style="padding:12px;border-radius:10px">
          <h3 id="next-training-label" style="margin-top:0;color:var(--gov-blue)">Training (This Visit)</h3>

          <div class="field">
            <label>Door to Door Collection (this visit) <span class="req-inline">*</span></label>
            <div class="radio-row">
              <label class="radio-label"><input type="radio" name="door_to_door" value="yes" required> Yes</label>
              <label class="radio-label"><input type="radio" name="door_to_door" value="no"> No</label>
            </div>
            <div id="err-d2d" class="error">Choose yes or no</div>
          </div>

          <div class="field">
            <label>Waste Segregation (this visit) <span class="req-inline">*</span></label>
            <div class="radio-row">
              <label class="radio-label"><input type="radio" name="waste_segregation" value="yes" required> Yes</label>
              <label class="radio-label"><input type="radio" name="waste_segregation" value="no"> No</label>
            </div>
            <div id="err-waste" class="error">Choose yes or no</div>
          </div>

          <div class="field full camera-wrap" style="margin-top:8px">
            <label>Photo for this visit <span class="req-inline">*</span></label>
            <div id="camera-area-officer">
              <video id="video" autoplay playsinline style="display:none;"></video>
              <canvas id="canvas" style="display:none"></canvas>

              <div class="camera-controls" style="display:flex;gap:8px;margin-top:8px">
                <button type="button" id="open-camera-off" class="btn">Open Camera</button>
                <button type="button" id="take-photo-off" class="btn" style="display:none">Take Photo</button>
                <button type="button" id="retake-photo-off" class="btn ghost" style="display:none">Retake</button>
              </div>

              <input type="hidden" name="photo_data" id="photo_data_off">
              <div id="photo-preview-off" style="margin-top:10px"></div>
              <div id="err-photo" class="error">Photo is required</div>
            </div>
          </div>

          <div class="field-grid" style="margin-top:10px;display:grid;grid-template-columns:1fr 1fr;gap:12px;">
            <div class="field">
              <label for="r_date">Date</label>
              <input id="r_date" name="date" type="date" value="<?= $nowDate ?>" readonly required >
            </div>
            <div class="field">
              <label for="r_time">Time</label>
              <input id="r_time" name="time" type="time" value="<?= $nowTime ?>" readonly required>
            </div>
          </div>

          <div class="actions full actions-center" style="margin-top:12px">
            <button type="button" id="save-training" class="btn primary large">Save Training</button>
          </div>
        </div>
      </div> <!-- /resident-data -->
    </form>
  </main>

  <?php $cfg = require __DIR__ . '/../includes/config.php'; ?>
  <script>
  window.APP_CFG = {
    MAPBOX_TOKEN: "<?= htmlspecialchars($cfg['mapbox_token'] ?? '') ?>",
    GOOGLE_KEY: "<?= htmlspecialchars($cfg['google_key'] ?? '') ?>"
  };
  </script>

  <script src="assets/app.js?v=6"></script>

  <!-- Mini attendance geo + live clock -->
  <script>
  (function(){
    async function reverseGeocode(lat, lng){
      const GOOGLE_KEY = <?= json_encode($cfg['google_key'] ?? '') ?>;
      try{
        if (GOOGLE_KEY) {
          const r = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${GOOGLE_KEY}`);
          const j = await r.json();
          return (j.results && j.results[0] && j.results[0].formatted_address) ? j.results[0].formatted_address : '';
        } else {
          const controller = new AbortController();
          const t=setTimeout(()=>controller.abort(),6000);
          const r=await fetch(`https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}`,{
            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 ''; }
    }

    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 }
        );
      });
    }

    function wire(prefix, btnId, formId){
      const $btn=document.getElementById(btnId);
      const $form=document.getElementById(formId);
      if(!$btn || !$form) return;
      $form.addEventListener('submit', async (e)=>{
        e.preventDefault();
        if ($btn.hasAttribute('data-submitting')) return;
        try{
          $btn.setAttribute('disabled','disabled');
          $btn.dataset.originalText=$btn.textContent;
          $btn.textContent='Getting locationâ€¦';

          const g = await getGeoOnce();
          $btn.textContent='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 ?? '';

          $btn.setAttribute('data-submitting','1');
          $btn.textContent='Submittingâ€¦';
          $form.submit();
        }catch(err){
          alert('Unable to get location. Please allow GPS (site must be HTTPS) and try again.');
          $btn.removeAttribute('disabled');
          $btn.textContent = $btn.dataset.originalText || $btn.textContent;
        }
      });
    }

    wire('mini_in',  'mini_btn_in',  'mini-in');
    wire('mini_out', 'mini_btn_out', 'mini-out');

    setInterval(()=>{
      const el=document.getElementById('now-label'); if(!el) return;
      const d=new Date(); el.textContent = d.toISOString().slice(0,10) + ' ' + d.toTimeString().slice(0,5);
    },1000);
  })();
  </script>

  <!-- Lightbox -->
  <script>
  (function(){
    if (document.querySelector('.lightbox-backdrop')) return;
    const backdrop = document.createElement('div'); backdrop.className = 'lightbox-backdrop'; backdrop.setAttribute('aria-hidden','true');
    const inner = document.createElement('div'); inner.className = 'lightbox-inner';
    const loader = document.createElement('div'); loader.className = 'lightbox-loader'; loader.style.display='none';
    const img = document.createElement('img'); img.className='lightbox-img'; img.alt='Photo preview'; img.style.display='none';
    const closeBtn = document.createElement('button'); closeBtn.className='lightbox-close'; closeBtn.innerHTML='âœ•'; closeBtn.setAttribute('aria-label','Close preview');
    inner.appendChild(loader); inner.appendChild(img); inner.appendChild(closeBtn); backdrop.appendChild(inner); document.body.appendChild(backdrop);
    let currentSrc='';
    function show(src){
      if(!src) return; currentSrc=src; backdrop.style.display='flex'; backdrop.setAttribute('aria-hidden','false'); document.body.style.overflow='hidden';
      loader.style.display=''; img.style.display='none'; img.src='';
      const tmp=new Image();
      tmp.onload=function(){ img.src=src; loader.style.display='none'; img.style.display=''; closeBtn.focus({preventScroll:true}); };
      tmp.onerror=function(){ loader.style.display='none'; img.style.display='none'; const err=document.createElement('div'); err.style.color='#fff'; err.style.padding='8px'; err.textContent='Could not load image.'; const prev=inner.querySelector('.lb-error'); if(prev) prev.remove(); err.className='lb-error'; inner.appendChild(err); setTimeout(()=>{ if(err) err.remove(); },2500); };
      tmp.src=src;
    }
    function hide(){ backdrop.style.display='none'; backdrop.setAttribute('aria-hidden','true'); document.body.style.overflow=''; img.src=''; currentSrc=''; const prev=inner.querySelector('.lb-error'); if(prev) prev.remove(); }
    closeBtn.addEventListener('click', hide);
    backdrop.addEventListener('click', (ev)=>{ if(ev.target===backdrop) hide(); });
    document.addEventListener('keydown',(ev)=>{ if(ev.key==='Escape') hide(); });
    document.addEventListener('click', function(e){
      const t=e.target; if(!t) return; let targetImg=null;
      if (t.tagName==='IMG' && (t.closest('.training-image')||t.closest('#previous-trainings')||t.closest('#training-list')||t.closest('#reg-photo')||t.closest('#photo-preview')||t.closest('#photo-preview-off'))) {
        targetImg=t;
      } else {
        const wrapper=t.closest('.training-image, #previous-trainings, #training-list, #reg-photo, #photo-preview, #photo-preview-off');
        if (wrapper) targetImg=wrapper.querySelector('img');
      }
      if (targetImg && targetImg.src) { e.preventDefault && e.preventDefault(); show(targetImg.src); }
    }, { passive:false });
  })();
  </script>
</body>
</html>
