<?php
// ============================================================
// CONTACT QUERIES - ADMIN PANEL
// THE MURUGAN'S CO.
// ============================================================

require('includes/db.php');

// ============================================================
// ADMIN LOGIN CHECK
// ============================================================

if (!isset($_SESSION['ADMIN_ID']) || empty($_SESSION['ADMIN_ID'])) {
    header('Location: login.php');
    exit();
}

// ============================================================
// HELPER
// ============================================================

function e($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

// ============================================================
// SEARCH + FILTER
// ============================================================

$search = isset($_GET['search'])
    ? trim($_GET['search'])
    : '';

$status_filter = isset($_GET['status'])
    ? trim($_GET['status'])
    : '';

$allowed_statuses = [
    'new',
    'read',
    'replied',
    'closed'
];

if (
    $status_filter !== '' &&
    !in_array($status_filter, $allowed_statuses, true)
) {
    $status_filter = '';
}

// ============================================================
// DELETE QUERY
// ============================================================

if (
    isset($_GET['delete']) &&
    $_GET['delete'] !== ''
) {

    $delete_id = (int)$_GET['delete'];

    if ($delete_id > 0) {

        $stmt = mysqli_prepare(
            $con,
            "DELETE FROM contact_queries WHERE id = ?"
        );

        if ($stmt) {

            mysqli_stmt_bind_param(
                $stmt,
                "i",
                $delete_id
            );

            mysqli_stmt_execute($stmt);

            mysqli_stmt_close($stmt);
        }
    }

    header('Location: contact.php');
    exit();
}

// ============================================================
// STATUS UPDATE
// ============================================================

if (
    isset($_GET['change_status']) &&
    isset($_GET['id'])
) {

    $status = trim($_GET['change_status']);
    $id = (int)$_GET['id'];

    if (
        $id > 0 &&
        in_array($status, $allowed_statuses, true)
    ) {

        $stmt = mysqli_prepare(
            $con,
            "UPDATE contact_queries
             SET status = ?
             WHERE id = ?"
        );

        if ($stmt) {

            mysqli_stmt_bind_param(
                $stmt,
                "si",
                $status,
                $id
            );

            mysqli_stmt_execute($stmt);

            mysqli_stmt_close($stmt);
        }
    }

    header(
        'Location: contact.php?' .
        http_build_query([
            'search' => $search,
            'status' => $status_filter
        ])
    );

    exit();
}

// ============================================================
// CSV EXPORT
// ============================================================

if (
    isset($_GET['export']) &&
    $_GET['export'] === 'csv'
) {

    $conditions = [];
    $params = [];
    $types = '';

    if ($search !== '') {

        $conditions[] =
            "(name LIKE ? OR email LIKE ? OR phone LIKE ? OR message LIKE ?)";

        $like = '%' . $search . '%';

        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
        $params[] = $like;

        $types .= 'ssss';
    }

    if ($status_filter !== '') {

        $conditions[] = "status = ?";

        $params[] = $status_filter;

        $types .= 's';
    }

    $sql = "
        SELECT
            id,
            name,
            email,
            phone,
            message,
            status,
            submitted_at
        FROM contact_queries
    ";

    if (!empty($conditions)) {
        $sql .= " WHERE " . implode(" AND ", $conditions);
    }

    $sql .= " ORDER BY id DESC";

    $stmt = mysqli_prepare($con, $sql);

    if ($stmt) {

        if (!empty($params)) {

            mysqli_stmt_bind_param(
                $stmt,
                $types,
                ...$params
            );
        }

        mysqli_stmt_execute($stmt);

        $result = mysqli_stmt_get_result($stmt);

        header(
            'Content-Type: text/csv; charset=utf-8'
        );

        header(
            'Content-Disposition: attachment; filename=contact_queries_' .
            date('Y-m-d_H-i-s') .
            '.csv'
        );

        $output = fopen(
            'php://output',
            'w'
        );

        fputcsv(
            $output,
            [
                'ID',
                'Name',
                'Email',
                'Phone',
                'Message',
                'Status',
                'Submitted At'
            ]
        );

        while ($row = mysqli_fetch_assoc($result)) {

            fputcsv(
                $output,
                [
                    $row['id'],
                    $row['name'],
                    $row['email'],
                    $row['phone'],
                    $row['message'],
                    $row['status'],
                    $row['submitted_at']
                ]
            );
        }

        fclose($output);

        mysqli_stmt_close($stmt);

        exit();
    }
}

// ============================================================
// STATISTICS
// ============================================================

$total_queries = 0;
$new_queries = 0;
$read_queries = 0;
$replied_queries = 0;
$closed_queries = 0;


// Total

$result = mysqli_query(
    $con,
    "SELECT COUNT(*) AS total
     FROM contact_queries"
);

if ($result) {

    $row = mysqli_fetch_assoc($result);

    $total_queries = (int)$row['total'];
}


// New

$result = mysqli_query(
    $con,
    "SELECT COUNT(*) AS total
     FROM contact_queries
     WHERE status = 'new'"
);

if ($result) {

    $row = mysqli_fetch_assoc($result);

    $new_queries = (int)$row['total'];
}


// Read

$result = mysqli_query(
    $con,
    "SELECT COUNT(*) AS total
     FROM contact_queries
     WHERE status = 'read'"
);

if ($result) {

    $row = mysqli_fetch_assoc($result);

    $read_queries = (int)$row['total'];
}


// Replied

$result = mysqli_query(
    $con,
    "SELECT COUNT(*) AS total
     FROM contact_queries
     WHERE status = 'replied'"
);

if ($result) {

    $row = mysqli_fetch_assoc($result);

    $replied_queries = (int)$row['total'];
}


// Closed

$result = mysqli_query(
    $con,
    "SELECT COUNT(*) AS total
     FROM contact_queries
     WHERE status = 'closed'"
);

if ($result) {

    $row = mysqli_fetch_assoc($result);

    $closed_queries = (int)$row['total'];
}

// ============================================================
// PAGINATION
// ============================================================

$limit = 10;

$page = isset($_GET['page'])
    ? (int)$_GET['page']
    : 1;

if ($page < 1) {
    $page = 1;
}

$offset = ($page - 1) * $limit;

// ============================================================
// BUILD WHERE CONDITION
// ============================================================

$conditions = [];
$params = [];
$types = '';

if ($search !== '') {

    $conditions[] =
        "(name LIKE ? OR email LIKE ? OR phone LIKE ? OR message LIKE ?)";

    $like = '%' . $search . '%';

    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;

    $types .= 'ssss';
}

if ($status_filter !== '') {

    $conditions[] = "status = ?";

    $params[] = $status_filter;

    $types .= 's';
}

$where_sql = '';

if (!empty($conditions)) {

    $where_sql =
        " WHERE " . implode(" AND ", $conditions);
}

// ============================================================
// FILTERED COUNT
// ============================================================

$filtered_queries = 0;

$count_sql = "
    SELECT COUNT(*) AS total
    FROM contact_queries
    $where_sql
";

$stmt = mysqli_prepare(
    $con,
    $count_sql
);

if ($stmt) {

    if (!empty($params)) {

        mysqli_stmt_bind_param(
            $stmt,
            $types,
            ...$params
        );
    }

    mysqli_stmt_execute($stmt);

    $result = mysqli_stmt_get_result($stmt);

    if ($result) {

        $row = mysqli_fetch_assoc($result);

        $filtered_queries = (int)$row['total'];
    }

    mysqli_stmt_close($stmt);
}

// ============================================================
// TOTAL PAGES
// ============================================================

$total_pages = max(
    1,
    (int)ceil(
        $filtered_queries / $limit
    )
);

if ($page > $total_pages) {

    $page = $total_pages;

    $offset =
        ($page - 1) * $limit;
}

// ============================================================
// FETCH CONTACT QUERIES
// ============================================================

$queries = [];

$list_sql = "
    SELECT
        id,
        name,
        email,
        phone,
        message,
        status,
        submitted_at
    FROM contact_queries
    $where_sql
    ORDER BY id DESC
    LIMIT ? OFFSET ?
";

$list_params = $params;
$list_types = $types . 'ii';

$list_params[] = $limit;
$list_params[] = $offset;

$stmt = mysqli_prepare(
    $con,
    $list_sql
);

if ($stmt) {

    mysqli_stmt_bind_param(
        $stmt,
        $list_types,
        ...$list_params
    );

    mysqli_stmt_execute($stmt);

    $result = mysqli_stmt_get_result($stmt);

    while ($row = mysqli_fetch_assoc($result)) {

        $queries[] = $row;
    }

    mysqli_stmt_close($stmt);
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Contact Queries | The Murugan's Co.
    </title>

    <meta
        name="theme-color"
        content="#1d5b3b"
    >

    <style>

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            padding: 0;
            background: #f4f8f5;
            color: #24382c;
            font-family:
                Arial,
                Helvetica,
                sans-serif;
        }

        /* =====================================================
           MAIN
        ===================================================== */

        .main {
            margin-left: 250px;
            min-height: 100vh;
            transition: .3s ease;
        }

        .content {
            max-width: 1600px;
            margin: auto;
            padding: 25px;
        }

        /* =====================================================
           HEADER
        ===================================================== */

        .page-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 20px;
            margin-bottom: 22px;
            flex-wrap: wrap;
        }

        .page-title h1 {
            margin: 0;
            font-size: 28px;
            font-weight: 800;
            color: #174c31;
        }

        .page-title p {
            margin: 7px 0 0;
            color: #728078;
            font-size: 14px;
        }

        /* =====================================================
           BUTTONS
        ===================================================== */

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 7px;
            padding: 11px 16px;
            border-radius: 10px;
            border: 0;
            text-decoration: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 700;
            transition: .2s ease;
        }

        .btn:hover {
            transform: translateY(-1px);
        }

        .btn-green {
            background: #1d5b3b;
            color: #fff;
        }

        .btn-green:hover {
            background: #15472e;
        }

        .btn-export {
            background: #e5f4ea;
            color: #1d5b3b;
            border: 1px solid #c8e4d1;
        }

        .btn-export:hover {
            background: #d9eddf;
        }

        /* =====================================================
           STATS
        ===================================================== */

        .stats-grid {
            display: grid;
            grid-template-columns:
                repeat(5, minmax(0, 1fr));
            gap: 14px;
            margin-bottom: 22px;
        }

        .stat-card {
            background: #fff;
            border: 1px solid #dfebe2;
            border-radius: 16px;
            padding: 18px;
            box-shadow:
                0 7px 25px rgba(20, 65, 42, .06);
        }

        .stat-top {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 8px;
        }

        .stat-title {
            color: #748279;
            font-size: 11px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: .5px;
        }

        .stat-icon {
            width: 38px;
            height: 38px;
            border-radius: 11px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #e8f5ec;
            color: #1d5b3b;
            font-size: 18px;
        }

        .stat-number {
            margin-top: 12px;
            font-size: 26px;
            font-weight: 800;
            color: #183d2a;
        }

        /* =====================================================
           FILTER
        ===================================================== */

        .filter-card {
            background: #fff;
            border: 1px solid #dfebe2;
            border-radius: 16px;
            padding: 17px;
            margin-bottom: 20px;
            box-shadow:
                0 7px 25px rgba(20, 65, 42, .06);
        }

        .filter-form {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .search-box {
            flex: 1;
            min-width: 250px;
        }

        .search-box input,
        .status-select {
            width: 100%;
            height: 46px;
            border: 1px solid #d5e2d9;
            border-radius: 10px;
            background: #fbfdfb;
            color: #283d31;
            outline: none;
            padding: 0 14px;
            font-size: 14px;
        }

        .status-select {
            width: 180px;
            cursor: pointer;
        }

        .search-box input:focus,
        .status-select:focus {
            border-color: #2f7047;
            box-shadow:
                0 0 0 3px rgba(47,112,71,.10);
        }

        .search-btn {
            height: 46px;
            background: #1d5b3b;
            color: #fff;
        }

        .clear-btn {
            height: 46px;
            background: #f1f4f2;
            color: #52645a;
        }

        /* =====================================================
           TABLE
        ===================================================== */

        .table-card {
            background: #fff;
            border: 1px solid #dfebe2;
            border-radius: 16px;
            overflow: hidden;
            box-shadow:
                0 7px 25px rgba(20, 65, 42, .07);
        }

        .table-head {
            padding: 17px 20px;
            border-bottom: 1px solid #e6eee8;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }

        .table-head h2 {
            margin: 0;
            font-size: 18px;
            color: #1d4931;
        }

        .result-count {
            color: #7b8880;
            font-size: 13px;
            font-weight: 600;
        }

        .table-wrapper {
            width: 100%;
            overflow-x: auto;
        }

        table {
            width: 100%;
            min-width: 1250px;
            border-collapse: collapse;
        }

        thead {
            background: #f1f7f3;
        }

        th {
            padding: 14px 13px;
            text-align: left;
            white-space: nowrap;
            color: #557061;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: .5px;
            border-bottom: 1px solid #dfe9e2;
        }

        td {
            padding: 14px 13px;
            border-bottom: 1px solid #edf2ee;
            vertical-align: top;
            color: #34483c;
            font-size: 13px;
        }

        tbody tr {
            transition: .15s ease;
        }

        tbody tr:hover {
            background: #f8fbf9;
        }

        tbody tr:last-child td {
            border-bottom: 0;
        }

        /* =====================================================
           QUERY ID
        ===================================================== */

        .query-id {
            font-weight: 800;
            color: #1d5b3b;
        }

        /* =====================================================
           CUSTOMER
        ===================================================== */

        .customer-name {
            font-weight: 800;
            color: #254e37;
            margin-bottom: 4px;
        }

        .customer-email {
            color: #697970;
            font-size: 12px;
            max-width: 220px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .phone {
            white-space: nowrap;
            color: #53645b;
        }

        /* =====================================================
           MESSAGE
        ===================================================== */

        .message-box {
            max-width: 340px;
            line-height: 1.55;
            color: #5f6f66;
        }

        .message-preview {
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .read-more {
            display: inline-block;
            margin-top: 5px;
            color: #1d5b3b;
            font-size: 11px;
            font-weight: 800;
        }

        /* =====================================================
           STATUS BADGES
        ===================================================== */

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 6px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 800;
            white-space: nowrap;
        }

        .status-new {
            background: #fff1e6;
            color: #c45b18;
        }

        .status-read {
            background: #eaf4ff;
            color: #27649b;
        }

        .status-replied {
            background: #e8f6ec;
            color: #267044;
        }

        .status-closed {
            background: #eef0ef;
            color: #66736c;
        }

        /* =====================================================
           STATUS SELECT
        ===================================================== */

        .status-action {
            display: flex;
            align-items: center;
            gap: 6px;
            flex-wrap: wrap;
        }

        .status-action select {
            height: 34px;
            border: 1px solid #d7e3da;
            border-radius: 8px;
            padding: 0 8px;
            background: #fff;
            color: #33483b;
            font-size: 11px;
            outline: none;
        }

        .status-action button {
            height: 34px;
            border: 0;
            border-radius: 8px;
            padding: 0 9px;
            background: #e7f3ea;
            color: #1d5b3b;
            cursor: pointer;
            font-size: 11px;
            font-weight: 800;
        }

        /* =====================================================
           DATE
        ===================================================== */

        .date-main {
            font-weight: 700;
            color: #42574b;
            white-space: nowrap;
        }

        .date-time {
            margin-top: 4px;
            color: #89958e;
            font-size: 11px;
            white-space: nowrap;
        }

        /* =====================================================
           ACTION
        ===================================================== */

        .actions {
            display: flex;
            align-items: center;
            gap: 7px;
        }

        .action-btn {
            width: 34px;
            height: 34px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 9px;
            text-decoration: none;
            font-size: 15px;
            transition: .2s ease;
        }

        .view-btn {
            background: #e8f4ec;
            color: #1d5b3b;
        }

        .view-btn:hover {
            background: #d7ebdd;
        }

        .delete-btn {
            background: #fff0f0;
            color: #c43d3d;
        }

        .delete-btn:hover {
            background: #ffe0e0;
        }

        /* =====================================================
           EMPTY
        ===================================================== */

        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }

        .empty-icon {
            font-size: 45px;
            margin-bottom: 10px;
        }

        .empty-state h3 {
            margin: 0 0 7px;
            color: #385345;
        }

        .empty-state p {
            margin: 0;
            color: #819087;
            font-size: 14px;
        }

        /* =====================================================
           PAGINATION
        ===================================================== */

        .pagination-area {
            padding: 17px 20px;
            border-top: 1px solid #e7eee9;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;
            flex-wrap: wrap;
        }

        .pagination-info {
            color: #77857c;
            font-size: 13px;
        }

        .pagination {
            display: flex;
            align-items: center;
            gap: 5px;
            flex-wrap: wrap;
        }

        .page-link {
            min-width: 35px;
            height: 35px;
            padding: 0 10px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #dce7df;
            border-radius: 8px;
            background: #fff;
            color: #315441;
            text-decoration: none;
            font-size: 13px;
            font-weight: 700;
        }

        .page-link:hover {
            background: #edf7f0;
        }

        .page-link.active {
            background: #1d5b3b;
            color: #fff;
            border-color: #1d5b3b;
        }

        .page-link.disabled {
            opacity: .45;
            pointer-events: none;
        }

        /* =====================================================
           RESPONSIVE
        ===================================================== */

        @media (max-width: 1250px) {

            .stats-grid {
                grid-template-columns:
                    repeat(3, minmax(0, 1fr));
            }

        }

        @media (max-width: 1000px) {

            .main {
                margin-left: 0;
            }

            .content {
                padding: 18px;
            }

        }

        @media (max-width: 650px) {

            .content {
                padding: 13px;
            }

            .page-title h1 {
                font-size: 23px;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .search-box {
                min-width: 100%;
            }

            .status-select {
                width: 100%;
            }

            .filter-form .btn {
                flex: 1;
            }

            .table-head {
                padding: 15px;
            }

            .pagination-area {
                padding: 14px;
            }

            .pagination-info {
                width: 100%;
            }

        }

        /* =====================================================
           PRINT
        ===================================================== */

        @media print {

            .main {
                margin-left: 0;
            }

            .sidebar,
            .sidebar-overlay,
            .topbar,
            .no-print,
            .filter-card,
            .pagination-area {
                display: none !important;
            }

            body {
                background: #fff;
            }

            .content {
                padding: 0;
                max-width: none;
            }

            .table-card {
                box-shadow: none;
                border: 1px solid #ccc;
            }

            table {
                min-width: 0;
            }

        }

    </style>

</head>

<body>

<?php
// ============================================================
// SIDEBAR
// ============================================================

require('sidebar.php');
?>

<div class="main">

<?php
// ============================================================
// TOPBAR
// ============================================================

require('top.php');
?>

    <main class="content">

        <!-- ==================================================
             PAGE HEADER
        =================================================== -->

        <div class="page-header">

            <div class="page-title">

                <h1>
                    Contact Queries
                </h1>

                <p>
                    Manage customer messages and contact enquiries.
                </p>

            </div>

            <div class="no-print">

                <a
                    href="?<?= http_build_query([
                        'search' => $search,
                        'status' => $status_filter,
                        'export' => 'csv'
                    ]); ?>"
                    class="btn btn-export"
                >
                    ? Export CSV
                </a>

            </div>

        </div>


        <!-- ==================================================
             STATISTICS
        =================================================== -->

        <div class="stats-grid">

            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-title">
                        Total
                    </div>

                    <div class="stat-icon">
                        ??
                    </div>

                </div>

                <div class="stat-number">
                    <?= number_format($total_queries); ?>
                </div>

            </div>



            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-title">
                        New
                    </div>

                    <div class="stat-icon">
                        ??
                    </div>

                </div>

                <div class="stat-number">
                    <?= number_format($new_queries); ?>
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-title">
                        Read
                    </div>

                    <div class="stat-icon">
                        ??
                    </div>

                </div>

                <div class="stat-number">
                    <?= number_format($read_queries); ?>
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-title">
                        Replied
                    </div>

                    <div class="stat-icon">
                        ?
                    </div>

                </div>

                <div class="stat-number">
                    <?= number_format($replied_queries); ?>
                </div>

            </div>


            <div class="stat-card">

                <div class="stat-top">

                    <div class="stat-title">
                        Closed
                    </div>

                    <div class="stat-icon">
                        ?
                    </div>

                </div>

                <div class="stat-number">
                    <?= number_format($closed_queries); ?>
                </div>

            </div>

        </div>


        <!-- ==================================================
             FILTER
        =================================================== -->

        <div class="filter-card no-print">

            <form
                action="contact.php"
                method="get"
                class="filter-form"
            >

                <div class="search-box">

                    <input
                        type="text"
                        name="search"
                        value="<?= e($search); ?>"
                        placeholder="Search name, email, phone or message..."
                        autocomplete="off"
                    >

                </div>


                <div>

                    <select
                        name="status"
                        class="status-select"
                    >

                        <option value="">
                            All Status
                        </option>

                        <option
                            value="new"
                            <?= $status_filter === 'new' ? 'selected' : ''; ?>
                        >
                            New
                        </option>

                        <option
                            value="read"
                            <?= $status_filter === 'read' ? 'selected' : ''; ?>
                        >
                            Read
                        </option>

                        <option
                            value="replied"
                            <?= $status_filter === 'replied' ? 'selected' : ''; ?>
                        >
                            Replied
                        </option>

                        <option
                            value="closed"
                            <?= $status_filter === 'closed' ? 'selected' : ''; ?>
                        >
                            Closed
                        </option>

                    </select>

                </div>


                <button
                    type="submit"
                    class="btn search-btn"
                >
                    ?? Search
                </button>


                <?php if (
                    $search !== '' ||
                    $status_filter !== ''
                ): ?>

                    <a
                        href="contact.php"
                        class="btn clear-btn"
                    >
                        ? Clear
                    </a>

                <?php endif; ?>

            </form>

        </div>


        <!-- ==================================================
             TABLE
        =================================================== -->

        <div class="table-card">

            <div class="table-head">

                <h2>
                    Customer Enquiries
                </h2>

                <div class="result-count">

                    Showing
                    <?= count($queries); ?>
                    of
                    <?= number_format($filtered_queries); ?>

                    queries

                </div>

            </div>


            <?php if (!empty($queries)): ?>

                <div class="table-wrapper">

                    <table>

                        <thead>

                            <tr>

                                <th>
                                    ID
                                </th>

                                <th>
                                    Customer
                                </th>

                                <th>
                                    Phone
                                </th>

                                <th>
                                    Message
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Submitted
                                </th>

                                <th class="no-print">
                                    Action
                                </th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($queries as $query): ?>

                            <?php

                            $query_id =
                                (int)$query['id'];

                            $query_status =
                                $query['status'] ?? 'new';

                            $message =
                                trim(
                                    $query['message'] ?? ''
                                );

                            $status_class =
                                'status-' .
                                $query_status;

                            ?>

                            <tr>

                                <!-- ID -->

                                <td>

                                    <div class="query-id">
                                        #<?= $query_id; ?>
                                    </div>

                                </td>


                                <!-- CUSTOMER -->

                                <td>

                                    <div class="customer-name">

                                        <?= e(
                                            $query['name']
                                        ); ?>

                                    </div>

                                    <div
                                        class="customer-email"
                                        title="<?= e($query['email']); ?>"
                                    >

                                        <?= e(
                                            $query['email']
                                        ); ?>

                                    </div>

                                </td>


                                <!-- PHONE -->

                                <td>

                                    <div class="phone">

                                        <?php if (
                                            !empty($query['phone'])
                                        ): ?>

                                            <?= e(
                                                $query['phone']
                                            ); ?>

                                        <?php else: ?>

                                            —

                                        <?php endif; ?>

                                    </div>

                                </td>


                                <!-- MESSAGE -->

                                <td>

                                    <div class="message-box">

                                        <div class="message-preview">

                                            <?= e(
                                                $message
                                            ); ?>

                                        </div>

                                        <?php if (
                                            strlen($message) > 150
                                        ): ?>

                                            <span class="read-more">
                                                Full message available
                                            </span>

                                        <?php endif; ?>

                                    </div>

                                </td>


                                <!-- STATUS -->

                                <td>

                                    <?php

                                    $status_label =
                                        ucfirst(
                                            $query_status
                                        );

                                    $status_icon = '•';

                                    if (
                                        $query_status === 'new'
                                    ) {
                                        $status_icon = '??';
                                    }

                                    elseif (
                                        $query_status === 'read'
                                    ) {
                                        $status_icon = '??';
                                    }

                                    elseif (
                                        $query_status === 'replied'
                                    ) {
                                        $status_icon = '?';
                                    }

                                    elseif (
                                        $query_status === 'closed'
                                    ) {
                                        $status_icon = '?';
                                    }

                                    ?>

                                    <span
                                        class="status-badge <?= e($status_class); ?>"
                                    >

                                        <?= $status_icon; ?>

                                        <?= e(
                                            $status_label
                                        ); ?>

                                    </span>


                                    <div
                                        class="status-action no-print"
                                        style="margin-top:8px;"
                                    >

                                        <form
                                            method="get"
                                            action="contact.php"
                                        >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= $query_id; ?>"
                                            >

                                            <input
                                                type="hidden"
                                                name="search"
                                                value="<?= e($search); ?>"
                                            >

                                            <input
                                                type="hidden"
                                                name="status"
                                                value="<?= e($status_filter); ?>"
                                            >

                                            <select
                                                name="change_status"
                                                onchange="this.form.submit();"
                                                title="Change Status"
                                            >

                                                <option
                                                    value="new"
                                                    <?= $query_status === 'new' ? 'selected' : ''; ?>
                                                >
                                                    New
                                                </option>

                                                <option
                                                    value="read"
                                                    <?= $query_status === 'read' ? 'selected' : ''; ?>
                                                >
                                                    Read
                                                </option>

                                                <option
                                                    value="replied"
                                                    <?= $query_status === 'replied' ? 'selected' : ''; ?>
                                                >
                                                    Replied
                                                </option>

                                                <option
                                                    value="closed"
                                                    <?= $query_status === 'closed' ? 'selected' : ''; ?>
                                                >
                                                    Closed
                                                </option>

                                            </select>

                                        </form>

                                    </div>

                                </td>


                                <!-- DATE -->

                                <td>

                                    <?php

                                    if (
                                        !empty(
                                            $query['submitted_at']
                                        )
                                    ) {

                                        $timestamp =
                                            strtotime(
                                                $query['submitted_at']
                                            );

                                    ?>

                                        <div class="date-main">

                                            <?= e(
                                                date(
                                                    'd M Y',
                                                    $timestamp
                                                )
                                            ); ?>

                                        </div>

                                        <div class="date-time">

                                            <?= e(
                                                date(
                                                    'h:i A',
                                                    $timestamp
                                                )
                                            ); ?>

                                        </div>

                                    <?php

                                    } else {

                                        echo '—';

                                    }

                                    ?>

                                </td>


                                <!-- ACTION -->

                                <td class="no-print">

                                    <div class="actions">

                                        <a
                                            href="contact_view.php?id=<?= $query_id; ?>"
                                            class="action-btn view-btn"
                                            title="View Query"
                                        >
                                            ??
                                        </a>


                                        <a
                                            href="contact.php?delete=<?= $query_id; ?>"
                                            class="action-btn delete-btn"
                                            title="Delete Query"
                                            onclick="return confirm('Are you sure you want to delete this contact query? This action cannot be undone.');"
                                        >
                                            ??
                                        </a>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>


                <!-- ==================================================
                     PAGINATION
                =================================================== -->

                <?php if ($total_pages > 1): ?>

                    <div class="pagination-area">

                        <div class="pagination-info">

                            Page
                            <strong>
                                <?= $page; ?>
                            </strong>

                            of

                            <strong>
                                <?= $total_pages; ?>
                            </strong>

                        </div>


                        <div class="pagination">

                            <?php

                            $prev_page =
                                $page - 1;

                            $next_page =
                                $page + 1;

                            ?>


                            <!-- PREVIOUS -->

                            <a
                                href="<?=
                                    $page > 1
                                    ? 'contact.php?' .
                                      http_build_query([
                                          'search' =>
                                              $search,
                                          'status' =>
                                              $status_filter,
                                          'page' =>
                                              $prev_page
                                      ])
                                    : '#';
                                ?>"
                                class="page-link <?= $page <= 1 ? 'disabled' : ''; ?>"
                            >
                                ‹
                            </a>


                            <?php

                            $start_page =
                                max(
                                    1,
                                    $page - 2
                                );

                            $end_page =
                                min(
                                    $total_pages,
                                    $page + 2
                                );

                            ?>


                            <?php if (
                                $start_page > 1
                            ): ?>

                                <a
                                    href="contact.php?<?= http_build_query([
                                        'search' =>
                                            $search,
                                        'status' =>
                                            $status_filter,
                                        'page' => 1
                                    ]); ?>"
                                    class="page-link"
                                >
                                    1
                                </a>

                                <?php if (
                                    $start_page > 2
                                ): ?>

                                    <span
                                        class="page-link disabled"
                                    >
                                        ...
                                    </span>

                                <?php endif; ?>

                            <?php endif; ?>


                            <?php for (
                                $i = $start_page;
                                $i <= $end_page;
                                $i++
                            ): ?>

                                <a
                                    href="contact.php?<?= http_build_query([
                                        'search' =>
                                            $search,
                                        'status' =>
                                            $status_filter,
                                        'page' =>
                                            $i
                                    ]); ?>"
                                    class="page-link <?= $i == $page ? 'active' : ''; ?>"
                                >
                                    <?= $i; ?>
                                </a>

                            <?php endfor; ?>


                            <?php if (
                                $end_page <
                                $total_pages
                            ): ?>

                                <?php if (
                                    $end_page <
                                    $total_pages - 1
                                ): ?>

                                    <span
                                        class="page-link disabled"
                                    >
                                        ...
                                    </span>

                                <?php endif; ?>


                                <a
                                    href="contact.php?<?= http_build_query([
                                        'search' =>
                                            $search,
                                        'status' =>
                                            $status_filter,
                                        'page' =>
                                            $total_pages
                                    ]); ?>"
                                    class="page-link"
                                >
                                    <?= $total_pages; ?>
                                </a>

                            <?php endif; ?>


                            <!-- NEXT -->

                            <a
                                href="<?=
                                    $page <
                                    $total_pages
                                    ? 'contact.php?' .
                                      http_build_query([
                                          'search' =>
                                              $search,
                                          'status' =>
                                              $status_filter,
                                          'page' =>
                                              $next_page
                                      ])
                                    : '#';
                                ?>"
                                class="page-link <?= $page >= $total_pages ? 'disabled' : ''; ?>"
                            >
                                ›
                            </a>

                        </div>

                    </div>

                <?php endif; ?>


            <?php else: ?>

                <!-- ==================================================
                     EMPTY STATE
                =================================================== -->

                <div class="empty-state">

                    <div class="empty-icon">
                        ??
                    </div>

                    <h3>
                        No Contact Queries Found
                    </h3>

                    <?php if (
                        $search !== '' ||
                        $status_filter !== ''
                    ): ?>

                        <p>
                            No contact query matches
                            your current search/filter.
                        </p>

                    <?php else: ?>

                        <p>
                            Customer contact enquiries
                            will appear here.
                        </p>

                    <?php endif; ?>

                </div>

            <?php endif; ?>

        </div>


        <div style="height:30px;"></div>

    </main>

