<?php
require_once __DIR__ . '/env.php';

// DB credentials from .env
define('DB_HOST',   $_ENV['DB_HOST']   ?? 'localhost');
define('DB_NAME',   $_ENV['DB_NAME']   ?? '');
define('DB_USER',   $_ENV['DB_USER']   ?? 'root');
define('DB_PASS',   $_ENV['DB_PASS']   ?? '');

// Admin login from .env
define('ADMIN_USER', $_ENV['ADMIN_USER'] ?? 'tfcs_admin');
define('ADMIN_PASS', $_ENV['ADMIN_PASS'] ?? '');

session_start();

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: index.php');
    exit;
}

// Handle login
$loginError = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username'])) {
    $u = trim($_POST['username'] ?? '');
    $p = trim($_POST['password'] ?? '');
    if ($u === ADMIN_USER && $p === ADMIN_PASS) {
        $_SESSION['tfcs_admin'] = true;
        $_SESSION['admin_time'] = time();
        header('Location: index.php');
        exit;
    } else {
        $loginError = 'Invalid username or password.';
        // small delay to slow brute force
        sleep(1);
    }
}

// Session timeout: 2 hours
if (isset($_SESSION['tfcs_admin']) && (time() - $_SESSION['admin_time']) > 7200) {
    session_destroy();
    header('Location: index.php?timeout=1');
    exit;
}

$loggedIn = !empty($_SESSION['tfcs_admin']);

// ── DATABASE CONNECTION ───────────────────────────────────────────────────────
$pdo = null;
$dbError = '';
if ($loggedIn) {
    try {
        $pdo = new PDO(
            'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8mb4',
            DB_USER, DB_PASS,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
             PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
    } catch (PDOException $e) {
        $dbError = 'Database connection failed. Please check your DB credentials.';
    }
}

// ── ACTIONS: mark status / delete ─────────────────────────────────────────────
if ($loggedIn && $pdo && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['mark_id']) && !empty($_POST['mark_status'])) {
        $allowed = ['unread','read','replied'];
        if (in_array($_POST['mark_status'], $allowed)) {
            $s = $pdo->prepare("UPDATE enquiries SET status=? WHERE id=?");
            $s->execute([$_POST['mark_status'], (int)$_POST['mark_id']]);
        }
    }
    if (!empty($_POST['delete_id'])) {
        $s = $pdo->prepare("DELETE FROM enquiries WHERE id=?");
        $s->execute([(int)$_POST['delete_id']]);
    }
    header('Location: index.php');
    exit;
}

// ── FETCH ENQUIRIES ───────────────────────────────────────────────────────────
$enquiries = [];
$counts    = ['all' => 0, 'unread' => 0, 'read' => 0, 'replied' => 0];
$filter    = $_GET['filter'] ?? 'all';
$search    = trim($_GET['search'] ?? '');

if ($loggedIn && $pdo) {
    // counts
    $rows = $pdo->query("SELECT status, COUNT(*) as c FROM enquiries GROUP BY status")->fetchAll();
    foreach ($rows as $r) $counts[$r['status']] = (int)$r['c'];
    $counts['all'] = array_sum(array_values(array_diff_key($counts, ['all'=>0])));

    // fetch
    $where  = [];
    $params = [];
    if ($filter !== 'all') { $where[] = 'status = ?'; $params[] = $filter; }
    if ($search !== '') {
        $where[] = '(full_name LIKE ? OR email LIKE ? OR phone LIKE ? OR subject LIKE ?)';
        $like = '%'.$search.'%';
        array_push($params, $like, $like, $like, $like);
    }
    $sql = "SELECT * FROM enquiries" . ($where ? ' WHERE '.implode(' AND ',$where) : '') . " ORDER BY created_at DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $enquiries = $stmt->fetchAll();
}

