<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../../error.log');
error_reporting(E_ALL);

session_start();

// ✅ This gives you $pdo
include __DIR__ . '/config/db.php';

// ✅ Auth guard
include __DIR__ . '/config/auth.php';
require_page_access();

// ── Handle Status Update ─────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $inquiry_id_val = $_POST['record_id'] ?? null;
    $new_status     = isset($_POST['new_status']) ? (int)$_POST['new_status'] : null;

    if ($inquiry_id_val && $new_status !== null) {
        try {
            $stmt = $pdo->prepare("UPDATE conference_proceedings SET status = ? WHERE id = ?");
            $stmt->execute([$new_status, $inquiry_id_val]);
            $_SESSION['cp_success'] = "Status updated successfully.";
        } catch (PDOException $e) {
            error_log("CP status update error: " . $e->getMessage());
            $_SESSION['cp_error'] = "Error updating status: " . $e->getMessage();
        }
    }

    $qs = http_build_query(array_filter([
        'status'  => $_GET['status']  ?? '',
        'search'  => $_GET['search']  ?? '',
        'country' => $_GET['country'] ?? '',
    ]));
    header("Location: " . basename($_SERVER['PHP_SELF']) . ($qs ? "?$qs" : ''));
    exit();
}

// ── Handle Delete ────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_record'])) {
    $del_id = $_POST['record_id'] ?? null;
    if ($del_id) {
        try {
            $stmt = $pdo->prepare("DELETE FROM conference_proceedings WHERE id = ?");
            $stmt->execute([$del_id]);
            $_SESSION['cp_success'] = "Inquiry deleted successfully.";
        } catch (PDOException $e) {
            $_SESSION['cp_error'] = "Error deleting record: " . $e->getMessage();
        }
    }
    $qs = http_build_query(array_filter([
        'status'  => $_GET['status']  ?? '',
        'search'  => $_GET['search']  ?? '',
        'country' => $_GET['country'] ?? '',
    ]));
    header("Location: " . basename($_SERVER['PHP_SELF']) . ($qs ? "?$qs" : ''));
    exit();
}

// ── Filters ──────────────────────────────────────────────
$selectedStatus  = isset($_GET['status'])  && $_GET['status']  !== '' ? (int)$_GET['status']  : null;
$searchQuery     = trim($_GET['search']  ?? '');
$selectedCountry = trim($_GET['country'] ?? '');

// ── Fetch Data ───────────────────────────────────────────
try {
    $sql    = "SELECT * FROM conference_proceedings WHERE 1=1";
    $params = [];

    if ($selectedStatus !== null) {
        $sql     .= " AND status = ?";
        $params[] = $selectedStatus;
    }
    if ($searchQuery) {
        $sql     .= " AND (conference_name LIKE ? OR organizer_name LIKE ? OR organizer_email LIKE ? OR inquiry_id LIKE ?)";
        $like     = "%$searchQuery%";
        $params   = array_merge($params, [$like, $like, $like, $like]);
    }
    if ($selectedCountry) {
        $sql     .= " AND conference_country = ?";
        $params[] = $selectedCountry;
    }

    $sql .= " ORDER BY created_at DESC";

    $stmt    = $pdo->prepare($sql);
    $stmt->execute($params);
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // For country filter dropdown
    $countryStmt = $pdo->query("SELECT DISTINCT conference_country FROM conference_proceedings ORDER BY conference_country ASC");
    $allCountries = $countryStmt->fetchAll(PDO::FETCH_COLUMN);

    // Stats
    $statStmt = $pdo->query("SELECT status, COUNT(*) as cnt FROM conference_proceedings GROUP BY status");
    $rawStats = $statStmt->fetchAll(PDO::FETCH_ASSOC);
    $stats = ['total' => 0, 'pending' => 0, 'reviewed' => 0, 'completed' => 0];
    foreach ($rawStats as $r) {
        $stats['total'] += $r['cnt'];
        if ($r['status'] == 0) $stats['pending']   = $r['cnt'];
        if ($r['status'] == 1) $stats['reviewed']  = $r['cnt'];
        if ($r['status'] == 2) $stats['completed'] = $r['cnt'];
    }

} catch (PDOException $e) {
    error_log("CP fetch error: " . $e->getMessage());
    $records = [];
    $allCountries = [];
    $stats = ['total' => 0, 'pending' => 0, 'reviewed' => 0, 'completed' => 0];
}

