<?php
include_once('../header.php');
if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_meeting_list.php');

function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$delinfo = 'none';
$addinfo = 'none';
$msg = "";

/* Delete (soft guard) */
if (isset($_GET['id']) && $_GET['id'] !== '' && (int)$_GET['id'] > 0) {
  $mid = (int)$_GET['id'];
  mysqli_query($link, "DELETE FROM `meetings` WHERE meeting_id = {$mid}");
  $delinfo = 'block';
}

/* Flash messages */
if (isset($_GET['m']) && $_GET['m'] === 'add') {
  $addinfo = 'block';
  $msg = $_data['text_15'];
} elseif (isset($_GET['m']) && $_GET['m'] === 'up') {
  $addinfo = 'block';
  $msg = $_data['text_17'];
}

/* Load meetings */
$rows   = [];
$months = []; // unique YYYY-MM => "Mon YYYY"
$res = mysqli_query($link, "SELECT meeting_id, meeting_title, meeting_description, issue_date FROM meetings ORDER BY issue_date DESC, meeting_id DESC");
while ($r = mysqli_fetch_assoc($res)) {
  $rows[] = $r;
  if (!empty($r['issue_date'])) {
    $k = date('Y-m', strtotime($r['issue_date']));
    $months[$k] = date('M Y', strtotime($r['issue_date']));
  }
}
mysqli_close($link); $link = NULL;

/* Totals */
$totalCount = count($rows);
?>
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;margin-bottom:8px;">
    <i class="fa fa-handshake-o" aria-hidden="true"></i>
    <span><?= e($_data['text_1_1']); ?></span>
  </h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL ?>dashboard.php"><i class="fa fa-dashboard"></i> <?= e($_data['home_breadcam']); ?></a></li>
    <li class="active"><?= e($_data['text_2']); ?></li>
    <li class="active"><?= e($_data['text_1_1']); ?></li>
  </ol>
</section>

