<?php 


require __DIR__ . '/../../includes/db.php';
require __DIR__ . '/../../includes/auth.php';



require_login(['super_admin','district_admin','ulb_admin','president','dm']);
$me = auth_user();

$ROLE = strtolower($me['role'] ?? '');
$isDistrict = ($ROLE === 'district_admin');
$isUlb      = ($ROLE === 'ulb_admin');
$isSuper    = ($ROLE === 'super_admin');
?>
<!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>Dashboard • Waste Segregation</title>

  <link rel="stylesheet" href="../assets/admin.css">

  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>

  <style>
    .kpi .k-title.ok { color:#22c55e; }
    .kpi .k-title.warn { color:#eab308; }
    .kpi .k-title.info { color:#60a5fa; }
    .chip { display:inline-block; padding:.15rem .5rem; border-radius:999px; font-size:.8rem; border:1px solid #334155; }
    .chip.ok{ background:#0b2; color:#fff; border-color:#0b2; }
    .chip.muted{ color:#94a3b8; border-color:#334155; }
    .panel .controls.gap > * { margin-right:8px; }
  </style>
</head>
<body class="dash">
  <header class="topbar">
    <div class="brand">Waste Segregation Dashboard</div>
    <div class="user">
      Logged in as <?= htmlspecialchars($me['username']) ?> (<?= htmlspecialchars(strtoupper($me['role'])) ?>)
      • <a href="/sbm/public/admin/logout.php">Logout</a>
    </div>
  </header>

  <main class="container">
       <!-- ===== Attendance (ULB / District / State) ===== -->
    <section class="panel">
      <div class="panel-head">
        <h2>Today's Attendance</h2>
        <div class="controls gap" id="att-district-controls" style="display:none;">
          <label>District:</label>
          <select id="att-district-picker"></select>
          <label>ULB:</label>
          <select id="att-ulb-picker"></select>
        </div>
      </div>

      <div class="kpis">
        <div class="kpi"><div class="k-title ok">Present Today</div><div id="att-k-present" class="k-value">-</div></div>
        <div class="kpi"><div class="k-title warn">Working Now</div><div id="att-k-working" class="k-value">-</div></div>
        <div class="kpi"><div class="k-title info">Visits Today</div><div id="att-k-data" class="k-value">-</div></div>
      </div>

      <div class="table-wrap" style="overflow:auto;">
        <table id="att-exec-table" class="data-table" style="width:100%;">
          <thead>
            <tr>
              <th style="text-align:left;">Executive</th>
              <th style="text-align:left;">Phone</th>
              <th style="text-align:center;">Present</th>
              <th style="text-align:center;">Working</th>
              <th style="text-align:right;">Visited Today</th>
              <th style="text-align:right;">Visited Total</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </section>

    <section class="panel" id="att-district-summary" style="display:none;">
      <div class="panel-head"><h2>State/District/ULB Summary</h2></div>
      <div class="table-wrap" style="overflow:auto;">
        <table id="att-ulb-table" class="data-table" style="width:100%;">
          <thead>
            <tr>
              <th>Scope</th>
              <th style="text-align:right;">Present</th>
              <th style="text-align:right;">Working</th>
              <th style="text-align:right;">Visited Today</th>
              <th style="text-align:right;">Visited Total</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </section>

    <!-- ===== Status Overview ===== -->
    <section class="panel">
      <div class="panel-head">
        <h2>Status Overview</h2>
        <div class="controls">
          <label for="ward-select">Ward:</label>
          <select id="ward-select">
            <option value="all" selected>All Wards</option>
            <option value="w1">W1</option>
            <option value="w2">W2</option>
            <option value="w3">W3</option>
            <option value="w4">W4</option>
            <option value="w5">W5</option>
          </select>
        </div>
      </div>

      <div class="kpis">
        <div class="kpi"><div class="k-title">Total Households</div><div id="k-total" class="k-value">-</div></div>
        <div class="kpi"><div class="k-title good">Segregating</div><div id="k-yes" class="k-value">-</div></div>
        <div class="kpi"><div class="k-title bad">Not Segregating</div><div id="k-no" class="k-value">-</div></div>
      </div>

      <div class="chart-wrap" style="height:260px;">
        <canvas id="pie"></canvas>
      </div>
    </section>

    <!-- ===== Ward Report ===== -->
    <section class="panel">
      <div class="panel-head">
        <h2>Ward Report ( Download Excel file ⟶ )</h2>
        <div class="controls">
          <button id="download-csv" class="btn">Download CSV</button>
        </div>
      </div>

      <div class="table-wrap" style="overflow:auto;">
        <table id="ward-table" class="data-table" style="width:100%; border-collapse:collapse;">
          <thead>
            <tr>
              <th style="text-align:left; padding:8px; border-bottom:1px solid #ddd;">Ward</th>
              <th style="text-align:right; padding:8px; border-bottom:1px solid #ddd;">Total Houses</th>
              <th style="text-align:right; padding:8px; border-bottom:1px solid #ddd;">Segregating</th>
              <th style="text-align:right; padding:8px; border-bottom:1px solid #ddd;">Not Segregating</th>
              <th style="text-align:right; padding:8px; border-bottom:1px solid #ddd;">DTDC</th>
              <th style="text-align:right; padding:8px; border-bottom:1px solid #ddd;">Segregation %</th>
            </tr>
          </thead>
          <tbody id="ward-table-body"></tbody>
          <tfoot id="ward-table-foot"></tfoot>
        </table>
      </div>

      <div class="chart-wrap" style="height:220px; margin-top:16px; display:none;">
        <canvas id="bar"></canvas>
      </div>
    </section>

    <!-- ===== House Report ===== -->
    <section class="panel">
      <div class="panel-head stack">
        <h2>House Report</h2>
        <div class="controls">
          <label for="hr-ward">Ward:</label>
          <select id="hr-ward" class="input-sm">
            <option value="all" selected>All Wards</option>
            <option value="w1">W1</option>
            <option value="w2">W2</option>
            <option value="w3">W3</option>
            <option value="w4">W4</option>
            <option value="w5">W5</option>
          </select>

          <select id="house-select" class="input-sm">
            <option value="">Select house…</option>
            <option value="*">All houses</option>
          </select>

          <label for="house-search" class="sr-only">House</label>
          <input id="house-search" class="input-sm" type="text" placeholder="Type house no…" />
          <button id="house-pick-btn" class="btn">Search</button>

          <button id="house-download-csv" class="btn">Download CSV</button>
        </div>
      </div>

      <ul id="house-suggest" class="combo-list" style="display:none;"></ul>
      <div id="house-card" class="house-card"></div>

      <div class="table-wrap" style="overflow:auto; margin-top:10px;">
        <table id="house-table" class="data-table" style="width:100%; border-collapse:collapse;">
          <thead id="house-thead">
            <tr>
              <th style="text-align:center; width:80px;">Round</th>
              <th style="text-align:center;">Training</th>
              <th style="text-align:center;">Waste Segregation</th>
              <th style="text-align:center;">DTDC</th>
            </tr>
          </thead>
          <tbody id="house-rows"></tbody>
        </table>
      </div>
    </section>

   

  </main>

  <script src="../assets/admin.js?v=12"></script>
  <script src="../assets/house_report.js?v=12"></script>

<script>
  (async () => {
    const ROLE = "<?= htmlspecialchars($ROLE) ?>".toLowerCase().trim();
    const DIST_ID = <?= (int)($me['district_id'] ?? 0) ?>;
    const ULB_ID  = <?= (int)($me['ulb_id'] ?? 0) ?>;

    const ctrlWrap = document.getElementById('att-district-controls');
    const districtPicker = document.getElementById('att-district-picker');
    const ulbPicker = document.getElementById('att-ulb-picker');
    const districtSummary = document.getElementById('att-district-summary');

    const kPresent = document.getElementById('att-k-present');  // will show Present Today
    const kWorking = document.getElementById('att-k-working');  // will show Working Now
    const kVisits  = document.getElementById('att-k-data');     // will show Total Executives

    // ---------- one-time UI tweaks ----------
    // add red chip style
    (function injectChipCSS(){
      const s = document.createElement('style');
      s.textContent = `.chip.bad{background:#dc2626;color:#fff;border-color:#dc2626}`;
      document.head.appendChild(s);
    })();

    
   // rename KPI labels (match the value IDs order)
(function renameKPIs(){
  const titles = document.querySelectorAll('.kpi .k-title');
  // 1st card => #att-k-present
  // 2nd card => #att-k-working
  // 3rd card => #att-k-data
  if (titles[0]) titles[0].textContent = 'Total Executives';
  if (titles[1]) titles[1].textContent = 'Present Today';
  if (titles[2]) titles[2].textContent = 'Working Today';
  
})();


    // rename executive table headers
    (function renameExecTableHead(){
      const ths = document.querySelectorAll('#att-exec-table thead th');
      if (ths[0]) ths[0].textContent = 'Executive Name';
      if (ths[1]) ths[1].textContent = 'Phone';
      if (ths[2]) ths[2].textContent = 'Present Today';
      if (ths[3]) ths[3].textContent = 'Working';
      if (ths[4]) ths[4].textContent = 'House Visited Today';
      if (ths[5]) ths[5].textContent = 'Total House Visited';
    })();

    // rename summary table headers
    function setSummaryTableHead(){
      const thead = document.querySelector('#att-ulb-table thead tr');
      if (!thead) return;
      thead.innerHTML = `
        <th>Scope</th>
        <th style="text-align:right;">Total Executives</th>
        <th style="text-align:right;">Present Today</th>
        <th style="text-align:right;">Working Today</th>
      `;
    }

    // ---------- helpers ----------
    function fillExecTable(items){
      const tb = document.querySelector('#att-exec-table tbody');
      tb.innerHTML = '';
      (items || []).forEach(x => {
        const presentChip = x.present_today
          ? '<span class="chip ok">Present</span>'
          : '<span class="chip bad">Absent</span>';
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>${x.name ?? ''}</td>
          <td>${x.phone ?? ''}</td>
          <td style="text-align:center;">${presentChip}</td>
          <td style="text-align:center;">${x.working_now ? '⏳' : '—'}</td>
          <td style="text-align:right;">${x.visits_today ?? 0}</td>
          <td style="text-align:right;">${x.visits_total ?? 0}</td>
        `;
        tb.appendChild(tr);
      });
    }

   // Correct KPI mapping to match visual order
function setKpisExec({totalExecs=0, present=0, working=0}={}) {
  // 1st card (Total Executives)
  kPresent.textContent = Number(totalExecs).toLocaleString();

  // 2nd card (Present Today)
  kWorking.textContent = Number(present).toLocaleString();

  // 3rd card (Working Today)
  kVisits.textContent  = Number(working).toLocaleString();
}


    function clearKPIsAndTables(){
      setKpisExec({totalExecs:0,present:0,working:0});
      fillExecTable([]);
      const tb = document.querySelector('#att-ulb-table tbody');
      if (tb) tb.innerHTML = '';
      districtSummary.style.display = 'none';
    }

    async function api(path){
      const r = await fetch(path);
      if (!r.ok) throw new Error('Request failed: ' + r.status);
      return r.json();
    }

    async function loadDistrictListAll(){
      const j = await api('api_attendance.php?mode=district_list_all');
      districtPicker.innerHTML = '';
      if (ROLE === 'super_admin') {
        const optAll = document.createElement('option');
        optAll.value = 'all';
        optAll.textContent = 'All Districts';
        districtPicker.appendChild(optAll);
      }
      (j.districts || []).forEach(d => {
        const opt = document.createElement('option');
        opt.value = d.id; opt.textContent = d.name;
        districtPicker.appendChild(opt);
      });
    }

    function addUlbPlaceholderAndAll(){
      ulbPicker.innerHTML = '';
      const ph = document.createElement('option');
      ph.value = '';
      ph.textContent = 'Select ULB…';
      ph.disabled = true;
      ph.selected = true;
      ulbPicker.appendChild(ph);
      const all = document.createElement('option');
      all.value = 'all';
      all.textContent = 'All ULBs';
      ulbPicker.appendChild(all);
    }

    async function loadUlbListForDistrict(did){
      const j = await api(`api_attendance.php?mode=ulb_list_for_district&district_id=${encodeURIComponent(did)}`);
      addUlbPlaceholderAndAll();
      (j.ulbs || []).forEach(u => {
        const opt = document.createElement('option');
        opt.value = u.id; opt.textContent = u.name;
        ulbPicker.appendChild(opt);
      });
      ulbPicker.value = ''; // force selection
      return j.ulbs || [];
    }

    async function loadUlbListAll(did = 0){
      const j = await api('api_attendance.php?mode=ulb_list_all' + (did ? `&district_id=${encodeURIComponent(did)}` : ''));
      addUlbPlaceholderAndAll();
      (j.ulbs || []).forEach(u => {
        const opt = document.createElement('option');
        opt.value = u.id;
        opt.textContent = u.name + (u.district_name ? ` (${u.district_name})` : '');
        ulbPicker.appendChild(opt);
      });
      ulbPicker.value = '';
      return j.ulbs || [];
    }

    async function loadUlbToday(uid){
      const j = await api(`api_attendance.php?mode=ulb_today&ulb_id=${encodeURIComponent(uid)}`);
      setKpisExec({
        totalExecs: j?.summary?.total_execs ?? 0,
        present:    j?.summary?.present ?? 0,
        working:    j?.summary?.working ?? 0
      });
      fillExecTable(j.executives);
      districtSummary.style.display = 'none';
    }

    // Summary renderers (for All ULBs)
    async function renderDistrictULBSummary(did){
      const j = await api('api_attendance.php?mode=state_ulbs_today&district_id=' + encodeURIComponent(did));
      // aggregate KPIs
      let totalExecs = 0, present = 0, working = 0;
      (j.ulbs || []).forEach(u => {
        totalExecs += (u.total_execs || 0);
        present    += (u.present || 0);
        working    += (u.working || 0);
      });
      setKpisExec({totalExecs, present, working});

      setSummaryTableHead();
      districtSummary.style.display = 'block';
      const tb = document.querySelector('#att-ulb-table tbody');
      tb.innerHTML = '';
      (j.ulbs || []).forEach(u => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>${u.ulb_name}${u.district_name ? ' — <small>'+u.district_name+'</small>' : ''}</td>
          <td style="text-align:right;">${u.total_execs ?? 0}</td>
          <td style="text-align:right;">${u.present ?? 0}</td>
          <td style="text-align:right;">${u.working ?? 0}</td>
        `;
        tb.appendChild(tr);
      });
    }

    async function renderStateULBSummary(){
      const j = await api('api_attendance.php?mode=state_ulbs_today');
      let totalExecs = 0, present = 0, working = 0;
      (j.ulbs || []).forEach(u => {
        totalExecs += (u.total_execs || 0);
        present    += (u.present || 0);
        working    += (u.working || 0);
      });
      setKpisExec({totalExecs, present, working});

      setSummaryTableHead();
      const head = document.querySelector('#att-district-summary .panel-head h2');
      if (head) head.textContent = 'State Summary (by ULB)';
      districtSummary.style.display = 'block';
      const tb = document.querySelector('#att-ulb-table tbody');
      tb.innerHTML = '';
      (j.ulbs || []).forEach(u => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>${u.ulb_name}${u.district_name ? ' — <small>'+u.district_name+'</small>' : ''}</td>
          <td style="text-align:right;">${u.total_execs ?? 0}</td>
          <td style="text-align:right;">${u.present ?? 0}</td>
          <td style="text-align:right;">${u.working ?? 0}</td>
        `;
        tb.appendChild(tr);
      });
    }

    // ================== Role-wise boot ==================
    if (ROLE === 'district_admin') {
      ctrlWrap.style.display = 'flex';
      await loadDistrictListAll();
      districtPicker.value = String(DIST_ID);
      districtPicker.disabled = true;

      await loadUlbListForDistrict(DIST_ID); // list only
      clearKPIsAndTables();

      ulbPicker.addEventListener('change', async (e) => {
        const ulbVal = e.target.value;
        if (!ulbVal) { clearKPIsAndTables(); return; }
        if (ulbVal === 'all') {
          await renderDistrictULBSummary(Number(DIST_ID));  // summary of all ULBs in this district
        } else {
          await loadUlbToday(ulbVal);                       // single ULB view + executive data
        }
      });

    } else if (ROLE === 'ulb_admin') {
      ctrlWrap.style.display = 'flex';
      await loadDistrictListAll();
      districtPicker.value = String(DIST_ID);
      districtPicker.disabled = true;

      await loadUlbListForDistrict(DIST_ID);
      ulbPicker.value = String(ULB_ID);
      ulbPicker.disabled = true;

      await loadUlbToday(ULB_ID);
      districtSummary.style.display = 'none';

    } else if (ROLE === 'super_admin') {
      ctrlWrap.style.display = 'flex';
      await loadDistrictListAll();   // includes "All Districts"
      await loadUlbListAll();        // populate ULBs initially (no fetch)
      clearKPIsAndTables();

      districtPicker.addEventListener('change', async (e) => {
        const val = e.target.value;
        clearKPIsAndTables();
        if (val === 'all') {
          await loadUlbListAll();
        } else {
          await loadUlbListForDistrict(val);
        }
      });

      ulbPicker.addEventListener('change', async (e) => {
        const ulbVal = e.target.value;
        const distVal = districtPicker.value;
        if (!ulbVal) { clearKPIsAndTables(); return; }

        if (ulbVal === 'all') {
          if (distVal === 'all') await renderStateULBSummary();
          else await renderDistrictULBSummary(Number(distVal));
        } else {
          await loadUlbToday(ulbVal);
        }
      });

    } else {
      // president/dm — minimal
      ctrlWrap.style.display = 'none';
      districtSummary.style.display = 'none';
    }
  })();
</script>


</body>
</html>
