<?php
/**
 * Pure Chemical Admin
 * File: admin/enquiry_items.php
 *
 * Database table used:
 * enquiry_items
 *
 * No new table is created.
 */

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
========================================================= */

function ei_e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function ei_post_string(string $key, string $default = ''): string
{
    return isset($_POST[$key]) ? trim((string)$_POST[$key]) : $default;
}

function ei_post_int(string $key, int $default = 0): int
{
    return isset($_POST[$key]) ? (int)$_POST[$key] : $default;
}

function ei_get_string(string $key, string $default = ''): string
{
    return isset($_GET[$key]) ? trim((string)$_GET[$key]) : $default;
}

function ei_get_int(string $key, int $default = 0): int
{
    return isset($_GET[$key]) ? (int)$_GET[$key] : $default;
}

function ei_csrf_field(): string
{
    if (function_exists('csrf_field')) {
        return csrf_field();
    }

    if (function_exists('csrf_token')) {
        return '<input type="hidden" name="csrf_token" value="' .
            ei_e(csrf_token()) . '">';
    }

    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }

    return '<input type="hidden" name="csrf_token" value="' .
        ei_e($_SESSION['csrf_token']) . '">';
}

function ei_verify_csrf(): bool
{
    if (function_exists('csrf_verify')) {
        return (bool)csrf_verify();
    }

    $token = $_POST['csrf_token'] ?? '';

    if (
        empty($_SESSION['csrf_token']) ||
        empty($token)
    ) {
        return false;
    }

    return hash_equals(
        (string)$_SESSION['csrf_token'],
        (string)$token
    );
}

function ei_redirect(string $url): never
{
    header('Location: ' . $url);
    exit;
}

function ei_flash(string $type, string $message): void
{
    $_SESSION['ei_flash'] = [
        'type' => $type,
        'message' => $message
    ];
}

function ei_get_flash(): ?array
{
    if (empty($_SESSION['ei_flash'])) {
        return null;
    }

    $flash = $_SESSION['ei_flash'];
    unset($_SESSION['ei_flash']);

    return $flash;
}

function ei_product_name(PDO $pdo, int $productId): string
{
    if ($productId <= 0) {
        return '';
    }

    try {
        $stmt = $pdo->prepare(
            "SELECT name FROM products WHERE id = ? LIMIT 1"
        );
        $stmt->execute([$productId]);

        return (string)($stmt->fetchColumn() ?: '');
    } catch (Throwable $e) {
        return '';
    }
}


/* =========================================================
   ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!ei_verify_csrf()) {
        ei_flash('error', 'Security token expired. Please try again.');
        ei_redirect('enquiry_items.php');
    }

    $action = ei_post_string('action');

    /* -----------------------------------------------------
       SAVE
    ----------------------------------------------------- */
    if ($action === 'save') {

        $id = ei_post_int('id');
        $enquiryId = ei_post_int('enquiry_id');
        $productId = ei_post_int('product_id');
        $productName = ei_post_string('product_name');
        $quantity = ei_post_string('quantity');
        $message = ei_post_string('message');

        if ($enquiryId <= 0) {
            ei_flash('error', 'Please select an enquiry.');
            ei_redirect('enquiry_items.php');
        }

        /*
         * Validate enquiry exists.
         */
        $stmt = $pdo->prepare(
            "SELECT id FROM enquiries WHERE id = ? LIMIT 1"
        );
        $stmt->execute([$enquiryId]);

        if (!$stmt->fetchColumn()) {
            ei_flash('error', 'Selected enquiry does not exist.');
            ei_redirect('enquiry_items.php');
        }

        /*
         * Product is optional.
         */
        if ($productId > 0) {

            $stmt = $pdo->prepare(
                "SELECT name FROM products WHERE id = ? LIMIT 1"
            );
            $stmt->execute([$productId]);

            $dbProductName = $stmt->fetchColumn();

            if ($dbProductName === false) {
                ei_flash('error', 'Selected product does not exist.');
                ei_redirect('enquiry_items.php');
            }

            /*
             * If product is selected but product_name is blank,
             * automatically use current product name.
             */
            if ($productName === '') {
                $productName = (string)$dbProductName;
            }
        }

        try {

            if ($id > 0) {

                $stmt = $pdo->prepare(
                    "UPDATE enquiry_items
                     SET
                        enquiry_id = ?,
                        product_id = ?,
                        product_name = ?,
                        quantity = ?,
                        message = ?
                     WHERE id = ?"
                );

                $stmt->execute([
                    $enquiryId,
                    $productId > 0 ? $productId : null,
                    $productName !== '' ? $productName : null,
                    $quantity !== '' ? $quantity : null,
                    $message !== '' ? $message : null,
                    $id
                ]);

                ei_flash(
                    'success',
                    'Enquiry item updated successfully.'
                );

            } else {

                $stmt = $pdo->prepare(
                    "INSERT INTO enquiry_items
                    (
                        enquiry_id,
                        product_id,
                        product_name,
                        quantity,
                        message
                    )
                    VALUES (?, ?, ?, ?, ?)"
                );

                $stmt->execute([
                    $enquiryId,
                    $productId > 0 ? $productId : null,
                    $productName !== '' ? $productName : null,
                    $quantity !== '' ? $quantity : null,
                    $message !== '' ? $message : null
                ]);

                ei_flash(
                    'success',
                    'Enquiry item added successfully.'
                );
            }

        } catch (Throwable $e) {

            error_log(
                'Enquiry Item Save Error: ' . $e->getMessage()
            );

            ei_flash(
                'error',
                'Unable to save enquiry item. Please try again.'
            );
        }

        ei_redirect('enquiry_items.php');
    }


    /* -----------------------------------------------------
       DELETE
    ----------------------------------------------------- */
    if ($action === 'delete') {

        $id = ei_post_int('id');

        if ($id <= 0) {
            ei_flash('error', 'Invalid enquiry item.');
            ei_redirect('enquiry_items.php');
        }

        try {

            $stmt = $pdo->prepare(
                "DELETE FROM enquiry_items WHERE id = ?"
            );

            $stmt->execute([$id]);

            ei_flash(
                'success',
                'Enquiry item deleted successfully.'
            );

        } catch (Throwable $e) {

            error_log(
                'Enquiry Item Delete Error: ' . $e->getMessage()
            );

            ei_flash(
                'error',
                'Unable to delete enquiry item.'
            );
        }

        ei_redirect('enquiry_items.php');
    }
}


