<?php
/**
 * Pure Chemical Admin
 * File: admin/enquiries.php
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

if (file_exists(__DIR__ . '/includes/auth.php')) {
    require_once __DIR__ . '/includes/auth.php';
}

if (file_exists(__DIR__ . '/includes/functions.php')) {
    require_once __DIR__ . '/includes/functions.php';
}

if (file_exists(__DIR__ . '/includes/csrf.php')) {
    require_once __DIR__ . '/includes/csrf.php';
}

if (function_exists('requireAdmin')) {
    requireAdmin();
}


/* =========================================================
   HELPERS
========================================================= */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
    }
}


/**
 * CSRF token fallback.
 */
function enquiriesCsrfToken()
{
    if (function_exists('csrf_token')) {
        return csrf_token();
    }

    if (empty($_SESSION['enquiries_csrf_token'])) {
        $_SESSION['enquiries_csrf_token'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['enquiries_csrf_token'];
}


/**
 * CSRF verification fallback.
 */
function enquiriesVerifyCsrf($token)
{
    if (function_exists('csrf_verify')) {
        return csrf_verify($token);
    }

    return isset($_SESSION['enquiries_csrf_token'])
        && hash_equals(
            $_SESSION['enquiries_csrf_token'],
            (string) $token
        );
}


/**
 * Flash message.
 */
function enquiriesFlash($type, $message)
{
    $_SESSION['enquiries_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}


/**
 * Get flash.
 */
function enquiriesGetFlash()
{
    if (empty($_SESSION['enquiries_flash'])) {
        return null;
    }

    $flash = $_SESSION['enquiries_flash'];
    unset($_SESSION['enquiries_flash']);
    return $flash;
}


/**
 * Read ENUM values dynamically from database.
 */
function enquiriesEnumOptions(
    PDO $pdo,
    $table,
    $column,
    array $fallback = []
) {
    try {
        $stmt = $pdo->prepare("
            SELECT COLUMN_TYPE
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
            AND table_name = ?
            AND column_name = ?
            LIMIT 1
        ");
        $stmt->execute([$table, $column]);
        $type = $stmt->fetchColumn();

        if (!$type) {
            return $fallback;
        }

        if (preg_match("/^enum\\((.*)\\)$/i", $type, $matches)) {
            $inside = $matches[1];
            $values = str_getcsv($inside, ',', "'", "\\");
            $options = [];

            foreach ($values as $value) {
                $value = str_replace("''", "'", $value);
                if ($value !== '') {
                    $options[] = $value;
                }
            }

            if (!empty($options)) {
                return $options;
            }
        }
    } catch (Throwable $e) {
        // Fallback
    }

    return $fallback;
}


/* =========================================================
   ADMIN DATA
========================================================= */

$adminName =
    $_SESSION['ADMIN_NAME']
    ?? $_SESSION['admin_name']
    ?? $_SESSION['name']
    ?? 'Administrator';

$adminEmail =
    $_SESSION['ADMIN_EMAIL']
    ?? $_SESSION['admin_email']
    ?? '';

$csrfToken = enquiriesCsrfToken();


/* =========================================================
   STATUS OPTIONS
========================================================= */

$statusFallback = [
    'new',
    'read',
    'processing',
    'replied',
    'closed',
    'spam'
];

$enquiryStatuses = enquiriesEnumOptions(
    $pdo,
    'enquiries',
    'status',
    $statusFallback
);


/* =========================================================
   ACTION HANDLER (STATUS UPDATE / DELETE)
========================================================= */

$action = $_POST['action'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $postedToken = $_POST['csrf_token'] ?? '';

    if (!enquiriesVerifyCsrf($postedToken)) {
        enquiriesFlash('error', 'Security verification failed. Please try again.');
        header('Location: enquiries.php');
        exit;
    }

    /* Update Status */
    if ($action === 'update_status') {
        $id = (int) ($_POST['id'] ?? 0);
        $newStatus = trim($_POST['status'] ?? '');

        if ($id <= 0 || !in_array($newStatus, $enquiryStatuses, true)) {
            enquiriesFlash('error', 'Invalid enquiry or status selected.');
            header('Location: enquiries.php');
            exit;
        }

        try {
            $stmt = $pdo->prepare("
                UPDATE enquiries
                SET status = ?
                WHERE id = ?
            ");
            $stmt->execute([$newStatus, $id]);

            enquiriesFlash('success', 'Enquiry status updated successfully.');
        } catch (Throwable $e) {
            enquiriesFlash('error', 'Unable to update enquiry status.');
        }

        header('Location: enquiries.php');
        exit;
    }

    /* Delete Enquiry */
    if ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);

        if ($id <= 0) {
            enquiriesFlash('error', 'Invalid enquiry selected.');
            header('Location: enquiries.php');
            exit;
        }

        try {
            $stmt = $pdo->prepare("DELETE FROM enquiries WHERE id = ?");
            $stmt->execute([$id]);

            enquiriesFlash('success', 'Enquiry deleted successfully.');
        } catch (Throwable $e) {
            enquiriesFlash('error', 'Unable to delete enquiry.');
        }

        header('Location: enquiries.php');
        exit;
    }
}


/* =========================================================
   FILTERS & PAGINATION
========================================================= */

$search = trim($_GET['search'] ?? '');
$statusFilter = $_GET['status'] ?? 'all';
$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 15;


/* =========================================================
   BUILD WHERE CLAUSE
========================================================= */

$where = [];
$params = [];

if ($search !== '') {
    $where[] = "
        (
            enquiry_number LIKE ?
            OR name LIKE ?
            OR email LIKE ?
            OR mobile LIKE ?
            OR company LIKE ?
            OR subject LIKE ?
        )
    ";
    $searchLike = '%' . $search . '%';
    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
}

if ($statusFilter !== 'all' && in_array($statusFilter, $enquiryStatuses, true)) {
    $where[] = "status = ?";
    $params[] = $statusFilter;
}

$whereSql = '';
if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}


/* =========================================================
   TOTAL ROWS & PAGINATION MATH
========================================================= */

$totalRows = 0;

try {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM enquiries {$whereSql}");
    $stmt->execute($params);
    $totalRows = (int) $stmt->fetchColumn();
} catch (Throwable $e) {
    $totalRows = 0;
}

$totalPages = max(1, (int) ceil($totalRows / $perPage));
if ($page > $totalPages) {
    $page = $totalPages;
}
$offset = ($page - 1) * $perPage;


/* =========================================================
   FETCH ENQUIRIES
========================================================= */

$enquiryRows = [];

try {
    $stmt = $pdo->prepare("
        SELECT
            id,
            enquiry_number,
            name,
            email,
            country_code,
            mobile,
            location,
            company,
            product_id,
            industry_id,
            quantity,
            industry_name,
            subject,
            message,
            source_url,
            ip_address,
            status,
            created_at
        FROM enquiries
        {$whereSql}
        ORDER BY id DESC
        LIMIT {$perPage}
        OFFSET {$offset}
    ");
    $stmt->execute($params);
    $enquiryRows = $stmt->fetchAll();
} catch (Throwable $e) {
    $enquiryRows = [];
}


/* =========================================================
   STATS COUNT
========================================================= */

$stats = [
    'total' => 0,
    'new' => 0,
    'processing' => 0,
    'replied' => 0,
    'closed' => 0
];

try {
    $statStmt = $pdo->query("
        SELECT
            COUNT(*) AS total,
            SUM(status = 'new') AS new_count,
            SUM(status = 'processing') AS processing_count,
            SUM(status = 'replied') AS replied_count,
            SUM(status = 'closed') AS closed_count
        FROM enquiries
    ");
    $statRow = $statStmt->fetch();
    if ($statRow) {
        $stats['total'] = (int) ($statRow['total'] ?? 0);
        $stats['new'] = (int) ($statRow['new_count'] ?? 0);
        $stats['processing'] = (int) ($statRow['processing_count'] ?? 0);
        $stats['replied'] = (int) ($statRow['replied_count'] ?? 0);
        $stats['closed'] = (int) ($statRow['closed_count'] ?? 0);
    }
} catch (Throwable $e) {
    // Keep defaults
}

$flash = enquiriesGetFlash();


/* =========================================================
   PAGINATION URL HELPER
========================================================= */

function enquiriesPageUrl($page)
{
    $query = $_GET;
    $query['page'] = $page;
    return 'enquiries.php?' . http_build_query($query);
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Enquiries | Pure Chemical Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    
    <style>
        :root {
            --primary: #176b52;
            --primary-dark: #0e4e3c;
            --primary-soft: #eaf7f1;
            --dark: #10231d;
            --muted: #71807a;
            --border: #e5ebe8;
            --bg: #f5f8f7;
            --white: #ffffff;
            --success: #14804a;
            --success-bg: #eaf8f0;
            --danger: #c53b3b;
            --danger-bg: #fff0f0;
            --warning: #b97800;
            --warning-bg: #fff8e8;
            --blue: #3867b3;
            --blue-bg: #eef4ff;
            --shadow: 0 15px 45px rgba(16, 35, 29, .07);
            --radius: 18px;
        }

        * { box-sizing: border-box; }
        html { scroll-behavior: smooth; }
        body { margin: 0; font-family: "Inter", sans-serif; background: var(--bg); color: var(--dark); }
        a { color: inherit; text-decoration: none; }
        button, input, textarea, select { font: inherit; }

        .main { margin-left: 280px; min-height: 100vh; }

        .topbar {
            height: 78px;
            background: rgba(255,255,255,.95);
            backdrop-filter: blur(18px);
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 32px;
            position: sticky;
            top: 0;
            z-index: 50;
        }

        .topbar-left { display: flex; align-items: center; gap: 14px; }
        .page-icon {
            width: 45px; height: 45px; border-radius: 13px;
            background: var(--primary-soft); color: var(--primary);
            display: flex; align-items: center; justify-content: center; font-size: 18px;
        }
        .page-title h1 { margin: 0; font-size: 19px; font-weight: 800; letter-spacing: -.3px; }
        .page-title p { margin: 4px 0 0; color: var(--muted); font-size: 11px; }

        .admin-profile { display: flex; align-items: center; gap: 10px; }
        .admin-avatar {
            width: 42px; height: 42px; border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), #29966f);
            color: white; display: flex; align-items: center; justify-content: center;
            font-size: 14px; font-weight: 800;
        }
        .admin-info strong { display: block; font-size: 13px; }
        .admin-info span { display: block; margin-top: 3px; color: var(--muted); font-size: 10px; }

        .content { padding: 30px 32px 55px; }

        .alert {
            padding: 14px 17px; border-radius: 14px; margin-bottom: 22px;
            display: flex; align-items: center; gap: 10px; font-size: 13px; font-weight: 600;
        }
        .alert.success { background: var(--success-bg); color: var(--success); border: 1px solid #ccebd9; }
        .alert.error { background: var(--danger-bg); color: var(--danger); border: 1px solid #f1cccc; }

        .hero { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; margin-bottom: 24px; }
        .hero h2 { margin: 0; font-size: 27px; font-weight: 800; letter-spacing: -.8px; }
        .hero p { margin: 7px 0 0; color: var(--muted); font-size: 13px; }

        .btn {
            min-height: 43px; border: 0; border-radius: 12px; padding: 0 17px;
            display: inline-flex; align-items: center; justify-content: center; gap: 8px;
            cursor: pointer; font-size: 12px; font-weight: 700; transition: .2s ease;
        }
        .btn-primary { background: var(--primary); color: white; box-shadow: 0 8px 20px rgba(23,107,82,.2); }
        .btn-primary:hover { background: var(--primary-dark); transform: translateY(-1px); }
        .btn-light { background: white; color: var(--dark); border: 1px solid var(--border); }
        .btn-light:hover { border-color: #bfd0c8; }
        .btn-danger { background: var(--danger); color: white; }
        .btn-danger:hover { background: #aa2e2e; }

        .stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-bottom: 24px; }
        .stat-card {
            position: relative; overflow: hidden; padding: 19px; background: white;
            border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow);
        }
        .stat-card::after {
            content: ""; position: absolute; right: -28px; bottom: -28px;
            width: 72px; height: 72px; border-radius: 50%; background: var(--primary-soft);
        }
        .stat-icon {
            width: 42px; height: 42px; border-radius: 12px; display: flex;
            align-items: center; justify-content: center; background: var(--primary-soft); color: var(--primary);
        }
        .stat-number { margin-top: 14px; font-size: 26px; font-weight: 800; line-height: 1; }
        .stat-label { margin-top: 7px; color: var(--muted); font-size: 11px; font-weight: 600; }

        .panel { background: white; border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; }
        .toolbar { padding: 17px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 9px; }
        .filter-form { width: 100%; display: flex; align-items: center; gap: 9px; }
        .search-box { position: relative; flex: 1; max-width: 400px; }
        .search-box i { position: absolute; left: 14px; top: 50%; transform: translateY(-50%); color: #91a099; font-size: 12px; }
        .input {
            width: 100%; height: 43px; border: 1px solid var(--border); border-radius: 11px;
            background: #fbfcfc; outline: none; padding: 0 13px; color: var(--dark); font-size: 12px; transition: .2s ease;
        }
        .search-box .input { padding-left: 38px; }
        .input:focus { border-color: #91cbb7; background: white; box-shadow: 0 0 0 4px rgba(23,107,82,.08); }
        select.input { cursor: pointer; }

        .table-wrap { width: 100%; overflow-x: auto; }
        table { width: 100%; min-width: 1100px; border-collapse: collapse; }
        th {
            padding: 13px 17px; text-align: left; background: #fbfcfc; border-bottom: 1px solid var(--border);
            color: #7a8983; font-size: 9px; text-transform: uppercase; letter-spacing: .8px; font-weight: 800;
        }
        td { padding: 16px 17px; border-bottom: 1px solid #edf1ef; vertical-align: middle; font-size: 12px; }
        tbody tr:hover { background: #fbfdfc; }
        tbody tr:last-child td { border-bottom: 0; }

        .customer-info strong { display: block; font-size: 12px; }
        .customer-info span { display: block; margin-top: 3px; color: var(--muted); font-size: 10px; }
        .enquiry-no { display: inline-block; padding: 4px 8px; border-radius: 6px; background: #f2f5f4; color: #5d6c66; font-family: monospace; font-size: 10px; font-weight: 700; }

        .badge { display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px; border-radius: 100px; font-size: 9px; font-weight: 800; text-transform: uppercase; }
        .badge::before { content: ""; width: 5px; height: 5px; border-radius: 50%; }
        .badge.new { background: var(--blue-bg); color: var(--blue); }
        .badge.new::before { background: var(--blue); }
        .badge.processing { background: var(--warning-bg); color: var(--warning); }
        .badge.processing::before { background: var(--warning); }
        .badge.replied { background: var(--success-bg); color: var(--success); }
        .badge.replied::before { background: var(--success); }
        .badge.closed { background: #f1f3f3; color: #7d8884; }
        .badge.closed::before { background: #89938f; }
        .badge.read { background: #eaf3f8; color: #20628a; }
        .badge.read::before { background: #20628a; }

        .actions { display: flex; align-items: center; gap: 6px; }
        .icon-btn {
            width: 34px; height: 34px; border-radius: 9px; display: inline-flex;
            align-items: center; justify-content: center; border: 1px solid var(--border);
            background: white; color: #66746e; cursor: pointer; transition: .2s ease;
        }
        .icon-btn:hover { background: var(--primary-soft); border-color: #bdd0c8; color: var(--primary); }
        .icon-btn.delete:hover { background: var(--danger-bg); border-color: #f0cccc; color: var(--danger); }

        .pagination { padding: 16px 18px; border-top: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; gap: 15px; }
        .pagination-info { color: var(--muted); font-size: 11px; }
        .pagination-links { display: flex; align-items: center; gap: 5px; }
        .page-link {
            min-width: 34px; height: 34px; padding: 0 8px; display: inline-flex; align-items: center;
            justify-content: center; background: white; border: 1px solid var(--border); border-radius: 9px;
            color: #66736e; font-size: 10px; font-weight: 700;
        }
        .page-link:hover { color: var(--primary); border-color: #bfd0c8; }
        .page-link.active { background: var(--primary); color: white; border-color: var(--primary); }

        .empty { padding: 70px 20px; text-align: center; }
        .empty-icon {
            width: 65px; height: 65px; margin: 0 auto 16px; border-radius: 18px;
            background: var(--primary-soft); color: var(--primary); display: flex; align-items: center; justify-content: center; font-size: 23px;
        }

        /* Modal styling with custom sidebar offset */
        .modal {
            position: fixed; inset: 0; z-index: 99999; padding: 20px; padding-left: 300px;
            display: none; align-items: center; justify-content: center; background: rgba(10,27,21,.58); backdrop-filter: blur(6px);
        }
        .modal.show { display: flex; }
        .modal-card { width: min(760px, 100%); max-height: calc(100vh - 40px); overflow-y: auto; background: white; border-radius: 22px; box-shadow: 0 30px 90px rgba(0,0,0,.22); animation: modalIn .2s ease; }
        @keyframes modalIn { from { opacity: 0; transform: translateY(15px) scale(.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
        .modal-header { padding: 20px 23px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; }
        .modal-title { display: flex; align-items: center; gap: 11px; }
        .modal-title-icon { width: 42px; height: 42px; border-radius: 12px; background: var(--primary-soft); color: var(--primary); display: flex; align-items: center; justify-content: center; }
        .modal-title h3 { margin: 0; font-size: 17px; }
        .modal-title p { margin: 4px 0 0; color: var(--muted); font-size: 10px; }
        .modal-close { width: 35px; height: 35px; border: 0; border-radius: 10px; background: #f3f5f4; color: #66736e; cursor: pointer; }
        .modal-body { padding: 23px; }
        .modal-footer { padding: 17px 23px; border-top: 1px solid var(--border); display: flex; justify-content: flex-end; gap: 9px; }

        .detail-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px; }
        .detail-group.full { grid-column: 1 / -1; }
        .detail-group label { display: block; font-size: 10px; text-transform: uppercase; font-weight: 800; color: var(--muted); margin-bottom: 4px; letter-spacing: .5px; }
        .detail-group .val { font-size: 13px; font-weight: 600; color: var(--dark); background: #fbfcfc; padding: 10px 12px; border: 1px solid var(--border); border-radius: 10px; word-break: break-word; }

        .delete-card { width: min(440px, 100%); padding: 28px; border-radius: 22px; background: white; text-align: center; }
        .delete-icon { width: 58px; height: 58px; margin: 0 auto 15px; border-radius: 17px; background: var(--danger-bg); color: var(--danger); display: flex; align-items: center; justify-content: center; font-size: 21px; }

        @media (max-width: 1200px) { .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
        @media (max-width: 1050px) { .main { margin-left: 0; } .topbar { padding: 0 20px; } .content { padding: 25px 20px 45px; } .modal { padding-left: 20px; } }
    </style>
</head>

<body>

<?php
if (file_exists(__DIR__ . '/sidebar.php')) {
    require_once __DIR__ . '/sidebar.php';
}
?>

<div class="main">

    <!-- TOPBAR -->
    <header class="topbar">
        <div class="topbar-left">
            <div class="page-icon">
                <i class="fa-solid fa-envelope-open-text"></i>
            </div>
            <div class="page-title">
                <h1>Customer Enquiries</h1>
                <p>Manage and track all website product or service enquiries</p>
            </div>
        </div>

        <div class="admin-profile">
            <div class="admin-avatar">
                <?= e(strtoupper(substr(trim($adminName), 0, 1))) ?>
            </div>
            <div class="admin-info">
                <strong><?= e($adminName) ?></strong>
                <span><?= e($adminEmail ?: 'Administrator') ?></span>
            </div>
        </div>
    </header>

    <!-- CONTENT -->
    <main class="content">

        <?php if ($flash): ?>
            <div class="alert <?= e($flash['type']) ?>">
                <?php if ($flash['type'] === 'success'): ?>
                    <i class="fa-solid fa-circle-check"></i>
                <?php else: ?>
                    <i class="fa-solid fa-circle-exclamation"></i>
                <?php endif; ?>
                <span><?= e($flash['message']) ?></span>
            </div>
        <?php endif; ?>

        <!-- HERO SECTION -->
        <section class="hero">
            <div>
                <h2>Enquiry Inbox</h2>
                <p>View submissions from clients, update response status, and check details.</p>
            </div>
        </section>

        <!-- STATS -->
        <section class="stats">
            <div class="stat-card">
                <div class="stat-icon"><i class="fa-solid fa-inbox"></i></div>
                <div class="stat-number"><?= number_format($stats['total']) ?></div>
                <div class="stat-label">Total Enquiries</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon"><i class="fa-solid fa-circle-exclamation"></i></div>
                <div class="stat-number"><?= number_format($stats['new']) ?></div>
                <div class="stat-label">New Enquiries</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon"><i class="fa-solid fa-spinner"></i></div>
                <div class="stat-number"><?= number_format($stats['processing']) ?></div>
                <div class="stat-label">Processing</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon"><i class="fa-solid fa-circle-check"></i></div>
                <div class="stat-number"><?= number_format($stats['replied']) ?></div>
                <div class="stat-label">Replied</div>
            </div>
        </section>

        <!-- PANEL -->
        <section class="panel">
            <div class="toolbar">
                <form method="get" action="enquiries.php" class="filter-form">
                    <div class="search-box">
                        <i class="fa-solid fa-magnifying-glass"></i>
                        <input
                            type="text"
                            name="search"
                            class="input"
                            placeholder="Search name, email, mobile, company..."
                            value="<?= e($search) ?>"
                        >
                    </div>

                    <select name="status" class="input" style="max-width:180px;" onchange="this.form.submit()">
                        <option value="all">All Statuses</option>
                        <?php foreach ($enquiryStatuses as $st): ?>
                            <option value="<?= e($st) ?>" <?= ($statusFilter === $st) ? 'selected' : '' ?>>
                                <?= e(ucwords($st)) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <button type="submit" class="btn btn-primary">
                        <i class="fa-solid fa-filter"></i> Filter
                    </button>

                    <?php if ($search !== '' || $statusFilter !== 'all'): ?>
                        <a href="enquiries.php" class="btn btn-light">
                            <i class="fa-solid fa-rotate-left"></i> Reset
                        </a>
                    <?php endif; ?>
                </form>
            </div>

            <!-- TABLE -->
            <?php if (!empty($enquiryRows)): ?>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Enquiry / Ref</th>
                                <th>Client Details</th>
                                <th>Company / Location</th>
                                <th>Subject / Industry</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($enquiryRows as $row): ?>
                                <tr>
                                    <td>
                                        <span class="enquiry-no">
                                            <?= e($row['enquiry_number'] ?: 'EQ-' . $row['id']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="customer-info">
                                            <strong><?= e($row['name']) ?></strong>
                                            <span>
                                                <i class="fa-solid fa-envelope"></i> <?= e($row['email'] ?: 'N/A') ?>
                                                <?php if (!empty($row['mobile'])): ?>
                                                    <br><i class="fa-solid fa-phone"></i> <?= e($row['country_code'] . ' ' . $row['mobile']) ?>
                                                <?php endif; ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="font-weight:600; font-size:11px;">
                                            <?= e($row['company'] ?: '—') ?>
                                        </div>
                                        <div style="color:var(--muted); font-size:10px; margin-top:2px;">
                                            <?= e($row['location'] ?: '—') ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="font-weight:600; font-size:11px; max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                                            <?= e($row['subject'] ?: 'General Enquiry') ?>
                                        </div>
                                        <div style="color:var(--muted); font-size:10px; margin-top:2px;">
                                            <?= e($row['industry_name'] ?: '—') ?>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge <?= e($row['status']) ?>">
                                            <?= e(ucwords($row['status'])) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span style="color:#78847f; font-size:10px; white-space:nowrap;">
                                            <?= !empty($row['created_at']) ? e(date('d M Y, H:i', strtotime($row['created_at']))) : '—' ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="actions">
                                            <button
                                                type="button"
                                                class="icon-btn"
                                                title="View Details"
                                                onclick='openViewModal(<?= json_encode($row, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>)'
                                            >
                                                <i class="fa-solid fa-eye"></i>
                                            </button>

                                            <button
                                                type="button"
                                                class="icon-btn delete"
                                                title="Delete Enquiry"
                                                onclick="openDeleteModal(<?= (int) $row['id'] ?>, <?= htmlspecialchars(json_encode($row['enquiry_number'] ?: 'EQ-' . $row['id']), ENT_QUOTES, 'UTF-8') ?>)"
                                            >
                                                <i class="fa-regular fa-trash-can"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- PAGINATION -->
                <?php if ($totalPages > 1): ?>
                    <div class="pagination">
                        <div class="pagination-info">
                            Showing <strong><?= $totalRows > 0 ? $offset + 1 : 0 ?></strong> - <strong><?= min($offset + $perPage, $totalRows) ?></strong> of <strong><?= number_format($totalRows) ?></strong> enquiries
                        </div>
                        <div class="pagination-links">
                            <?php if ($page > 1): ?>
                                <a href="<?= e(enquiriesPageUrl($page - 1)) ?>" class="page-link"><i class="fa-solid fa-chevron-left"></i></a>
                            <?php endif; ?>

                            <?php
                            $startPage = max(1, $page - 2);
                            $endPage = min($totalPages, $page + 2);
                            for ($p = $startPage; $p <= $endPage; $p++):
                            ?>
                                <a href="<?= e(enquiriesPageUrl($p)) ?>" class="page-link <?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
                            <?php endfor; ?>

                            <?php if ($page < $totalPages): ?>
                                <a href="<?= e(enquiriesPageUrl($page + 1)) ?>" class="page-link"><i class="fa-solid fa-chevron-right"></i></a>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>

            <?php else: ?>
                <div class="empty">
                    <div class="empty-icon"><i class="fa-solid fa-envelope-open-text"></i></div>
                    <h3>No enquiries found</h3>
                    <p>There are no client enquiries matching your current filters.</p>
                    <?php if ($search !== '' || $statusFilter !== 'all'): ?>
                        <a href="enquiries.php" class="btn btn-light"><i class="fa-solid fa-rotate-left"></i> Clear Filters</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </section>
    </main>
</div>

<!-- =========================================================
     VIEW / EDIT STATUS MODAL
========================================================= -->
<div class="modal" id="viewModal" onclick="closeViewBackdrop(event)">
    <div class="modal-card">
        <div class="modal-header">
            <div class="modal-title">
                <div class="modal-title-icon"><i class="fa-solid fa-circle-info"></i></div>
                <div>
                    <h3>Enquiry Details</h3>
                    <p id="modalRefTitle">Viewing client request information</p>
                </div>
            </div>
            <button type="button" class="modal-close" onclick="closeViewModal()"><i class="fa-solid fa-xmark"></i></button>
        </div>

        <form method="post" action="enquiries.php">
            <input type="hidden" name="csrf_token" value="<?= e($csrfToken) ?>">
            <input type="hidden" name="action" value="update_status">
            <input type="hidden" name="id" id="viewId" value="">

            <div class="modal-body">
                <div class="detail-grid">
                    <div class="detail-group">
                        <label>Enquiry Reference</label>
                        <div class="val" id="detEnquiryNumber">-</div>
                    </div>
                    <div class="detail-group">
                        <label>Date & Time</label>
                        <div class="val" id="detCreatedAt">-</div>
                    </div>
                    <div class="detail-group">
                        <label>Client Name</label>
                        <div class="val" id="detName">-</div>
                    </div>
                    <div class="detail-group">
                        <label>Email Address</label>
                        <div class="val" id="detEmail">-</div>
                    </div>
                    <div class="detail-group">
                        <label>Mobile Number</label>
                        <div class="val" id="detMobile">-</div>
                    </div>
                    <div class="detail-group">
                        <label>Company</label>
                        <div class="val" id="detCompany">-</div>
                    </div>
                    <div class="detail-group">
                        <label>Location / City</label>
                        <div class="val" id="detLocation">-</div>
                    </div>
                    <div class="detail-group">
                        <label>Quantity / Requirement</label>
                        <div class="val" id="detQuantity">-</div>
                    </div>
                    <div class="detail-group">
                        <label>Industry Name</label>
                        <div class="val" id="detIndustryName">-</div>
                    </div>
                    <div class="detail-group">
                        <label>Subject</label>
                        <div class="val" id="detSubject">-</div>
                    </div>
                    <div class="detail-group full">
                        <label>Message Content</label>
                        <div class="val" id="detMessage" style="white-space: pre-wrap; min-height: 80px;">-</div>
                    </div>
                    <div class="detail-group full">
                        <label for="updateStatusSelect">Update Status</label>
                        <select name="status" id="updateStatusSelect" class="input">
                            <?php foreach ($enquiryStatuses as $st): ?>
                                <option value="<?= e($st) ?>"><?= e(ucwords($st)) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-light" onclick="closeViewModal()">Close</button>
                <button type="submit" class="btn btn-primary"><i class="fa-solid fa-check"></i> Save Changes</button>
            </div>
        </form>
    </div>
</div>

<!-- =========================================================
     DELETE MODAL
========================================================= -->
<div class="modal" id="deleteModal" onclick="closeDeleteBackdrop(event)">
    <div class="delete-card">
        <div class="delete-icon"><i class="fa-regular fa-trash-can"></i></div>
        <h3>Delete Enquiry?</h3>
        <p>Are you sure you want to delete enquiry <strong id="deleteRefText"></strong>? This action cannot be undone.</p>
        
        <form method="post" action="enquiries.php">
            <input type="hidden" name="csrf_token" value="<?= e($csrfToken) ?>">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" id="deleteId" value="">

            <div style="margin-top:22px; display:flex; justify-content:center; gap:9px;">
                <button type="button" class="btn btn-light" onclick="closeDeleteModal()">Cancel</button>
                <button type="submit" class="btn btn-danger"><i class="fa-regular fa-trash-can"></i> Delete</button>
            </div>
        </form>
    </div>
</div>

<script>
    function openViewModal(data) {
        document.getElementById('viewId').value = data.id || '';
        document.getElementById('detEnquiryNumber').textContent = data.enquiry_number || ('EQ-' + data.id);
        document.getElementById('modalRefTitle').textContent = 'Viewing details for ' + (data.enquiry_number || ('EQ-' + data.id));
        document.getElementById('detCreatedAt').textContent = data.created_at || '-';
        document.getElementById('detName').textContent = data.name || '-';
        document.getElementById('detEmail').textContent = data.email || 'N/A';
        document.getElementById('detMobile').textContent = (data.country_code ? data.country_code + ' ' : '') + (data.mobile || 'N/A');
        document.getElementById('detCompany').textContent = data.company || 'N/A';
        document.getElementById('detLocation').textContent = data.location || 'N/A';
        document.getElementById('detQuantity').textContent = data.quantity || 'N/A';
        document.getElementById('detIndustryName').textContent = data.industry_name || 'N/A';
        document.getElementById('detSubject').textContent = data.subject || 'General Enquiry';
        document.getElementById('detMessage').textContent = data.message || 'No message provided.';

        const statusSelect = document.getElementById('updateStatusSelect');
        if (statusSelect && data.status) {
            statusSelect.value = data.status;
        }

        document.getElementById('viewModal').classList.add('show');
        document.body.style.overflow = 'hidden';
    }

    function closeViewModal() {
        document.getElementById('viewModal').classList.remove('show');
        document.body.style.overflow = '';
    }

    function closeViewBackdrop(event) {
        if (event.target === document.getElementById('viewModal')) {
            closeViewModal();
        }
    }

    function openDeleteModal(id, refNo) {
        document.getElementById('deleteId').value = id;
        document.getElementById('deleteRefText').textContent = refNo;
        document.getElementById('deleteModal').classList.add('show');
        document.body.style.overflow = 'hidden';
    }

    function closeDeleteModal() {
        document.getElementById('deleteModal').classList.remove('show');
        document.body.style.overflow = '';
    }

    function closeDeleteBackdrop(event) {
        if (event.target === document.getElementById('deleteModal')) {
            closeDeleteModal();
        }
    }

    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeViewModal();
            closeDeleteModal();
        }
    });
</script>

</body>
</html>