<!-- Calm, readable style (matches your new unitlist.php look) -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
  :root{
    --ink:#0f172a; --ink-2:#334155; --muted:#64748b; --line:#e5e7eb;
    --brand:#3b82f6; --ok:#16a34a; --warn:#d97706; --danger:#dc2626;
    --soft:#f8fafc; --soft2:#eef2ff; --card:#ffffff;
  }
  .content-wrapper, .box, .table, label, .btn, .alert, input, select {
    font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial;
    color:var(--ink-2);
  }
  .content-header > h1{ font-weight:700; color:var(--ink); letter-spacing:.1px; }

  /* Card shell */
  .box.box-success{
    border-radius:16px; overflow:hidden; border:1px solid var(--line);
    box-shadow:0 12px 28px rgba(2,6,23,.06);
    background:var(--card);
  }
  .box .box-header{
    background:linear-gradient(135deg,var(--soft),var(--soft2));
    border-bottom:1px solid var(--line);
    display:flex; align-items:center; justify-content:space-between; gap:12px;
    padding:12px 14px;
  }
  .box .box-title{ font-weight:700; color:var(--ink); margin:0; font-size:15px; }

  /* Toolbar */
  .toolbar{ display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
  .btn, .btn:focus { outline: none; }
  .btn { border-radius:10px; border:1px solid var(--line); background:#fff; color:var(--ink-2); font-weight:600; }
  .btn i { margin-right:6px; }
  .btn:hover { background:#f8fafc; }
  .btn-slim{ padding:6px 10px; font-size:12px; line-height:1.2; }
  .btn-primary{ background:var(--brand); border-color:var(--brand); color:#fff; }
  .btn-primary:hover{ filter:brightness(0.95); }
  .btn-success-solid{ background:var(--ok); border-color:var(--ok); color:#fff; }
  .btn-success-solid:hover{ filter:brightness(0.95); }

  .input, .select{
    border:1px solid var(--line); background:#fff; border-radius:10px; padding:6px 10px; outline:none; font-weight:500; font-size:12px;
    height:32px;
  }
  .input:focus, .select:focus{ border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.12); }

  /* Counters */
  .meta{
    display:flex; align-items:center; gap:10px; flex-wrap:wrap;
    font-size:12px; color:var(--muted);
  }
  .meta .dot{ width:6px; height:6px; background:#cbd5e1; border-radius:999px; display:inline-block; }

  /* Table */
  .table.sakotable{ width:100%; border-collapse:separate; border-spacing:0 8px; }
  .table > thead > tr > th{
    border-bottom:1px solid var(--line) !important;
    color:var(--ink); font-weight:600; text-transform:uppercase; font-size:12px; letter-spacing:.2px;
    background:#fff;
  }
  .table > tbody > tr { background:#fff; border:1px solid var(--line); transition:background .15s ease; }
  .table > tbody > tr > td{ vertical-align:middle; padding:10px; font-size:13px; }
  .table > tbody > tr > td:first-child{ border-left:1px solid var(--line); border-radius:12px 0 0 12px; }
  .table > tbody > tr > td:last-child{ border-right:1px solid var(--line); border-radius:0 12px 12px 0; }
  .table > tbody > tr:hover { background:#fbfbfb; }

  .chip{
    display:inline-flex; align-items:center; gap:6px; padding:4px 8px; border-radius:999px;
    font-size:11px; font-weight:600; border:1px solid var(--line);
  }
  .chip.gray{ background:#fff; color:#6b7280; }
  .chip.blue{ background:#eff6ff; color:#1e40af; border-color:#bfdbfe; }

  .alert{ border-radius:12px; border:none; box-shadow:0 8px 24px rgba(0,0,0,.08); }
  .alert-success{ background:#ecfdf5; color:#065f46; }
  .alert-danger{ background:#fef2f2; color:#7f1d1d; }

  /* Row actions */
  .btn-row{ padding:4px 8px; font-size:12px; line-height:1.2; border-radius:10px; border:1px solid var(--line); }
  .btn-row i{ margin-right:0; font-size:12px; }
  .btn-row + .btn-row{ margin-left:6px; }
  .btn-warning-solid{ background:#f59e0b; border-color:#f59e0b; color:#fff; }
  .btn-warning-solid:hover{ filter:brightness(0.95); }
  .btn-danger-solid{ background:var(--danger); border-color:var(--danger); color:#fff; }
  .btn-danger-solid:hover{ filter:brightness(0.95); }

  /* Empty state */
  .empty{
    padding:28px; text-align:center; color:#6b7280; font-size:14px;
    border:1px dashed var(--line); border-radius:14px; background:#fff;
  }
</style>

<section class="content">
  <div class="row">
    <div class="col-xs-12">

      <!-- Alerts -->
      <div id="me" class="alert alert-danger alert-dismissable" style="display:<?= $delinfo; ?>">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button" aria-label="Close"><i class="fa fa-close"></i></button>
        <h4 style="margin-top:0;"><i class="icon fa fa-ban"></i> <?= e($_data['delete_text']); ?>!</h4>
        <?= e($_data['text_18']); ?>
      </div>
      <div id="you" class="alert alert-success alert-dismissable" style="display:<?= $addinfo; ?>">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button" aria-label="Close"><i class="fa fa-close"></i></button>
        <h4 style="margin-top:0;"><i class="icon fa fa-check"></i> <?= e($_data['success']); ?>!</h4>
        <?= e($msg); ?>
      </div>

      <div class="box box-success">
        <div class="box-header">
          <div>
            <h3 class="box-title"><?= e($_data['text_1_1']); ?></h3>
            <div class="meta" id="metaLine" aria-live="polite">
              <span id="countText">Showing <?= (int)$totalCount; ?> of <?= (int)$totalCount; ?></span>
              <span class="dot"></span>
              <span>Tip: press “/” to focus search</span>
            </div>
          </div>

          <!-- Toolbar -->
          <div class="toolbar" role="group" aria-label="Meeting list toolbar">
            <a class="btn btn-success-solid btn-slim" href="<?= WEB_URL; ?>meeting/addmeeting.php" title="<?= e($_data['text_3']); ?>">
              <i class="fa fa-plus" aria-hidden="true"></i><?= e($_data['text_3']); ?>
            </a>
            <a class="btn btn-primary btn-slim" href="<?= WEB_URL; ?>dashboard.php" title="<?= e($_data['home_breadcam']); ?>">
              <i class="fa fa-dashboard" aria-hidden="true"></i><?= e($_data['home_breadcam']); ?>
            </a>

            <select id="monthFilter" class="select" aria-label="Filter by month">
              <option value=""><?= e($_data['text_5']); ?>: All</option>
              <?php foreach ($months as $ym => $label): ?>
                <option value="<?= e($ym); ?>"><?= e($label); ?></option>
              <?php endforeach; ?>
            </select>

            <input id="searchInput" class="input" placeholder="Search reminders…" aria-label="Search reminders">
          </div>
        </div>

        <div class="box-body">
          <?php if (empty($rows)): ?>
            <div class="empty">
              <div style="font-weight:600;margin-bottom:6px;">No reminders yet</div>
              <div style="margin-bottom:12px;">Create your first reminder to get started.</div>
              <a class="btn btn-success-solid btn-slim" href="<?= WEB_URL; ?>meeting/addmeeting.php">
                <i class="fa fa-plus"></i> Add reminder
              </a>
            </div>
          <?php else: ?>
            <div class="table-responsive">
              <table id="meetingTable" class="table sakotable table-bordered table-striped">
                <thead>
                  <tr>
                    <th style="min-width:160px;"><?= e($_data['text_5']); ?></th>
                    <th><?= e($_data['text_6']); ?></th>
                    <th style="width:130px;"><?= e($_data['action_text'] ?? 'Action'); ?></th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($rows as $row):
                    $ym = $row['issue_date'] ? date('Y-m', strtotime($row['issue_date'])) : '';
                    $dateChip = $row['issue_date']
                      ? '<span class="chip blue"><i class="fa fa-calendar" aria-hidden="true"></i> ' . e($ams_helper->mySqlToDatePicker($row['issue_date'])) . '</span>'
                      : '<span class="chip gray"><i class="fa fa-info-circle" aria-hidden="true"></i> N/A</span>';
                  ?>
                  <tr data-month="<?= e($ym); ?>">
                    <td><?= $dateChip; ?></td>
                    <td><?= e($row['meeting_title']); ?></td>
                    <td>
                      <a class="btn btn-warning-solid btn-row"
                         href="<?= WEB_URL; ?>meeting/addmeeting.php?id=<?= (int)$row['meeting_id']; ?>"
                         title="<?= e($_data['edit_text']); ?>" aria-label="Edit meeting">
                        <i class="fa fa-pencil" aria-hidden="true"></i>
                      </a>
                      <a class="btn btn-danger-solid btn-row"
                         href="javascript:;" title="<?= e($_data['delete_text']); ?>" aria-label="Delete meeting"
                         onclick="deleteMeeting(<?= (int)$row['meeting_id']; ?>);">
                        <i class="fa fa-trash-o" aria-hidden="true"></i>
                      </a>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>
      </div>

    </div>
  </div>
</section>

<script>
  function deleteMeeting(Id){
    const proceed = function(){ window.location = '<?= WEB_URL; ?>meeting/meetinglist.php?id=' + Id; };
    if (typeof sweetConfirmDelete === 'function') sweetConfirmDelete(proceed);
    else if (confirm("<?= addslashes($_data['confirm'] ?? 'Are you sure you want to delete this meeting?'); ?>")) proceed();
  }

  function updateCount(){
    const total = <?= (int)$totalCount; ?>;
    const visible = document.querySelectorAll("#meetingTable tbody tr:not([style*='display: none'])").length;
    const el = document.getElementById('countText');
    if (el) el.textContent = `Showing ${visible} of ${total}`;
  }

  function applyFilters(){
    const q = (document.getElementById("searchInput").value || '').toLowerCase().trim();
    const m = document.getElementById("monthFilter").value; // YYYY-MM or ''
    const rows = document.querySelectorAll("#meetingTable tbody tr");

    rows.forEach(function(tr){
      // skip if it's a synthetic "no rows" row; we don't use one here
      const text = tr.textContent.toLowerCase();
      const rowMonth = (tr.getAttribute("data-month") || '').toString();
      let show = true;
      if (q && text.indexOf(q) === -1) show = false;
      if (m && rowMonth !== m) show = false;
      tr.style.display = show ? "" : "none";
    });

    updateCount();
  }

  // Search + filter bindings
  document.addEventListener('DOMContentLoaded', function(){
    const search = document.getElementById("searchInput");
    const month  = document.getElementById("monthFilter");

    if (search) {
      search.addEventListener('keyup', applyFilters);
      search.addEventListener('input', applyFilters);
    }
    if (month) month.addEventListener('change', applyFilters);

    // Quick focus on search with "/"
    document.addEventListener('keydown', function(e){
      if (e.key === '/' && !/input|textarea|select/i.test((e.target || {}).tagName)) {
        e.preventDefault();
        if (search) search.focus();
      }
      if (e.key === 'Escape' && search === document.activeElement) {
        search.value = '';
        applyFilters();
        search.blur();
      }
    });

    // Auto-hide alerts
    setTimeout(function(){ 
      var me = document.getElementById("me");
      var you = document.getElementById("you");
      if (me) me.style.display = 'none';
      if (you) you.style.display = 'none';
    }, 3000);
  });
</script>

<?php include_once('../footer.php'); ?>