function cpStatusBadge($status) {
    switch ((int)$status) {
        case 0: return '<span class="cp-badge-status cp-s-pending">Pending</span>';
        case 1: return '<span class="cp-badge-status cp-s-reviewed">Reviewed</span>';
        case 2: return '<span class="cp-badge-status cp-s-completed">Completed</span>';
        default: return '<span class="cp-badge-status cp-s-unknown">Unknown</span>';
    }
}

$active_section = 'conference_proceedings';
$user_name = $_SESSION['username'] ?? 'Admin';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Conference Proceedings – RSIS Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <style>
        body { font-family: 'Roboto', sans-serif; margin: 0; height: 100vh; overflow: hidden; }
        body.dark { background-color: #1a202c; color: #e2e8f0; }

        /* Sidebar (same as reviewer_applications.php) */
        .sidebar { width:250px; background:#2d3748; color:white; transition:all .3s; height:100%; position:fixed; top:0; left:0; z-index:10; overflow-y:auto; }
        .sidebar.collapsed { width:70px; }
        .sidebar.collapsed .sidebar-title,
        .sidebar.collapsed nav ul li a span,
        .sidebar.collapsed .submenu,
        .sidebar.collapsed button span.label { display:none !important; }
        .sidebar.collapsed .nav-item i.main-icon { display:inline-block !important; font-size:22px; margin-right:0; }
        .sidebar.collapsed .nav-item i.arrow-icon,
        .sidebar.collapsed .submenu { display:none !important; }
        .content { margin-left:250px; padding:20px; transition:margin-left .3s; height:100vh; overflow-y:auto; }
        .content.collapsed-sidebar { margin-left:70px; }
        .nav-item { padding:10px 15px; cursor:pointer; transition:background .2s; }
        .nav-item:hover { background:#4a5568; }
        .nav-item.active { background:#4a5568; border-left:4px solid #4299e1; }

        /* Dark mode overrides */
        body.dark .bg-white { background-color:#2d3748; }
        body.dark .text-gray-700 { color:#d1d5db; }
        body.dark .bg-gray-50 { background-color:#3f3f3f; }
        body.dark input, body.dark select { background-color:#374151; color:#e5e7eb; border-color:#4b5563; }

        /* Stats Cards */
        .stat-card { background:#fff; border-radius:12px; padding:20px 24px; box-shadow:0 2px 12px rgba(0,0,0,.07); display:flex; align-items:center; gap:16px; }
        body.dark .stat-card { background:#2d3748; }
        .stat-icon { width:52px; height:52px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-size:22px; flex-shrink:0; }
        .stat-num { font-size:1.8rem; font-weight:700; line-height:1; }
        .stat-lbl { font-size:.8rem; color:#6b7a99; font-weight:500; margin-top:3px; }

        /* Alerts */
        .cp-alert { padding:14px 18px; border-radius:8px; margin-bottom:18px; display:flex; align-items:center; gap:10px; font-size:.92rem; }
        .cp-alert-ok  { background:#d1fae5; color:#065f46; border:1px solid #10b981; }
        .cp-alert-err { background:#fee2e2; color:#991b1b; border:1px solid #ef4444; }

        /* Table */
        .table-container { overflow-x:auto; max-height:520px; }
        table { width:100%; border-collapse:collapse; font-size:.84rem; }
        thead tr { background:#f8fafc; position:sticky; top:0; z-index:2; }
        body.dark thead tr { background:#374151; }
        th { padding:12px 14px; text-align:left; font-weight:600; color:#374151; border-bottom:2px solid #e5e7eb; white-space:nowrap; }
        body.dark th { color:#d1d5db; border-color:#4b5563; }
        td { padding:11px 14px; border-bottom:1px solid #f1f5f9; vertical-align:middle; }
        body.dark td { border-color:#374151; }
        tr:hover td { background:#f8faff; }
        body.dark tr:hover td { background:#374151; }
        .truncate-cell { max-width:180px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }

        /* Status badges */
        .cp-badge-status { display:inline-block; padding:3px 10px; border-radius:20px; font-size:.75rem; font-weight:600; }
        .cp-s-pending   { background:#fef3c7; color:#92400e; }
        .cp-s-reviewed  { background:#dbeafe; color:#1e40af; }
        .cp-s-completed { background:#d1fae5; color:#065f46; }
        .cp-s-unknown   { background:#f1f5f9; color:#64748b; }

        /* Column toggles */
        .toggle-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(160px,1fr)); gap:10px; }

        /* Modal */
        .cp-modal { display:none; position:fixed; inset:0; background:rgba(0,0,0,.55); z-index:60; align-items:center; justify-content:center; padding:20px; }
        .cp-modal.open { display:flex; }
        .cp-modal-box { background:#fff; border-radius:16px; max-width:860px; width:100%; max-height:90vh; overflow-y:auto; box-shadow:0 20px 60px rgba(0,0,0,.25); }
        body.dark .cp-modal-box { background:#2d3748; }
        .cp-modal-head { background:linear-gradient(135deg,#1a4fa0,#3a6ec8); color:#fff; padding:22px 28px; border-radius:16px 16px 0 0; display:flex; align-items:center; justify-content:space-between; }
        .cp-modal-body { padding:28px; }
        .detail-grid { display:grid; grid-template-columns:1fr 1fr; gap:18px; }
        @media(max-width:640px){ .detail-grid { grid-template-columns:1fr; } }
        .detail-item label { font-size:.75rem; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:#6b7a99; display:block; margin-bottom:4px; }
        .detail-item p { color:#1a2340; font-size:.9rem; margin:0; }
        body.dark .detail-item p { color:#e2e8f0; }
        .section-heading { font-size:.8rem; font-weight:700; text-transform:uppercase; letter-spacing:.08em; color:#1a4fa0; padding-bottom:8px; border-bottom:2px solid #e8f0fe; margin:20px 0 14px; }

        @media(max-width:768px){
            .sidebar { transform:translateX(-250px); }
            .sidebar.mobile-open { transform:translateX(0); }
            .content { margin-left:0; }
        }
    </style>
</head>
<body class="bg-gray-100 mt-5">

    <button id="sidebarToggleBtn" onclick="toggleMobileSidebar()"
        class="fixed top-3 left-3 z-20 bg-gray-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>

    <?php include __DIR__ . '/include/sidebar.php'; ?>

    <div class="content" id="content">

        <!-- Header -->
        <header class="bg-white shadow p-4 flex justify-between items-center rounded-lg mb-6">
            <div class="hidden md:block">
                <h1 class="text-2xl font-semibold text-gray-700">
                    <i class="fas fa-book-open mr-2 text-blue-600"></i>Conference Proceedings
                </h1>
                <p class="text-sm text-gray-400 mt-1">Manage all conference publishing inquiries</p>
            </div>
            <div class="flex items-center space-x-4">
                <span class="bg-blue-100 text-blue-800 px-4 py-2 rounded-full font-semibold text-sm">
                    <?php echo count($records); ?> result<?php echo count($records) != 1 ? 's' : ''; ?>
                </span>
                <span class="text-gray-700 text-sm">Welcome, <strong><?php echo htmlspecialchars($user_name); ?></strong></span>
                <button id="darkModeToggle" class="text-xl text-gray-600 hover:text-gray-800" title="Toggle Dark Mode">
                    <i class="fas fa-moon"></i>
                </button>
                <a href="logout.php" class="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600 text-sm">
                    <i class="fas fa-sign-out-alt mr-1"></i>Logout
                </a>
            </div>
        </header>

        <main class="pb-10">

            <!-- Flash messages -->
            <?php if (isset($_SESSION['cp_success'])): ?>
                <div class="cp-alert cp-alert-ok">
                    <i class="fas fa-check-circle"></i>
                    <?php echo htmlspecialchars($_SESSION['cp_success']); unset($_SESSION['cp_success']); ?>
                </div>
            <?php endif; ?>
            <?php if (isset($_SESSION['cp_error'])): ?>
                <div class="cp-alert cp-alert-err">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($_SESSION['cp_error']); unset($_SESSION['cp_error']); ?>
                </div>
            <?php endif; ?>

            <!-- Stats -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                <div class="stat-card">
                    <div class="stat-icon" style="background:#e8f0fe">
                        <i class="fas fa-inbox text-blue-600"></i>
                    </div>
                    <div>
                        <div class="stat-num text-gray-800"><?php echo $stats['total']; ?></div>
                        <div class="stat-lbl">Total Inquiries</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background:#fef3c7">
                        <i class="fas fa-clock text-yellow-600"></i>
                    </div>
                    <div>
                        <div class="stat-num text-yellow-700"><?php echo $stats['pending']; ?></div>
                        <div class="stat-lbl">Pending</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background:#dbeafe">
                        <i class="fas fa-eye text-blue-500"></i>
                    </div>
                    <div>
                        <div class="stat-num text-blue-700"><?php echo $stats['reviewed']; ?></div>
                        <div class="stat-lbl">Reviewed</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background:#d1fae5">
                        <i class="fas fa-check-double text-green-600"></i>
                    </div>
                    <div>
                        <div class="stat-num text-green-700"><?php echo $stats['completed']; ?></div>
                        <div class="stat-lbl">Completed</div>
                    </div>
                </div>
            </div>

            <!-- Filters -->
            <div class="bg-white p-6 rounded-lg shadow mb-6">
                <h2 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fas fa-filter mr-2 text-blue-600"></i>Filter Inquiries
                </h2>
                <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Search</label>
                        <input type="text" name="search" value="<?php echo htmlspecialchars($searchQuery); ?>"
                            placeholder="Name, email, ref ID…"
                            class="w-full border border-gray-300 rounded-md p-2 text-sm">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select name="status" class="w-full border border-gray-300 rounded-md p-2 text-sm">
                            <option value="">All Statuses</option>
                            <option value="0" <?php echo $selectedStatus === 0 ? 'selected' : ''; ?>>Pending</option>
                            <option value="1" <?php echo $selectedStatus === 1 ? 'selected' : ''; ?>>Reviewed</option>
                            <option value="2" <?php echo $selectedStatus === 2 ? 'selected' : ''; ?>>Completed</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Country</label>
                        <select name="country" class="w-full border border-gray-300 rounded-md p-2 text-sm">
                            <option value="">All Countries</option>
                            <?php foreach ($allCountries as $c): ?>
                                <option value="<?php echo htmlspecialchars($c); ?>" <?php echo $selectedCountry === $c ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($c); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="flex items-end gap-2">
                        <button type="submit" class="flex-1 bg-blue-600 text-white py-2 rounded-md hover:bg-blue-700 text-sm flex items-center justify-center gap-2">
                            <i class="fas fa-search"></i>Apply
                        </button>
                        <?php if ($selectedStatus !== null || $searchQuery || $selectedCountry): ?>
                            <a href="<?php echo basename($_SERVER['PHP_SELF']); ?>"
                               class="px-4 py-2 border border-gray-300 rounded-md text-sm text-gray-600 hover:bg-gray-50 flex items-center gap-1">
                                <i class="fas fa-times"></i>Clear
                            </a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>

            <!-- Column Toggles -->
            <div class="bg-white p-5 rounded-lg shadow mb-6">
                <h2 class="text-lg font-semibold mb-3 flex items-center">
                    <i class="fas fa-columns mr-2 text-purple-600"></i>Toggle Columns
                </h2>
                <div class="toggle-grid">
                    <?php
                    $cols = [
                        'col_id'            => 'ID',
                        'col_ref'           => 'Reference ID',
                        'col_confname'      => 'Conference Name',
                        'col_dates'         => 'Conf. Dates',
                        'col_city'          => 'City',
                        'col_country'       => 'Country',
                        'col_website'       => 'Website',
                        'col_orgname'       => 'Organizer Name',
                        'col_orgemail'      => 'Organizer Email',
                        'col_orgphone'      => 'Phone',
                        'col_papers'        => 'Expected Papers',
                        'col_pubdate'       => 'Pref. Pub Date',
                        'col_special'       => 'Special Requests',
                        'col_status'        => 'Status',
                        'col_createdat'     => 'Submitted At',
                        'col_action'        => 'Actions',
                    ];
                    foreach ($cols as $key => $label): ?>
                        <label class="flex items-center gap-2 text-sm">
                            <input type="checkbox" class="toggle-col" data-col="<?php echo $key; ?>" checked>
                            <?php echo $label; ?>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Table -->
            <div class="bg-white p-6 rounded-lg shadow">
                <div class="flex justify-between items-center mb-4 flex-wrap gap-3">
                    <h2 class="text-lg font-semibold flex items-center">
                        <i class="fas fa-table mr-2 text-green-600"></i>Inquiries List
                    </h2>
                    <button onclick="exportExcel()" class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 text-sm flex items-center gap-2">
                        <i class="fas fa-file-excel"></i>Export to Excel
                    </button>
                </div>

                <?php if (empty($records)): ?>
                    <div class="text-center py-16">
                        <i class="fas fa-inbox text-6xl text-gray-200 mb-4"></i>
                        <p class="text-gray-500 text-lg">No inquiries found.</p>
                        <p class="text-gray-400 text-sm mt-1">Try adjusting your filters.</p>
                    </div>
                <?php else: ?>
                    <div class="table-container">
                        <table id="cpTable">
                            <thead>
                                <tr>
                                    <th data-col="col_id">ID</th>
                                    <th data-col="col_ref">Reference ID</th>
                                    <th data-col="col_confname">Conference Name</th>
                                    <th data-col="col_dates">Conf. Dates</th>
                                    <th data-col="col_city">City</th>
                                    <th data-col="col_country">Country</th>
                                    <th data-col="col_website">Website</th>
                                    <th data-col="col_orgname">Organizer Name</th>
                                    <th data-col="col_orgemail">Organizer Email</th>
                                    <th data-col="col_orgphone">Phone</th>
                                    <th data-col="col_papers">Papers</th>
                                    <th data-col="col_pubdate">Pref. Pub Date</th>
                                    <th data-col="col_special">Special Requests</th>
                                    <th data-col="col_status">Status</th>
                                    <th data-col="col_createdat">Submitted At</th>
                                    <th data-col="col_action">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($records as $row): ?>
                                    <tr>
                                        <td data-col="col_id">
                                            <span class="font-mono text-xs bg-gray-100 px-2 py-1 rounded">#<?php echo $row['id']; ?></span>
                                        </td>
                                        <td data-col="col_ref">
                                            <span class="font-mono text-xs bg-blue-50 text-blue-700 px-2 py-1 rounded">
                                                <?php echo htmlspecialchars($row['inquiry_id']); ?>
                                            </span>
                                        </td>
                                        <td data-col="col_confname" class="truncate-cell" title="<?php echo htmlspecialchars($row['conference_name']); ?>">
                                            <span class="font-medium text-gray-800"><?php echo htmlspecialchars($row['conference_name']); ?></span>
                                        </td>
                                        <td data-col="col_dates" style="white-space:nowrap">
                                            <?php if ($row['conference_date_start']): ?>
                                                <span class="text-xs text-gray-600">
                                                    <?php echo date('M d, Y', strtotime($row['conference_date_start'])); ?>
                                                    <?php if ($row['conference_date_end']): ?>
                                                        → <?php echo date('M d, Y', strtotime($row['conference_date_end'])); ?>
                                                    <?php endif; ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-gray-400 text-xs">N/A</span>
                                            <?php endif; ?>
                                        </td>
                                        <td data-col="col_city"><?php echo htmlspecialchars($row['conference_city']); ?></td>
                                        <td data-col="col_country">
                                            <span class="text-xs bg-teal-50 text-teal-700 px-2 py-1 rounded">
                                                <?php echo htmlspecialchars($row['conference_country']); ?>
                                            </span>
                                        </td>
                                        <td data-col="col_website">
                                            <a href="<?php echo htmlspecialchars($row['conference_website']); ?>" target="_blank"
                                               class="text-blue-600 hover:underline text-xs flex items-center gap-1">
                                                <i class="fas fa-external-link-alt text-xs"></i>
                                                <?php
                                                $url = $row['conference_website'];
                                                $display = preg_replace('#^https?://(www\.)?#', '', $url);
                                                echo htmlspecialchars(strlen($display) > 28 ? substr($display, 0, 28) . '…' : $display);
                                                ?>
                                            </a>
                                        </td>
                                        <td data-col="col_orgname">
                                            <div class="font-medium text-gray-800"><?php echo htmlspecialchars($row['organizer_name']); ?></div>
                                        </td>
                                        <td data-col="col_orgemail">
                                            <a href="mailto:<?php echo htmlspecialchars($row['organizer_email']); ?>"
                                               class="text-blue-600 hover:underline text-xs">
                                                <?php echo htmlspecialchars($row['organizer_email']); ?>
                                            </a>
                                        </td>
                                        <td data-col="col_orgphone" class="text-xs text-gray-600">
                                            <?php echo htmlspecialchars($row['organizer_phone'] ?? 'N/A'); ?>
                                        </td>
                                        <td data-col="col_papers" class="text-center">
                                            <?php if ($row['expected_papers']): ?>
                                                <span class="bg-purple-50 text-purple-700 px-2 py-1 rounded text-xs font-semibold">
                                                    <?php echo (int)$row['expected_papers']; ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-gray-400 text-xs">N/A</span>
                                            <?php endif; ?>
                                        </td>
                                        <td data-col="col_pubdate" class="text-xs text-gray-600">
                                            <?php echo $row['preferred_pub_date'] ? date('M d, Y', strtotime($row['preferred_pub_date'])) : 'N/A'; ?>
                                        </td>
                                        <td data-col="col_special" class="truncate-cell text-xs text-gray-600"
                                            title="<?php echo htmlspecialchars($row['special_requests'] ?? ''); ?>">
                                            <?php echo $row['special_requests'] ? htmlspecialchars($row['special_requests']) : '<span class="text-gray-400">—</span>'; ?>
                                        </td>
                                        <td data-col="col_status">
                                            <?php echo cpStatusBadge($row['status']); ?>
                                        </td>
                                        <td data-col="col_createdat" class="text-xs text-gray-500" style="white-space:nowrap">
                                            <?php echo date('Y-m-d H:i', strtotime($row['created_at'])); ?>
                                        </td>
                                        <td data-col="col_action">
                                            <div class="flex items-center gap-2">
                                                <!-- View -->
                                                <button onclick="viewDetail(<?php echo $row['id']; ?>)"
                                                    class="text-purple-500 hover:text-purple-700" title="View Details">
                                                    <i class="fas fa-eye"></i>
                                                </button>

                                                <!-- Status change dropdown -->
                                                <form method="POST" class="inline flex items-center">
                                                    <input type="hidden" name="record_id" value="<?php echo $row['id']; ?>">
                                                    <select name="new_status" onchange="this.form.submit()"
                                                        class="text-xs border border-gray-200 rounded px-1 py-0.5 bg-white cursor-pointer"
                                                        title="Change Status">
                                                        <option value="0" <?php echo $row['status']==0?'selected':''; ?>>Pending</option>
                                                        <option value="1" <?php echo $row['status']==1?'selected':''; ?>>Reviewed</option>
                                                        <option value="2" <?php echo $row['status']==2?'selected':''; ?>>Completed</option>
                                                    </select>
                                                    <input type="hidden" name="update_status" value="1">
                                                </form>

                                                <!-- Delete -->
                                                <form method="POST" class="inline"
                                                    onsubmit="return confirm('Delete this inquiry permanently?');">
                                                    <input type="hidden" name="record_id" value="<?php echo $row['id']; ?>">
                                                    <button type="submit" name="delete_record"
                                                        class="text-red-500 hover:text-red-700" title="Delete">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <!-- Detail Modal -->
    <div id="cpModal" class="cp-modal">
        <div class="cp-modal-box">
            <div class="cp-modal-head">
                <div>
                    <h3 class="text-xl font-bold m-0" id="modalTitle">Inquiry Details</h3>
                    <p class="text-sm opacity-80 mt-1 m-0" id="modalSubtitle"></p>
                </div>
                <button onclick="closeModal()" class="text-white hover:text-gray-200 text-2xl">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="cp-modal-body" id="modalBody">
                <!-- populated by JS -->
            </div>
        </div>
    </div>

    <script>
    // All records for modal
    const ALL_RECORDS = <?php echo json_encode($records); ?>;

    // ── Sidebar toggle ──────────────────────────────────
    document.getElementById('toggleSidebar')?.addEventListener('click', () => {
        document.getElementById('sidebar')?.classList.toggle('collapsed');
        document.getElementById('content')?.classList.toggle('collapsed-sidebar');
    });
    function toggleMobileSidebar() {
        document.getElementById('sidebar')?.classList.toggle('mobile-open');
    }

    // ── Dark Mode ──────────────────────────────────────
    const dmBtn = document.getElementById('darkModeToggle');
    dmBtn.addEventListener('click', function () {
        document.body.classList.toggle('dark');
        this.querySelector('i').classList.toggle('fa-moon');
        this.querySelector('i').classList.toggle('fa-sun');
        localStorage.setItem('darkMode', document.body.classList.contains('dark') ? 'enabled' : 'disabled');
    });
    if (localStorage.getItem('darkMode') === 'enabled') {
        document.body.classList.add('dark');
        dmBtn.querySelector('i').classList.replace('fa-moon', 'fa-sun');
    }

    // ── Column Toggles ─────────────────────────────────
    const STORAGE_KEY = 'cpColumnState';
    document.querySelectorAll('.toggle-col').forEach(cb => {
        cb.addEventListener('change', function () {
            const col = this.getAttribute('data-col');
            document.querySelectorAll(`[data-col="${col}"]`).forEach(el => {
                el.style.display = this.checked ? '' : 'none';
            });
            const state = {};
            document.querySelectorAll('.toggle-col').forEach(c => { state[c.dataset.col] = c.checked; });
            localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
        });
    });
    const savedState = localStorage.getItem(STORAGE_KEY);
    if (savedState) {
        const state = JSON.parse(savedState);
        document.querySelectorAll('.toggle-col').forEach(cb => {
            const col = cb.dataset.col;
            if (state.hasOwnProperty(col)) { cb.checked = state[col]; cb.dispatchEvent(new Event('change')); }
        });
    }

    // ── Export Excel ───────────────────────────────────
    function exportExcel() {
        const wb = XLSX.utils.table_to_book(document.getElementById('cpTable'), { sheet: "Conference Proceedings" });
        XLSX.writeFile(wb, `Conference_Proceedings_${new Date().toISOString().slice(0,10)}.xlsx`);
    }

    // ── Modal ──────────────────────────────────────────
    function viewDetail(id) {
        const row = ALL_RECORDS.find(r => r.id == id);
        if (!row) return;

        document.getElementById('modalTitle').textContent = row.conference_name;
        document.getElementById('modalSubtitle').textContent = 'Ref: ' + row.inquiry_id;

        const fmt = v => v || '<span style="color:#aaa">N/A</span>';
        const fmtDate = v => v ? new Date(v).toLocaleDateString('en-GB', {day:'2-digit',month:'short',year:'numeric'}) : 'N/A';
        const statusLabel = ['Pending','Reviewed','Completed'][row.status] ?? 'Unknown';

        document.getElementById('modalBody').innerHTML = `
            <div class="section-heading">Conference Details</div>
            <div class="detail-grid">
                <div class="detail-item"><label>Reference ID</label><p>${fmt(row.inquiry_id)}</p></div>
                <div class="detail-item"><label>Conference Name</label><p>${fmt(row.conference_name)}</p></div>
                <div class="detail-item"><label>Start Date</label><p>${fmtDate(row.conference_date_start)}</p></div>
                <div class="detail-item"><label>End Date</label><p>${fmtDate(row.conference_date_end)}</p></div>
                <div class="detail-item"><label>City</label><p>${fmt(row.conference_city)}</p></div>
                <div class="detail-item"><label>Country</label><p>${fmt(row.conference_country)}</p></div>
                <div class="detail-item" style="grid-column:1/-1">
                    <label>Website</label>
                    <p><a href="${row.conference_website}" target="_blank" style="color:#1a4fa0">${fmt(row.conference_website)}</a></p>
                </div>
            </div>

            <div class="section-heading">Organizer Information</div>
            <div class="detail-grid">
                <div class="detail-item"><label>Organizer Name</label><p>${fmt(row.organizer_name)}</p></div>
                <div class="detail-item"><label>Email</label>
                    <p><a href="mailto:${row.organizer_email}" style="color:#1a4fa0">${fmt(row.organizer_email)}</a></p>
                </div>
                <div class="detail-item"><label>Phone</label><p>${fmt(row.organizer_phone)}</p></div>
            </div>

            <div class="section-heading">Publication Details</div>
            <div class="detail-grid">
                <div class="detail-item"><label>Expected Papers</label><p>${row.expected_papers ?? 'N/A'}</p></div>
                <div class="detail-item"><label>Preferred Publication Date</label><p>${fmtDate(row.preferred_pub_date)}</p></div>
                <div class="detail-item"><label>Status</label><p>${statusLabel}</p></div>
                <div class="detail-item"><label>Submitted At</label><p>${row.created_at || 'N/A'}</p></div>
            </div>

            ${row.special_requests ? `
            <div class="section-heading">Special Requests / Notes</div>
            <div style="background:#f8faff;padding:16px;border-radius:8px;font-size:.88rem;color:#374151;line-height:1.7;border:1px solid #e8f0fe">
                ${row.special_requests.replace(/\n/g,'<br>')}
            </div>` : ''}
        `;

        document.getElementById('cpModal').classList.add('open');
    }

    function closeModal() {
        document.getElementById('cpModal').classList.remove('open');
    }

    document.getElementById('cpModal').addEventListener('click', e => {
        if (e.target === document.getElementById('cpModal')) closeModal();
    });
    document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });
    </script>
</body>
</html>
<?php ob_end_flush(); ?>