// ── HELPERS ───────────────────────────────────────────────────────────────────
function e($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
function statusBadge($s) {
    $map = ['unread'=>['#e53e3e','Unread'], 'read'=>['#2d6a4f','Read'], 'replied'=>['#c9963a','Replied']];
    [$col,$lbl] = $map[$s] ?? ['#888','Unknown'];
    return "<span style='background:{$col};color:#fff;padding:3px 10px;border-radius:20px;font-size:0.72rem;font-weight:700;'>{$lbl}</span>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <title>TFCS Admin — Enquiries</title>
  <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600&family=Playfair+Display:wght@600&display=swap" rel="stylesheet"/>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
  <style>
    :root {
      --green-dark:#1a3d2b; --green-mid:#2d6a4f; --green-light:#52b788;
      --gold:#c9963a; --cream:#f7f3ec; --white:#fff;
      --text-dark:#1c1c1c; --text-mid:#4a4a4a; --text-light:#7a7a7a;
      --border:#e0d9ce; --danger:#e53e3e; --shadow:0 4px 24px rgba(0,0,0,0.08);
      --radius:12px;
    }
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
    body{font-family:'DM Sans',sans-serif;background:var(--cream);color:var(--text-dark);min-height:100vh;}
    a{text-decoration:none;color:inherit;}

    /* LOGIN */
    .login-wrap{min-height:100vh;display:flex;align-items:center;justify-content:center;background:var(--green-dark);}
    .login-card{background:var(--white);border-radius:20px;padding:48px 40px;width:100%;max-width:420px;box-shadow:var(--shadow);}
    .login-logo{display:flex;align-items:center;gap:12px;margin-bottom:32px;}
    .login-logo-icon{width:50px;height:50px;background:var(--green-dark);border-radius:10px;display:flex;align-items:center;justify-content:center;}
    .login-logo-icon i{color:var(--gold);font-size:1.4rem;}
    .login-logo h1{font-family:'Playfair Display',serif;font-size:1.2rem;color:var(--green-dark);}
    .login-logo span{font-size:0.72rem;color:var(--text-light);}
    .login-card h2{font-family:'Playfair Display',serif;font-size:1.5rem;color:var(--green-dark);margin-bottom:6px;}
    .login-card p{font-size:0.85rem;color:var(--text-light);margin-bottom:28px;}
    .field{display:flex;flex-direction:column;gap:6px;margin-bottom:18px;}
    .field label{font-size:0.8rem;font-weight:600;color:var(--text-mid);text-transform:uppercase;letter-spacing:0.06em;}
    .field input{padding:13px 16px;border:2px solid var(--border);border-radius:10px;font-family:'DM Sans',sans-serif;font-size:0.94rem;outline:none;transition:border-color 0.2s;}
    .field input:focus{border-color:var(--green-mid);}
    .login-btn{width:100%;padding:14px;background:var(--green-dark);color:var(--white);border:none;border-radius:10px;font-family:'DM Sans',sans-serif;font-size:0.95rem;font-weight:600;cursor:pointer;transition:background 0.2s;}
    .login-btn:hover{background:var(--green-mid);}
    .login-error{background:#f8d7da;color:#721c24;border:1px solid #f5c6cb;border-radius:8px;padding:10px 14px;font-size:0.85rem;margin-bottom:16px;}

    /* LAYOUT */
    .sidebar{position:fixed;top:0;left:0;bottom:0;width:240px;background:var(--green-dark);display:flex;flex-direction:column;z-index:100;}
    .sidebar-logo{padding:24px 20px;border-bottom:1px solid rgba(255,255,255,0.1);}
    .sidebar-logo h1{font-family:'Playfair Display',serif;font-size:1.1rem;color:var(--white);}
    .sidebar-logo span{font-size:0.7rem;color:rgba(255,255,255,0.45);}
    .sidebar-nav{flex:1;padding:20px 12px;display:flex;flex-direction:column;gap:4px;}
    .sidebar-link{display:flex;align-items:center;gap:12px;padding:11px 14px;border-radius:10px;font-size:0.88rem;color:rgba(255,255,255,0.65);transition:all 0.2s;cursor:pointer;}
    .sidebar-link:hover,.sidebar-link.active{background:rgba(255,255,255,0.1);color:var(--white);}
    .sidebar-link i{width:18px;text-align:center;}
    .sidebar-badge{margin-left:auto;background:var(--danger);color:#fff;font-size:0.68rem;font-weight:700;padding:2px 7px;border-radius:20px;}
    .sidebar-footer{padding:16px 20px;border-top:1px solid rgba(255,255,255,0.1);}
    .sidebar-footer a{font-size:0.82rem;color:rgba(255,255,255,0.5);display:flex;align-items:center;gap:8px;}
    .sidebar-footer a:hover{color:rgba(255,255,255,0.85);}

    .main{margin-left:240px;min-height:100vh;}
    .topbar{background:var(--white);border-bottom:1px solid var(--border);padding:16px 32px;display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:50;}
    .topbar h2{font-family:'Playfair Display',serif;font-size:1.2rem;color:var(--green-dark);}
    .topbar-right{display:flex;align-items:center;gap:16px;}
    .topbar-right a{font-size:0.85rem;color:var(--text-light);}
    .content{padding:32px;}

    /* STATS */
    .stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:20px;margin-bottom:28px;}
    .stat-card{background:var(--white);border-radius:var(--radius);padding:22px 24px;border:1px solid var(--border);display:flex;align-items:center;gap:16px;}
    .stat-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;}
    .stat-icon.all{background:#e8f5e9;} .stat-icon.all i{color:var(--green-mid);}
    .stat-icon.unread{background:#fdecea;} .stat-icon.unread i{color:var(--danger);}
    .stat-icon.read{background:#e8f5e9;} .stat-icon.read i{color:var(--green-mid);}
    .stat-icon.replied{background:#fdf6e3;} .stat-icon.replied i{color:var(--gold);}
    .stat-num{font-family:'Playfair Display',serif;font-size:1.8rem;color:var(--green-dark);font-weight:700;line-height:1;}
    .stat-lbl{font-size:0.78rem;color:var(--text-light);margin-top:2px;}

    /* FILTERS */
    .filters{background:var(--white);border:1px solid var(--border);border-radius:var(--radius);padding:16px 20px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:20px;}
    .filter-btn{padding:7px 16px;border-radius:20px;font-size:0.82rem;font-weight:600;cursor:pointer;border:2px solid var(--border);background:var(--white);color:var(--text-mid);transition:all 0.2s;}
    .filter-btn.active,.filter-btn:hover{border-color:var(--green-mid);color:var(--green-dark);background:var(--cream);}
    .search-box{margin-left:auto;display:flex;align-items:center;gap:8px;}
    .search-box input{padding:8px 14px;border:2px solid var(--border);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:0.85rem;outline:none;width:220px;}
    .search-box input:focus{border-color:var(--green-mid);}
    .search-box button{padding:8px 14px;background:var(--green-dark);color:var(--white);border:none;border-radius:8px;cursor:pointer;}

    /* TABLE */
    .table-wrap{background:var(--white);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;}
    table{width:100%;border-collapse:collapse;}
    thead{background:var(--cream);}
    thead th{padding:13px 16px;text-align:left;font-size:0.75rem;font-weight:700;text-transform:uppercase;letter-spacing:0.07em;color:var(--text-light);}
    tbody tr{border-top:1px solid var(--border);transition:background 0.15s;}
    tbody tr:hover{background:#fafaf8;}
    tbody tr.unread td{font-weight:600;}
    td{padding:14px 16px;font-size:0.88rem;color:var(--text-dark);vertical-align:top;}
    td.meta{color:var(--text-light);font-size:0.8rem;}
    td.message-cell{max-width:240px;}
    td.message-cell p{overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;color:var(--text-mid);font-size:0.82rem;}

    /* MODAL */
    .modal-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:200;align-items:center;justify-content:center;}
    .modal-overlay.open{display:flex;}
    .modal{background:var(--white);border-radius:20px;padding:36px;max-width:580px;width:90%;max-height:85vh;overflow-y:auto;position:relative;}
    .modal-close{position:absolute;top:16px;right:16px;width:32px;height:32px;border-radius:50%;background:var(--cream);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:1rem;color:var(--text-mid);}
    .modal-close:hover{background:var(--border);}
    .modal h3{font-family:'Playfair Display',serif;font-size:1.3rem;color:var(--green-dark);margin-bottom:20px;}
    .modal-field{margin-bottom:14px;}
    .modal-field label{display:block;font-size:0.75rem;font-weight:700;text-transform:uppercase;letter-spacing:0.07em;color:var(--text-light);margin-bottom:4px;}
    .modal-field p{font-size:0.92rem;color:var(--text-dark);line-height:1.6;}
    .modal-field p.message-body{background:var(--cream);border-radius:10px;padding:14px;white-space:pre-wrap;}
    .modal-actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:24px;padding-top:20px;border-top:1px solid var(--border);}

    /* BUTTONS */
    .btn-sm{padding:7px 14px;border-radius:8px;font-size:0.8rem;font-weight:600;cursor:pointer;border:none;transition:all 0.2s;}
    .btn-read{background:#e8f5e9;color:var(--green-dark);}
    .btn-read:hover{background:#c8e6c9;}
    .btn-replied{background:#fdf6e3;color:#7a5c00;}
    .btn-replied:hover{background:#fce9a0;}
    .btn-delete{background:#fdecea;color:var(--danger);}
    .btn-delete:hover{background:#f8c0bc;}
    .btn-view{background:var(--green-dark);color:var(--white);}
    .btn-view:hover{background:var(--green-mid);}

    .empty{text-align:center;padding:60px 20px;color:var(--text-light);}
    .empty i{font-size:3rem;margin-bottom:12px;display:block;opacity:0.3;}
    .db-error{background:#fdecea;color:var(--danger);border:1px solid #f5c6cb;border-radius:10px;padding:16px;margin-bottom:20px;}

    @media(max-width:900px){
      .sidebar{display:none;} .main{margin-left:0;}
      .stats-row{grid-template-columns:1fr 1fr;}
    }
  </style>
</head>
<body>

<?php if (!$loggedIn): ?>
<!-- ── LOGIN PAGE ── -->
<div class="login-wrap">
  <div class="login-card">
    <div class="login-logo">
      <div class="login-logo-icon"><img src="../images/tulaga_logo.png" alt="TFCS Logo" style="width: 100%; height: 100%; object-fit: contain; border-radius: 5px;"/></div>
      <div>
        <h1>TFCS Admin</h1>
        <span>Tulaga Farmers Co-operative Society</span>
      </div>
    </div>
    <h2>Sign In</h2>
    <p>Enter your credentials to access the enquiries dashboard.</p>
    <?php if ($loginError): ?>
      <div class="login-error"><i class="fas fa-circle-exclamation"></i> <?= e($loginError) ?></div>
    <?php endif; ?>
    <?php if (isset($_GET['timeout'])): ?>
      <div class="login-error">Your session has expired. Please sign in again.</div>
    <?php endif; ?>
    <form method="POST" autocomplete="off">
      <div class="field">
        <label for="username">Username</label>
        <input type="text" id="username" name="username" placeholder="Enter username" required autofocus />
      </div>
      <div class="field">
        <label for="password">Password</label>
        <input type="password" id="password" name="password" placeholder="Enter password" required />
      </div>
      <button type="submit" class="login-btn"><i class="fas fa-right-to-bracket"></i> Sign In</button>
    </form>
  </div>
</div>

<?php else: ?>
<!-- ── ADMIN DASHBOARD ── -->

<div class="sidebar">
  <div class="sidebar-logo">
    <h1>TFCS Admin</h1>
    <span>Enquiries Dashboard</span>
  </div>
  <nav class="sidebar-nav">
    <a href="?filter=all" class="sidebar-link <?= $filter==='all'?'active':'' ?>">
      <i class="fas fa-inbox"></i> All Enquiries
      <?php if ($counts['all']>0): ?><span class="sidebar-badge"><?= $counts['all'] ?></span><?php endif; ?>
    </a>
    <a href="?filter=unread" class="sidebar-link <?= $filter==='unread'?'active':'' ?>">
      <i class="fas fa-envelope"></i> Unread
      <?php if ($counts['unread']>0): ?><span class="sidebar-badge"><?= $counts['unread'] ?></span><?php endif; ?>
    </a>
    <a href="?filter=read" class="sidebar-link <?= $filter==='read'?'active':'' ?>">
      <i class="fas fa-envelope-open"></i> Read
    </a>
    <a href="?filter=replied" class="sidebar-link <?= $filter==='replied'?'active':'' ?>">
      <i class="fas fa-reply"></i> Replied
    </a>
    <hr style="border:none;border-top:1px solid rgba(255,255,255,0.08);margin:12px 0;">
    <a href="http://localhost/Tulagafs_Website/index (1).html" target="_blank" class="sidebar-link">
      <i class="fas fa-globe"></i> View Website
    </a>
  </nav>
  <div class="sidebar-footer">
    <a href="?logout=1"><i class="fas fa-right-from-bracket"></i> Sign Out</a>
  </div>
</div>

<div class="main">
  <div class="topbar">
    <h2>Enquiries Dashboard</h2>
    <div class="topbar-right">
      <span style="font-size:0.82rem;color:var(--text-light);">
        <i class="fas fa-circle" style="color:var(--green-light);font-size:0.5rem;"></i>
        Logged in as <strong><?= e(ADMIN_USER) ?></strong>
      </span>
      <a href="?logout=1" style="color:var(--danger);font-size:0.85rem;"><i class="fas fa-right-from-bracket"></i> Logout</a>
    </div>
  </div>

  <div class="content">
    <?php if ($dbError): ?>
      <div class="db-error"><i class="fas fa-triangle-exclamation"></i> <?= e($dbError) ?></div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="stats-row">
      <div class="stat-card">
        <div class="stat-icon all"><i class="fas fa-inbox fa-lg"></i></div>
        <div><div class="stat-num"><?= $counts['all'] ?></div><div class="stat-lbl">Total Enquiries</div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon unread"><i class="fas fa-envelope fa-lg"></i></div>
        <div><div class="stat-num"><?= $counts['unread'] ?></div><div class="stat-lbl">Unread</div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon read"><i class="fas fa-envelope-open fa-lg"></i></div>
        <div><div class="stat-num"><?= $counts['read'] ?></div><div class="stat-lbl">Read</div></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon replied"><i class="fas fa-reply fa-lg"></i></div>
        <div><div class="stat-num"><?= $counts['replied'] ?></div><div class="stat-lbl">Replied</div></div>
      </div>
    </div>

    <!-- Filters & Search -->
    <form method="GET" class="filters">
      <a href="?filter=all" class="filter-btn <?= $filter==='all'?'active':'' ?>">All (<?= $counts['all'] ?>)</a>
      <a href="?filter=unread" class="filter-btn <?= $filter==='unread'?'active':'' ?>">Unread (<?= $counts['unread'] ?>)</a>
      <a href="?filter=read" class="filter-btn <?= $filter==='read'?'active':'' ?>">Read (<?= $counts['read'] ?>)</a>
      <a href="?filter=replied" class="filter-btn <?= $filter==='replied'?'active':'' ?>">Replied (<?= $counts['replied'] ?>)</a>
      <div class="search-box">
        <input type="hidden" name="filter" value="<?= e($filter) ?>">
        <input type="text" name="search" placeholder="Search name, email, subject…" value="<?= e($search) ?>">
        <button type="submit"><i class="fas fa-search"></i></button>
      </div>
    </form>

    <!-- Table -->
    <div class="table-wrap">
      <?php if (empty($enquiries)): ?>
        <div class="empty">
          <i class="fas fa-inbox"></i>
          <p>No enquiries found<?= $search ? ' for "'.$search.'"' : '' ?>.</p>
        </div>
      <?php else: ?>
      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>Name</th>
            <th>Contact</th>
            <th>Subject</th>
            <th>Message</th>
            <th>Status</th>
            <th>Date</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($enquiries as $row): ?>
          <tr class="<?= e($row['status']) ?>"
              data-id="<?= $row['id'] ?>"
              data-name="<?= e($row['full_name']) ?>"
              data-phone="<?= e($row['phone']) ?>"
              data-email="<?= e($row['email']) ?>"
              data-location="<?= e($row['location']) ?>"
              data-subject="<?= e($row['subject']) ?>"
              data-message="<?= e($row['message']) ?>"
              data-status="<?= e($row['status']) ?>"
              data-date="<?= e($row['created_at']) ?>">
            <td class="meta">#<?= $row['id'] ?></td>
            <td><strong><?= e($row['full_name']) ?></strong></td>
            <td class="meta">
              <?= e($row['phone']) ?><br>
              <a href="mailto:<?= e($row['email']) ?>" style="color:var(--green-mid)"><?= e($row['email']) ?></a>
              <?php if ($row['location']): ?><br><?= e($row['location']) ?><?php endif; ?>
            </td>
            <td><?= e($row['subject']) ?></td>
            <td class="message-cell"><p><?= e($row['message']) ?></p></td>
            <td><?= statusBadge($row['status']) ?></td>
            <td class="meta"><?= date('d M Y<\b\r>H:i', strtotime($row['created_at'])) ?></td>
            <td>
              <button class="btn-sm btn-view open-modal" data-id="<?= $row['id'] ?>">
                <i class="fas fa-eye"></i> View
              </button>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- DETAIL MODAL -->
<div class="modal-overlay" id="modalOverlay">
  <div class="modal">
    <button class="modal-close" id="modalClose"><i class="fas fa-times"></i></button>
    <h3 id="modalTitle">Enquiry Details</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
      <div class="modal-field"><label>Name</label><p id="mName"></p></div>
      <div class="modal-field"><label>Status</label><p id="mStatus"></p></div>
      <div class="modal-field"><label>Phone</label><p id="mPhone"></p></div>
      <div class="modal-field"><label>Email</label><p id="mEmail"></p></div>
      <div class="modal-field"><label>Location</label><p id="mLocation"></p></div>
      <div class="modal-field"><label>Date</label><p id="mDate"></p></div>
    </div>
    <div class="modal-field" style="margin-top:12px;"><label>Subject</label><p id="mSubject"></p></div>
    <div class="modal-field"><label>Message</label><p id="mMessage" class="message-body"></p></div>
    <div class="modal-actions" id="mActions"></div>
  </div>
</div>

<script>
  let currentId = null;

  document.querySelectorAll('.open-modal').forEach(btn => {
    btn.addEventListener('click', () => {
      const row = btn.closest('tr');
      currentId = row.dataset.id;
      document.getElementById('mName').textContent     = row.dataset.name;
      document.getElementById('mPhone').textContent    = row.dataset.phone;
      document.getElementById('mEmail').innerHTML      = `<a href="mailto:${row.dataset.email}" style="color:var(--green-mid)">${row.dataset.email}</a>`;
      document.getElementById('mLocation').textContent = row.dataset.location || '—';
      document.getElementById('mSubject').textContent  = row.dataset.subject;
      document.getElementById('mMessage').textContent  = row.dataset.message;
      document.getElementById('mDate').textContent     = row.dataset.date;
      document.getElementById('mStatus').innerHTML     = statusBadge(row.dataset.status);

      const actions = document.getElementById('mActions');
      actions.innerHTML = `
        <a href="mailto:${row.dataset.email}?subject=Re: ${encodeURIComponent(row.dataset.subject)}" class="btn-sm btn-replied"><i class="fas fa-envelope"></i> Reply by Email</a>
        ${row.dataset.status !== 'read'    ? markBtn('read',    currentId, '✓ Mark as Read')    : ''}
        ${row.dataset.status !== 'replied' ? markBtn('replied', currentId, '✓ Mark as Replied') : ''}
        ${deleteBtn(currentId)}
      `;
      document.getElementById('modalOverlay').classList.add('open');
    });
  });

  document.getElementById('modalClose').addEventListener('click', closeModal);
  document.getElementById('modalOverlay').addEventListener('click', e => { if (e.target === e.currentTarget) closeModal(); });
  function closeModal() { document.getElementById('modalOverlay').classList.remove('open'); }

  function markBtn(status, id, label) {
    return `<form method="POST" style="display:inline">
      <input type="hidden" name="mark_id" value="${id}">
      <input type="hidden" name="mark_status" value="${status}">
      <button type="submit" class="btn-sm btn-${status}">${label}</button>
    </form>`;
  }
  function deleteBtn(id) {
    return `<form method="POST" style="display:inline" onsubmit="return confirm('Delete this enquiry permanently?')">
      <input type="hidden" name="delete_id" value="${id}">
      <button type="submit" class="btn-sm btn-delete"><i class="fas fa-trash"></i> Delete</button>
    </form>`;
  }
  function statusBadge(s) {
    const map = {unread:['#e53e3e','Unread'],read:['#2d6a4f','Read'],replied:['#c9963a','Replied']};
    const [c,l] = map[s]||['#888','Unknown'];
    return `<span style="background:${c};color:#fff;padding:3px 10px;border-radius:20px;font-size:0.72rem;font-weight:700;">${l}</span>`;
  }

  // Auto-mark unread as read when modal opens (via hidden form submit)
  document.querySelectorAll('.open-modal').forEach(btn => {
    btn.addEventListener('click', () => {
      const row = btn.closest('tr');
      if (row.dataset.status === 'unread') {
        const f = document.createElement('form');
        f.method = 'POST'; f.style.display = 'none';
        f.innerHTML = `<input name="mark_id" value="${row.dataset.id}"><input name="mark_status" value="read">`;
        document.body.appendChild(f);
        // submit after brief delay so modal opens first
        setTimeout(() => f.submit(), 800);
      }
    });
  });
</script>
<?php endif; ?>
</body>
</html>