/* =========================================================
   FILTERS
========================================================= */

$search = ei_get_string('search');
$filterEnquiry = ei_get_int('enquiry_id');
$filterProduct = ei_get_int('product_id');


/* =========================================================
   ENQUIRIES
========================================================= */

$enquiries = [];

try {

    $stmt = $pdo->query(
        "SELECT *
         FROM enquiries
         ORDER BY id DESC"
    );

    $enquiries = $stmt->fetchAll();

} catch (Throwable $e) {

    $enquiries = [];
}


/* =========================================================
   PRODUCTS
========================================================= */

$products = [];

try {

    $stmt = $pdo->query(
        "SELECT id, name
         FROM products
         ORDER BY name ASC"
    );

    $products = $stmt->fetchAll();

} catch (Throwable $e) {

    $products = [];
}


/* =========================================================
   EDIT RECORD
========================================================= */

$editId = ei_get_int('edit');
$editItem = null;

if ($editId > 0) {

    $stmt = $pdo->prepare(
        "SELECT *
         FROM enquiry_items
         WHERE id = ?
         LIMIT 1"
    );

    $stmt->execute([$editId]);
    $editItem = $stmt->fetch() ?: null;
}


/* =========================================================
   STATS
========================================================= */

$totalItems = 0;
$totalEnquiries = 0;
$totalProducts = 0;
$todayItems = 0;

try {

    $totalItems = (int)$pdo
        ->query("SELECT COUNT(*) FROM enquiry_items")
        ->fetchColumn();

    $totalEnquiries = (int)$pdo
        ->query("SELECT COUNT(DISTINCT enquiry_id) FROM enquiry_items")
        ->fetchColumn();

    $totalProducts = (int)$pdo
        ->query(
            "SELECT COUNT(DISTINCT product_id)
             FROM enquiry_items
             WHERE product_id IS NOT NULL"
        )
        ->fetchColumn();

    $todayItems = (int)$pdo
        ->query(
            "SELECT COUNT(*)
             FROM enquiry_items
             WHERE DATE(created_at) = CURDATE()"
        )
        ->fetchColumn();

} catch (Throwable $e) {
    // Keep defaults.
}


/* =========================================================
   LIST QUERY
========================================================= */

$where = [];
$params = [];

if ($search !== '') {

    $where[] = "(
        ei.product_name LIKE ?
        OR ei.quantity LIKE ?
        OR ei.message LIKE ?
        OR CAST(ei.id AS CHAR) LIKE ?
    )";

    $searchLike = '%' . $search . '%';

    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
}

if ($filterEnquiry > 0) {

    $where[] = "ei.enquiry_id = ?";
    $params[] = $filterEnquiry;
}

if ($filterProduct > 0) {

    $where[] = "ei.product_id = ?";
    $params[] = $filterProduct;
}

$sql = "
    SELECT
        ei.*,
        e.id AS enquiry_ref_id,
        p.id AS product_ref_id,
        p.name AS linked_product_name
    FROM enquiry_items ei
    LEFT JOIN enquiries e
        ON e.id = ei.enquiry_id
    LEFT JOIN products p
        ON p.id = ei.product_id
";

if (!empty($where)) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}

$sql .= " ORDER BY ei.id DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$items = $stmt->fetchAll();