</div>


<!-- ============================================================
     SIDEBAR JS
============================================================ -->

<script>

function toggleSidebar()
{
    const sidebar =
        document.getElementById('sidebar');

    const overlay =
        document.getElementById('sidebarOverlay');

    if (sidebar) {
        sidebar.classList.toggle('open');
    }

    if (overlay) {
        overlay.classList.toggle('show');
    }
}


function closeSidebar()
{
    const sidebar =
        document.getElementById('sidebar');

    const overlay =
        document.getElementById('sidebarOverlay');

    if (sidebar) {
        sidebar.classList.remove('open');
    }

    if (overlay) {
        overlay.classList.remove('show');
    }
}


document.addEventListener(
    'DOMContentLoaded',
    function()
    {

        document
            .querySelectorAll('.sidebar-menu a')
            .forEach(function(link)
            {

                link.addEventListener(
                    'click',
                    function()
                    {

                        if (
                            window.innerWidth <= 1000
                        ) {

                            closeSidebar();

                        }

                    }
                );

            });

    }
);


window.addEventListener(
    'resize',
    function()
    {

        if (
            window.innerWidth > 1000
        ) {

            const sidebar =
                document.getElementById('sidebar');

            const overlay =
                document.getElementById('sidebarOverlay');

            if (sidebar) {
                sidebar.classList.remove('open');
            }

            if (overlay) {
                overlay.classList.remove('show');
            }

        }

    }
);

</script>

</body>
</html>