$flash = ei_get_flash();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>Enquiry Items | Pure Chemical Admin</title>

    <meta
        name="theme-color"
        content="#0f172a"
    >

    <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: #2563eb;
            --primary-dark: #1d4ed8;
            --primary-soft: #eff6ff;

            --success: #16a34a;
            --success-soft: #f0fdf4;

            --danger: #dc2626;
            --danger-soft: #fef2f2;

            --warning: #d97706;
            --warning-soft: #fffbeb;

            --dark: #0f172a;
            --text: #1e293b;
            --muted: #64748b;

            --border: #e2e8f0;
            --bg: #f8fafc;
            --white: #ffffff;

            --radius: 18px;
            --shadow:
                0 10px 30px rgba(15, 23, 42, 0.06);

            --sidebar-width: 285px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            background:
                radial-gradient(
                    circle at top right,
                    rgba(37, 99, 235, 0.06),
                    transparent 28%
                ),
                var(--bg);

            color: var(--text);
            font-family: "Inter", sans-serif;
            font-size: 14px;
        }

        a {
            color: inherit;
            text-decoration: none;
        }

        button,
        input,
        select,
        textarea {
            font: inherit;
        }

        button {
            cursor: pointer;
        }

        /* =====================================================
           MAIN LAYOUT
        ===================================================== */

        .ei-page {
            margin-left: var(--sidebar-width);
            min-height: 100vh;
        }

        .ei-topbar {
            height: 76px;
            position: sticky;
            top: 0;
            z-index: 50;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 0 30px;

            background: rgba(255, 255, 255, 0.92);
            border-bottom: 1px solid rgba(226, 232, 240, 0.85);

            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
        }

        .ei-topbar-left {
            display: flex;
            align-items: center;
            gap: 14px;
        }

        .ei-page-title {
            margin: 0;
            font-size: 19px;
            font-weight: 800;
            color: var(--dark);
            letter-spacing: -0.02em;
        }

        .ei-page-subtitle {
            margin: 4px 0 0;
            color: var(--muted);
            font-size: 12px;
        }

        .ei-topbar-right {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .ei-admin-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;

            padding: 9px 13px;
            border: 1px solid var(--border);
            border-radius: 12px;

            background: #fff;
            color: var(--muted);
            font-size: 12px;
            font-weight: 600;
        }

        .ei-admin-badge i {
            color: var(--primary);
        }

        .ei-content {
            padding: 30px;
            max-width: 1700px;
            margin: 0 auto;
        }

        /* =====================================================
           MOBILE SIDEBAR BUTTON
        ===================================================== */

        .ei-mobile-menu {
            display: none;

            width: 42px;
            height: 42px;

            align-items: center;
            justify-content: center;

            border: 1px solid var(--border);
            border-radius: 12px;

            background: #fff;
            color: var(--dark);
        }

        /* =====================================================
           FLASH
        ===================================================== */

        .ei-alert {
            display: flex;
            align-items: center;
            gap: 12px;

            margin-bottom: 22px;
            padding: 14px 17px;

            border-radius: 14px;
            border: 1px solid transparent;

            font-weight: 600;
        }

        .ei-alert.success {
            background: var(--success-soft);
            color: #166534;
            border-color: #bbf7d0;
        }

        .ei-alert.error {
            background: var(--danger-soft);
            color: #991b1b;
            border-color: #fecaca;
        }

        .ei-alert-close {
            margin-left: auto;
            border: 0;
            background: transparent;
            color: inherit;
            opacity: .7;
        }

        /* =====================================================
           HEADER
        ===================================================== */

        .ei-heading {
            display: flex;
            align-items: flex-end;
            justify-content: space-between;
            gap: 20px;
            margin-bottom: 24px;
        }

        .ei-heading h1 {
            margin: 0;
            font-size: 30px;
            line-height: 1.2;
            letter-spacing: -0.04em;
            color: var(--dark);
        }

        .ei-heading p {
            margin: 8px 0 0;
            color: var(--muted);
            font-size: 13px;
        }

        .ei-heading-actions {
            display: flex;
            gap: 10px;
        }

        /* =====================================================
           BUTTONS
        ===================================================== */

        .ei-btn {
            min-height: 42px;

            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;

            padding: 0 15px;

            border-radius: 12px;
            border: 1px solid transparent;

            font-size: 13px;
            font-weight: 700;

            transition:
                transform .18s ease,
                box-shadow .18s ease,
                background .18s ease;
        }

        .ei-btn:hover {
            transform: translateY(-1px);
        }

        .ei-btn-primary {
            color: #fff;
            background: linear-gradient(
                135deg,
                var(--primary),
                var(--primary-dark)
            );

            box-shadow:
                0 8px 20px rgba(37, 99, 235, .20);
        }

        .ei-btn-secondary {
            color: var(--text);
            background: #fff;
            border-color: var(--border);
        }

        .ei-btn-danger {
            color: var(--danger);
            background: var(--danger-soft);
            border-color: #fecaca;
        }

        /* =====================================================
           STATS
        ===================================================== */

        .ei-stats {
            display: grid;
            grid-template-columns:
                repeat(4, minmax(0, 1fr));

            gap: 16px;
            margin-bottom: 24px;
        }

        .ei-stat {
            position: relative;
            overflow: hidden;

            padding: 20px;

            border: 1px solid var(--border);
            border-radius: var(--radius);

            background: #fff;
            box-shadow: var(--shadow);
        }

        .ei-stat::after {
            content: "";
            position: absolute;

            width: 90px;
            height: 90px;

            right: -30px;
            top: -30px;

            border-radius: 50%;
            background: rgba(37, 99, 235, .06);
        }

        .ei-stat-top {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .ei-stat-icon {
            width: 42px;
            height: 42px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 12px;

            color: var(--primary);
            background: var(--primary-soft);
        }

        .ei-stat:nth-child(2) .ei-stat-icon {
            color: #7c3aed;
            background: #f5f3ff;
        }

        .ei-stat:nth-child(3) .ei-stat-icon {
            color: #0891b2;
            background: #ecfeff;
        }

        .ei-stat:nth-child(4) .ei-stat-icon {
            color: #16a34a;
            background: #f0fdf4;
        }

        .ei-stat-label {
            margin-top: 17px;
            color: var(--muted);
            font-size: 12px;
            font-weight: 600;
        }

        .ei-stat-value {
            margin-top: 4px;
            color: var(--dark);
            font-size: 25px;
            font-weight: 800;
            letter-spacing: -0.04em;
        }

        /* =====================================================
           FILTERS
        ===================================================== */

        .ei-card {
            border: 1px solid var(--border);
            border-radius: var(--radius);
            background: #fff;
            box-shadow: var(--shadow);
        }

        .ei-filter-card {
            padding: 18px;
            margin-bottom: 22px;
        }

        .ei-filter-grid {
            display: grid;
            grid-template-columns:
                minmax(220px, 1.6fr)
                minmax(180px, 1fr)
                minmax(180px, 1fr)
                auto;

            gap: 12px;
            align-items: end;
        }

        .ei-field {
            min-width: 0;
        }

        .ei-field label {
            display: block;
            margin-bottom: 7px;

            color: #475569;
            font-size: 11px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: .06em;
        }

        .ei-input,
        .ei-select,
        .ei-textarea {
            width: 100%;

            border: 1px solid var(--border);
            border-radius: 11px;

            background: #fff;
            color: var(--text);

            outline: none;

            transition:
                border-color .18s ease,
                box-shadow .18s ease;
        }

        .ei-input,
        .ei-select {
            height: 43px;
            padding: 0 12px;
        }

        .ei-textarea {
            min-height: 105px;
            padding: 12px;
            resize: vertical;
        }

        .ei-input:focus,
        .ei-select:focus,
        .ei-textarea:focus {
            border-color: #93c5fd;

            box-shadow:
                0 0 0 4px rgba(37, 99, 235, .08);
        }

        .ei-filter-actions {
            display: flex;
            gap: 8px;
        }

        /* =====================================================
           TABLE
        ===================================================== */

        .ei-table-card {
            overflow: hidden;
        }

        .ei-table-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;

            padding: 18px 20px;

            border-bottom: 1px solid var(--border);
        }

        .ei-table-title {
            color: var(--dark);
            font-size: 15px;
            font-weight: 800;
        }

        .ei-table-count {
            display: inline-flex;
            align-items: center;

            padding: 6px 10px;

            border-radius: 999px;

            background: var(--primary-soft);
            color: var(--primary);

            font-size: 11px;
            font-weight: 800;
        }

        .ei-table-wrap {
            overflow-x: auto;
        }

        .ei-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 950px;
        }

        .ei-table th {
            padding: 13px 16px;

            background: #f8fafc;

            color: #64748b;

            font-size: 10px;
            font-weight: 800;

            text-transform: uppercase;
            letter-spacing: .07em;

            text-align: left;
            white-space: nowrap;
        }

        .ei-table td {
            padding: 16px;

            border-top: 1px solid #eef2f7;

            vertical-align: middle;
        }

        .ei-table tbody tr {
            transition: background .16s ease;
        }

        .ei-table tbody tr:hover {
            background: #fafcff;
        }

        .ei-id {
            display: inline-flex;

            min-width: 36px;
            height: 30px;

            align-items: center;
            justify-content: center;

            padding: 0 9px;

            border-radius: 9px;

            background: #f1f5f9;
            color: #475569;

            font-size: 11px;
            font-weight: 800;
        }

        .ei-enquiry {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .ei-enquiry strong {
            color: var(--dark);
            font-size: 13px;
        }

        .ei-enquiry span {
            color: var(--muted);
            font-size: 11px;
        }

        .ei-product {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .ei-product-icon {
            width: 36px;
            height: 36px;

            flex: 0 0 36px;

            display: flex;
            align-items: center;
            justify-content: center;

            border-radius: 10px;

            color: var(--primary);
            background: var(--primary-soft);
        }

        .ei-product-name {
            font-size: 13px;
            font-weight: 700;
            color: var(--dark);
        }

        .ei-product-id {
            margin-top: 3px;
            color: var(--muted);
            font-size: 10px;
        }

        .ei-quantity {
            display: inline-flex;

            padding: 6px 10px;

            border-radius: 8px;

            background: #f8fafc;
            border: 1px solid var(--border);

            color: #475569;
            font-size: 11px;
            font-weight: 700;
        }

        .ei-message {
            max-width: 280px;

            color: #64748b;

            font-size: 12px;
            line-height: 1.6;

            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;

            overflow: hidden;
        }

        .ei-date {
            color: #64748b;
            font-size: 11px;
            white-space: nowrap;
        }

        .ei-actions {
            display: flex;
            gap: 7px;
        }

        .ei-action {
            width: 34px;
            height: 34px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            border-radius: 9px;
            border: 1px solid var(--border);

            background: #fff;

            color: #64748b;

            transition: all .18s ease;
        }

        .ei-action:hover {
            transform: translateY(-1px);
            border-color: #cbd5e1;
            color: var(--primary);
            background: #f8fafc;
        }

        .ei-action.delete:hover {
            color: var(--danger);
            border-color: #fecaca;
            background: var(--danger-soft);
        }

        /* =====================================================
           EMPTY
        ===================================================== */

        .ei-empty {
            padding: 65px 25px;
            text-align: center;
        }

        .ei-empty-icon {
            width: 65px;
            height: 65px;

            display: flex;
            align-items: center;
            justify-content: center;

            margin: 0 auto 16px;

            border-radius: 20px;

            background: var(--primary-soft);
            color: var(--primary);

            font-size: 24px;
        }

        .ei-empty h3 {
            margin: 0;
            color: var(--dark);
            font-size: 16px;
        }

        .ei-empty p {
            max-width: 420px;
            margin: 8px auto 0;
            color: var(--muted);
            font-size: 12px;
            line-height: 1.7;
        }

        /* =====================================================
           FORM PANEL
        ===================================================== */

        .ei-form-card {
            margin-top: 22px;
            padding: 22px;
        }

        .ei-form-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;

            margin-bottom: 20px;
            padding-bottom: 17px;

            border-bottom: 1px solid var(--border);
        }

        .ei-form-header h2 {
            margin: 0;
            color: var(--dark);
            font-size: 16px;
            font-weight: 800;
        }

        .ei-form-header p {
            margin: 5px 0 0;
            color: var(--muted);
            font-size: 11px;
        }

        .ei-form-grid {
            display: grid;
            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 17px;
        }

        .ei-form-full {
            grid-column: 1 / -1;
        }

        .ei-product-preview {
            display: none;

            margin-top: 8px;
            padding: 9px 11px;

            border-radius: 9px;

            background: var(--primary-soft);
            color: var(--primary);

            font-size: 11px;
            font-weight: 700;
        }

        .ei-form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 9px;

            margin-top: 20px;
            padding-top: 18px;

            border-top: 1px solid var(--border);
        }

        /* =====================================================
           RESPONSIVE
        ===================================================== */

        @media (max-width: 1200px) {

            .ei-stats {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

            .ei-filter-grid {
                grid-template-columns:
                    repeat(2, minmax(0, 1fr));
            }

            .ei-filter-actions {
                grid-column: 1 / -1;
            }
        }

        @media (max-width: 991px) {

            .ei-page {
                margin-left: 0;
            }

            .ei-mobile-menu {
                display: inline-flex;
            }

            .ei-topbar {
                padding: 0 18px;
            }

            .ei-content {
                padding: 22px 18px;
            }

            .ei-admin-badge {
                display: none;
            }

            .ei-heading {
                align-items: flex-start;
                flex-direction: column;
            }

            .ei-heading-actions {
                width: 100%;
            }

            .ei-heading-actions .ei-btn {
                flex: 1;
            }
        }

        @media (max-width: 700px) {

            .ei-stats {
                grid-template-columns: 1fr;
            }

            .ei-filter-grid {
                grid-template-columns: 1fr;
            }

            .ei-filter-actions {
                grid-column: auto;
            }

            .ei-filter-actions .ei-btn {
                flex: 1;
            }

            .ei-form-grid {
                grid-template-columns: 1fr;
            }

            .ei-form-full {
                grid-column: auto;
            }

            .ei-heading h1 {
                font-size: 25px;
            }

            .ei-topbar {
                height: 68px;
            }

            .ei-page-subtitle {
                display: none;
            }
        }

        @media (max-width: 480px) {

            .ei-content {
                padding: 18px 12px;
            }

            .ei-heading-actions {
                flex-direction: column;
            }

            .ei-heading-actions .ei-btn {
                width: 100%;
            }

            .ei-form-card {
                padding: 16px;
            }

            .ei-form-actions {
                flex-direction: column-reverse;
            }

            .ei-form-actions .ei-btn {
                width: 100%;
            }
        }

    </style>
</head>

<body>

<?php
/*
 * Existing Pure Chemical admin sidebar.
 * No duplicate sidebar is created here.
 */
require_once __DIR__ . '/sidebar.php';
?>

<div class="ei-page">

    <!-- =====================================================
         TOPBAR
    ====================================================== -->
    <header class="ei-topbar">

        <div class="ei-topbar-left">

            <button
                type="button"
                class="ei-mobile-menu"
                onclick="toggleSidebar()"
                aria-label="Open menu"
            >
                <i class="fa-solid fa-bars"></i>
            </button>

            <div>
                <h1 class="ei-page-title">
                    Enquiry Items
                </h1>

                <p class="ei-page-subtitle">
                    Manage products and items attached to customer enquiries
                </p>
            </div>

        </div>

        <div class="ei-topbar-right">

            <div class="ei-admin-badge">
                <i class="fa-solid fa-shield-halved"></i>
                Admin Panel
            </div>

        </div>

    </header>


    <main class="ei-content">

        <!-- =================================================
             FLASH MESSAGE
        ================================================== -->

        <?php if ($flash): ?>

            <div
                class="ei-alert <?= ei_e($flash['type']) ?>"
                id="eiFlash"
            >

                <?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>
                    <?= ei_e($flash['message']) ?>
                </span>

                <button
                    type="button"
                    class="ei-alert-close"
                    onclick="document.getElementById('eiFlash').remove()"
                >
                    <i class="fa-solid fa-xmark"></i>
                </button>

            </div>

        <?php endif; ?>


        <!-- =================================================
             PAGE HEADING
        ================================================== -->

        <section class="ei-heading">

            <div>

                <h1>
                    Enquiry Items
                </h1>

                <p>
                    View and manage individual products requested through enquiries.
                </p>

            </div>

            <div class="ei-heading-actions">

                <a
                    href="enquiry_items.php"
                    class="ei-btn ei-btn-secondary"
                >
                    <i class="fa-solid fa-rotate-right"></i>
                    Refresh
                </a>

                <a
                    href="enquiry_items.php?add=1"
                    class="ei-btn ei-btn-primary"
                >
                    <i class="fa-solid fa-plus"></i>
                    Add Item
                </a>

            </div>

        </section>


        <!-- =================================================
             STATS
        ================================================== -->

        <section class="ei-stats">

            <div class="ei-stat">

                <div class="ei-stat-top">

                    <div class="ei-stat-icon">
                        <i class="fa-solid fa-layer-group"></i>
                    </div>

                </div>

                <div class="ei-stat-label">
                    Total Items
                </div>

                <div class="ei-stat-value">
                    <?= number_format($totalItems) ?>
                </div>

            </div>


            <div class="ei-stat">

                <div class="ei-stat-top">

                    <div class="ei-stat-icon">
                        <i class="fa-solid fa-envelope"></i>
                    </div>

                </div>

                <div class="ei-stat-label">
                    Enquiries With Items
                </div>

                <div class="ei-stat-value">
                    <?= number_format($totalEnquiries) ?>
                </div>

            </div>


            <div class="ei-stat">

                <div class="ei-stat-top">

                    <div class="ei-stat-icon">
                        <i class="fa-solid fa-box-open"></i>
                    </div>

                </div>

                <div class="ei-stat-label">
                    Products Referenced
                </div>

                <div class="ei-stat-value">
                    <?= number_format($totalProducts) ?>
                </div>

            </div>


            <div class="ei-stat">

                <div class="ei-stat-top">

                    <div class="ei-stat-icon">
                        <i class="fa-solid fa-calendar-day"></i>
                    </div>

                </div>

                <div class="ei-stat-label">
                    Added Today
                </div>

                <div class="ei-stat-value">
                    <?= number_format($todayItems) ?>
                </div>

            </div>

        </section>


        <!-- =================================================
             FILTERS
        ================================================== -->

        <section class="ei-card ei-filter-card">

            <form
                method="get"
                action="enquiry_items.php"
            >

                <div class="ei-filter-grid">

                    <div class="ei-field">

                        <label>
                            Search
                        </label>

                        <input
                            type="text"
                            name="search"
                            class="ei-input"
                            value="<?= ei_e($search) ?>"
                            placeholder="Search item, product, quantity or message..."
                        >

                    </div>


                    <div class="ei-field">

                        <label>
                            Enquiry
                        </label>

                        <select
                            name="enquiry_id"
                            class="ei-select"
                        >

                            <option value="">
                                All enquiries
                            </option>

                            <?php foreach ($enquiries as $enquiry): ?>

                                <option
                                    value="<?= (int)$enquiry['id'] ?>"
                                    <?= $filterEnquiry === (int)$enquiry['id'] ? 'selected' : '' ?>
                                >
                                    Enquiry #<?= (int)$enquiry['id'] ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <div class="ei-field">

                        <label>
                            Product
                        </label>

                        <select
                            name="product_id"
                            class="ei-select"
                        >

                            <option value="">
                                All products
                            </option>

                            <?php foreach ($products as $product): ?>

                                <option
                                    value="<?= (int)$product['id'] ?>"
                                    <?= $filterProduct === (int)$product['id'] ? 'selected' : '' ?>
                                >
                                    <?= ei_e($product['name']) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <div class="ei-filter-actions">

                        <button
                            type="submit"
                            class="ei-btn ei-btn-primary"
                        >
                            <i class="fa-solid fa-filter"></i>
                            Filter
                        </button>

                        <a
                            href="enquiry_items.php"
                            class="ei-btn ei-btn-secondary"
                        >
                            Reset
                        </a>

                    </div>

                </div>

            </form>

        </section>


        <!-- =================================================
             ITEMS TABLE
        ================================================== -->

        <section class="ei-card ei-table-card">

            <div class="ei-table-header">

                <div class="ei-table-title">
                    Enquiry Item Records
                </div>

                <div class="ei-table-count">
                    <?= number_format(count($items)) ?> Records
                </div>

            </div>


            <?php if (!empty($items)): ?>

                <div class="ei-table-wrap">

                    <table class="ei-table">

                        <thead>

                            <tr>

                                <th>
                                    ID
                                </th>

                                <th>
                                    Enquiry
                                </th>

                                <th>
                                    Product
                                </th>

                                <th>
                                    Quantity
                                </th>

                                <th>
                                    Message
                                </th>

                                <th>
                                    Created
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($items as $item): ?>

                            <tr>

                                <td>

                                    <span class="ei-id">
                                        #<?= (int)$item['id'] ?>
                                    </span>

                                </td>


                                <td>

                                    <div class="ei-enquiry">

                                        <strong>
                                            Enquiry #<?= (int)$item['enquiry_id'] ?>
                                        </strong>

                                        <span>
                                            Enquiry record
                                        </span>

                                    </div>

                                </td>


                                <td>

                                    <div class="ei-product">

                                        <div class="ei-product-icon">

                                            <i class="fa-solid fa-flask"></i>

                                        </div>

                                        <div>

                                            <div class="ei-product-name">

                                                <?php
                                                $displayProduct =
                                                    $item['product_name']
                                                    ?: $item['linked_product_name']
                                                    ?: 'Product not specified';
                                                ?>

                                                <?= ei_e($displayProduct) ?>

                                            </div>

                                            <?php if (!empty($item['product_id'])): ?>

                                                <div class="ei-product-id">
                                                    Product ID:
                                                    #<?= (int)$item['product_id'] ?>
                                                </div>

                                            <?php else: ?>

                                                <div class="ei-product-id">
                                                    Custom / manual product
                                                </div>

                                            <?php endif; ?>

                                        </div>

                                    </div>

                                </td>


                                <td>

                                    <?php if ($item['quantity'] !== null && $item['quantity'] !== ''): ?>

                                        <span class="ei-quantity">
                                            <?= ei_e($item['quantity']) ?>
                                        </span>

                                    <?php else: ?>

                                        <span style="color:#94a3b8;">
                                            —
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <td>

                                    <?php if (!empty($item['message'])): ?>

                                        <div
                                            class="ei-message"
                                            title="<?= ei_e($item['message']) ?>"
                                        >
                                            <?= ei_e($item['message']) ?>
                                        </div>

                                    <?php else: ?>

                                        <span style="color:#94a3b8;">
                                            No message
                                        </span>

                                    <?php endif; ?>

                                </td>


                                <td>

                                    <div class="ei-date">

                                        <?php
                                        if (!empty($item['created_at'])) {
                                            echo ei_e(
                                                date(
                                                    'd M Y, h:i A',
                                                    strtotime($item['created_at'])
                                                )
                                            );
                                        } else {
                                            echo '—';
                                        }
                                        ?>

                                    </div>

                                </td>


                                <td>

                                    <div class="ei-actions">

                                        <a
                                            href="enquiry_items.php?edit=<?= (int)$item['id'] ?>"
                                            class="ei-action"
                                            title="Edit"
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </a>


                                        <form
                                            method="post"
                                            style="display:inline;"
                                            onsubmit="return confirm('Are you sure you want to delete this enquiry item?');"
                                        >

                                            <?= ei_csrf_field() ?>

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="delete"
                                            >

                                            <input
                                                type="hidden"
                                                name="id"
                                                value="<?= (int)$item['id'] ?>"
                                            >

                                            <button
                                                type="submit"
                                                class="ei-action delete"
                                                title="Delete"
                                            >
                                                <i class="fa-solid fa-trash"></i>
                                            </button>

                                        </form>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php else: ?>

                <div class="ei-empty">

                    <div class="ei-empty-icon">
                        <i class="fa-solid fa-layer-group"></i>
                    </div>

                    <h3>
                        No enquiry items found
                    </h3>

                    <p>
                        There are no enquiry item records matching your
                        current filters.
                    </p>

                    <div style="margin-top:18px;">

                        <a
                            href="enquiry_items.php?add=1"
                            class="ei-btn ei-btn-primary"
                        >
                            <i class="fa-solid fa-plus"></i>
                            Add Enquiry Item
                        </a>

                    </div>

                </div>

            <?php endif; ?>

        </section>


        <!-- =================================================
             ADD / EDIT FORM
        ================================================== -->

        <?php if ($editItem || isset($_GET['add'])): ?>

            <section class="ei-card ei-form-card" id="item-form">

                <div class="ei-form-header">

                    <div>

                        <h2>

                            <?php if ($editItem): ?>

                                <i
                                    class="fa-solid fa-pen-to-square"
                                    style="color:var(--primary);margin-right:7px;"
                                ></i>

                                Edit Enquiry Item

                            <?php else: ?>

                                <i
                                    class="fa-solid fa-plus"
                                    style="color:var(--primary);margin-right:7px;"
                                ></i>

                                Add Enquiry Item

                            <?php endif; ?>

                        </h2>

                        <p>
                            Connect an enquiry with a requested product/item.
                        </p>

                    </div>


                    <a
                        href="enquiry_items.php"
                        class="ei-btn ei-btn-secondary"
                    >
                        <i class="fa-solid fa-xmark"></i>
                        Close
                    </a>

                </div>


                <form
                    method="post"
                    action="enquiry_items.php"
                >

                    <?= ei_csrf_field() ?>

                    <input
                        type="hidden"
                        name="action"
                        value="save"
                    >

                    <input
                        type="hidden"
                        name="id"
                        value="<?= $editItem ? (int)$editItem['id'] : 0 ?>"
                    >


                    <div class="ei-form-grid">

                        <!-- ENQUIRY -->

                        <div class="ei-field">

                            <label>
                                Enquiry *
                            </label>

                            <select
                                name="enquiry_id"
                                class="ei-select"
                                required
                            >

                                <option value="">
                                    Select enquiry
                                </option>

                                <?php foreach ($enquiries as $enquiry): ?>

                                    <?php
                                    $selectedEnquiry =
                                        $editItem
                                        ? (int)$editItem['enquiry_id']
                                        : 0;
                                    ?>

                                    <option
                                        value="<?= (int)$enquiry['id'] ?>"
                                        <?= $selectedEnquiry === (int)$enquiry['id'] ? 'selected' : '' ?>
                                    >
                                        Enquiry #<?= (int)$enquiry['id'] ?>
                                    </option>

                                <?php endforeach; ?>

                            </select>

                        </div>


                        <!-- PRODUCT -->

                        <div class="ei-field">

                            <label>
                                Product
                            </label>

                            <select
                                name="product_id"
                                id="eiProduct"
                                class="ei-select"
                            >

                                <option value="">
                                    No linked product
                                </option>

                                <?php
                                $selectedProduct =
                                    $editItem
                                    ? (int)$editItem['product_id']
                                    : 0;
                                ?>

                                <?php foreach ($products as $product): ?>

                                    <option
                                        value="<?= (int)$product['id'] ?>"
                                        data-name="<?= ei_e($product['name']) ?>"
                                        <?= $selectedProduct === (int)$product['id'] ? 'selected' : '' ?>
                                    >
                                        <?= ei_e($product['name']) ?>
                                    </option>

                                <?php endforeach; ?>

                            </select>

                            <div
                                id="eiProductPreview"
                                class="ei-product-preview"
                            >
                                <i class="fa-solid fa-circle-info"></i>
                                Product name will be used automatically if
                                the name field is empty.
                            </div>

                        </div>


                        <!-- PRODUCT NAME -->

                        <div class="ei-field">

                            <label>
                                Product Name
                            </label>

                            <input
                                type="text"
                                name="product_name"
                                id="eiProductName"
                                class="ei-input"
                                maxlength="255"
                                value="<?= ei_e($editItem['product_name'] ?? '') ?>"
                                placeholder="Enter product name"
                            >

                        </div>


                        <!-- QUANTITY -->

                        <div class="ei-field">

                            <label>
                                Quantity
                            </label>

                            <input
                                type="text"
                                name="quantity"
                                class="ei-input"
                                maxlength="150"
                                value="<?= ei_e($editItem['quantity'] ?? '') ?>"
                                placeholder="e.g. 100 Kg, 20 Bags"
                            >

                        </div>


                        <!-- MESSAGE -->

                        <div class="ei-field ei-form-full">

                            <label>
                                Message
                            </label>

                            <textarea
                                name="message"
                                class="ei-textarea"
                                placeholder="Additional requirement or enquiry item message..."
                            ><?= ei_e($editItem['message'] ?? '') ?></textarea>

                        </div>

                    </div>


                    <div class="ei-form-actions">

                        <a
                            href="enquiry_items.php"
                            class="ei-btn ei-btn-secondary"
                        >
                            Cancel
                        </a>

                        <button
                            type="submit"
                            class="ei-btn ei-btn-primary"
                        >

                            <?php if ($editItem): ?>

                                <i class="fa-solid fa-floppy-disk"></i>
                                Update Item

                            <?php else: ?>

                                <i class="fa-solid fa-plus"></i>
                                Save Item

                            <?php endif; ?>

                        </button>

                    </div>

                </form>

            </section>

        <?php endif; ?>

    </main>

</div>


<script>

    /*
     * Product selection helper
     */
    (function () {

        const productSelect =
            document.getElementById('eiProduct');

        const productName =
            document.getElementById('eiProductName');

        const productPreview =
            document.getElementById('eiProductPreview');

        if (!productSelect || !productName) {
            return;
        }

        function updateProductName() {

            const option =
                productSelect.options[
                    productSelect.selectedIndex
                ];

            if (
                option &&
                option.value &&
                productPreview
            ) {
                productPreview.style.display = 'block';
            } else if (productPreview) {
                productPreview.style.display = 'none';
            }

        }

        productSelect.addEventListener(
            'change',
            updateProductName
        );

        updateProductName();

    })();


    /*
     * Auto hide flash message.
     */
    setTimeout(function () {

        const flash =
            document.getElementById('eiFlash');

        if (flash) {
            flash.style.opacity = '0';

            flash.style.transition =
                'opacity .3s ease';

            setTimeout(function () {
                flash.remove();
            }, 300);
        }

    }, 4500);


    /*
     * Sidebar mobile toggle.
     *
     * Existing sidebar normally has #pcSidebar.
     */
    function toggleSidebar() {

        const sidebar =
            document.getElementById('pcSidebar');

        if (!sidebar) {
            return;
        }

        sidebar.classList.toggle('open');

    }


    /*
     * Close mobile sidebar when clicking outside.
     */
    document.addEventListener(
        'click',
        function (event) {

            const sidebar =
                document.getElementById('pcSidebar');

            const button =
                document.querySelector('.ei-mobile-menu');

            if (
                !sidebar ||
                !button ||
                window.innerWidth > 991
            ) {
                return;
            }

            if (
                sidebar.classList.contains('open') &&
                !sidebar.contains(event.target) &&
                !button.contains(event.target)
            ) {
                sidebar.classList.remove('open');
            }

        }
    );

</script>

</body>
</html>