<?php
declare(strict_types=1);

/**
 * Pure Chemical Admin
 * File: admin/products.php
 *
 * Product Management
 *
 * Uses ONLY existing `products` table.
 */

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/csrf.php';

requireAdmin();

$page_title  = 'Products';
$active_menu = 'products';

/*
|--------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------
*/

if (!function_exists('e')) {
    function e(mixed $value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function productStatusClass(string $status): string
{
    return match ($status) {
        'published' => 'published',
        'inactive'  => 'inactive',
        default     => 'draft',
    };
}

function productStatusLabel(string $status): string
{
    return match ($status) {
        'published' => 'Published',
        'inactive'  => 'Inactive',
        default     => 'Draft',
    };
}

/*
|--------------------------------------------------------------------------
| CSRF
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    try {

        if (function_exists('requireCsrf')) {
            requireCsrf();
        }

        $action = trim((string)($_POST['action'] ?? ''));

        /*
        |--------------------------------------------------------------------------
        | Delete Product
        |--------------------------------------------------------------------------
        */

        if ($action === 'delete_product') {

            $productId = (int)($_POST['product_id'] ?? 0);

            if ($productId <= 0) {
                throw new RuntimeException('Invalid product selected.');
            }

            $check = $pdo->prepare("
                SELECT id, name
                FROM products
                WHERE id = ?
                LIMIT 1
            ");

            $check->execute([$productId]);

            $product = $check->fetch();

            if (!$product) {
                throw new RuntimeException('Product not found.');
            }

            /*
             * Delete only the product record.
             *
             * Related records such as media/categories/documents
             * are NOT deleted here.
             */
            $delete = $pdo->prepare("
                DELETE FROM products
                WHERE id = ?
                LIMIT 1
            ");

            $delete->execute([$productId]);

            header('Location: products.php?deleted=1');
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Quick Status
        |--------------------------------------------------------------------------
        */

        if ($action === 'update_status') {

            $productId = (int)($_POST['product_id'] ?? 0);
            $status    = trim((string)($_POST['status'] ?? ''));

            $allowedStatuses = [
                'draft',
                'published',
                'inactive'
            ];

            if ($productId <= 0) {
                throw new RuntimeException('Invalid product selected.');
            }

            if (!in_array($status, $allowedStatuses, true)) {
                throw new RuntimeException('Invalid product status.');
            }

            $stmt = $pdo->prepare("
                UPDATE products
                SET status = ?
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $status,
                $productId
            ]);

            header('Location: products.php?updated=1');
            exit;
        }

        /*
        |--------------------------------------------------------------------------
        | Quick Featured Toggle
        |--------------------------------------------------------------------------
        */

        if ($action === 'toggle_featured') {

            $productId = (int)($_POST['product_id'] ?? 0);

            if ($productId <= 0) {
                throw new RuntimeException('Invalid product selected.');
            }

            $stmt = $pdo->prepare("
                UPDATE products
                SET featured = CASE
                    WHEN featured = 1 THEN 0
                    ELSE 1
                END
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([$productId]);

            header('Location: products.php?updated=1');
            exit;
        }

    } catch (Throwable $e) {

        $error = $e->getMessage();
    }
}

/*
|--------------------------------------------------------------------------
| Filters
|--------------------------------------------------------------------------
*/

$search = trim((string)($_GET['search'] ?? ''));

$status = trim((string)($_GET['status'] ?? ''));

$featured = trim((string)($_GET['featured'] ?? ''));

$sort = trim((string)($_GET['sort'] ?? 'newest'));

$page = max(
    1,
    (int)($_GET['page'] ?? 1)
);

$perPage = 12;

$allowedStatuses = [
    'draft',
    'published',
    'inactive'
];

if (!in_array($status, $allowedStatuses, true)) {
    $status = '';
}

if (!in_array($featured, ['0', '1'], true)) {
    $featured = '';
}

/*
|--------------------------------------------------------------------------
| Sorting
|--------------------------------------------------------------------------
*/

$orderBy = match ($sort) {

    'name_asc' => 'p.name ASC',

    'name_desc' => 'p.name DESC',

    'sort_asc' => 'p.sort_order ASC, p.id DESC',

    'sort_desc' => 'p.sort_order DESC, p.id DESC',

    'oldest' => 'p.created_at ASC',

    default => 'p.created_at DESC',
};

/*
|--------------------------------------------------------------------------
| WHERE
|--------------------------------------------------------------------------
*/

$where = [];

$params = [];

if ($search !== '') {

    $where[] = "
        (
            p.name LIKE ?
            OR p.product_code LIKE ?
            OR p.cas_number LIKE ?
            OR p.grade LIKE ?
            OR p.sku LIKE ?
        )
    ";

    $searchValue = '%' . $search . '%';

    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;
}

if ($status !== '') {

    $where[] = "p.status = ?";

    $params[] = $status;
}

if ($featured !== '') {

    $where[] = "p.featured = ?";

    $params[] = (int)$featured;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

/*
|--------------------------------------------------------------------------
| Statistics
|--------------------------------------------------------------------------
*/

$statsStmt = $pdo->query("
    SELECT
        COUNT(*) AS total_products,
        SUM(CASE WHEN status = 'published' THEN 1 ELSE 0 END) AS published_products,
        SUM(CASE WHEN status = 'draft' THEN 1 ELSE 0 END) AS draft_products,
        SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) AS inactive_products,
        SUM(CASE WHEN featured = 1 THEN 1 ELSE 0 END) AS featured_products
    FROM products
");

$stats = $statsStmt->fetch() ?: [
    'total_products'     => 0,
    'published_products' => 0,
    'draft_products'     => 0,
    'inactive_products'  => 0,
    'featured_products'  => 0,
];

/*
|--------------------------------------------------------------------------
| Total Filtered Products
|--------------------------------------------------------------------------
*/

$countSql = "
    SELECT COUNT(*)
    FROM products p
    {$whereSql}
";

$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);

$totalFiltered = (int)$countStmt->fetchColumn();

$totalPages = max(
    1,
    (int)ceil($totalFiltered / $perPage)
);

if ($page > $totalPages) {
    $page = $totalPages;
}

$offset = ($page - 1) * $perPage;

/*
|--------------------------------------------------------------------------
| Products
|--------------------------------------------------------------------------
*/

$sql = "
    SELECT
        p.id,
        p.name,
        p.slug,
        p.product_code,
        p.cas_number,
        p.grade,
        p.molecular_formula,
        p.molecular_weight,
        p.sku,
        p.short_description,
        p.description,
        p.application,
        p.packaging,
        p.featured_image_id,
        p.status,
        p.featured,
        p.sort_order,
        p.published_at,
        p.created_by,
        p.updated_by,
        p.created_at,
        p.updated_at
    FROM products p
    {$whereSql}
    ORDER BY {$orderBy}
    LIMIT {$perPage}
    OFFSET {$offset}
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$products = $stmt->fetchAll();

/*
|--------------------------------------------------------------------------
| Query String Helper
|--------------------------------------------------------------------------
*/

function buildProductUrl(array $changes = []): string
{
    $query = $_GET;

    foreach ($changes as $key => $value) {

        if ($value === null || $value === '') {
            unset($query[$key]);
        } else {
            $query[$key] = $value;
        }
    }

    return 'products.php?' . http_build_query($query);
}

require_once __DIR__ . '/header.php';
?>

<style>
/* =========================================================
   PRODUCTS ADMIN
========================================================= */

.products-page {
    --p-primary: #0f766e;
    --p-primary-dark: #115e59;
    --p-primary-soft: #ecfdf5;

    --p-text: #111827;
    --p-muted: #6b7280;

    --p-border: #e5e7eb;
    --p-bg: #f6f8fb;
    --p-card: #ffffff;

    min-height: calc(100vh - 70px);
    padding: 24px;
    background: var(--p-bg);
}

.products-container {
    max-width: 1500px;
    margin: 0 auto;
}

/* =========================================================
   HEADER
========================================================= */

.products-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;
    margin-bottom: 24px;
}

.products-breadcrumb {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    color: var(--p-muted);
    font-size: 12px;
}

.products-breadcrumb i {
    font-size: 9px;
}

.products-title {
    margin: 0;
    color: var(--p-text);
    font-size: 28px;
    line-height: 1.2;
    font-weight: 800;
    letter-spacing: -.7px;
}

.products-subtitle {
    margin: 7px 0 0;
    color: var(--p-muted);
    font-size: 14px;
}

.products-add-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    min-height: 44px;
    padding: 0 17px;
    border-radius: 11px;
    background: var(--p-primary);
    color: #fff;
    text-decoration: none;
    font-size: 13px;
    font-weight: 750;
    box-shadow: 0 8px 20px rgba(15, 118, 110, .18);
    transition: .2s ease;
}

.products-add-btn:hover {
    background: var(--p-primary-dark);
    color: #fff;
    transform: translateY(-1px);
}

/* =========================================================
   STATS
========================================================= */

.products-stats {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 14px;
    margin-bottom: 20px;
}

.product-stat {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
    padding: 16px;
    background: var(--p-card);
    border: 1px solid var(--p-border);
    border-radius: 16px;
    box-shadow: 0 7px 24px rgba(15, 23, 42, .04);
}

.product-stat-icon {
    width: 40px;
    height: 40px;
    flex: 0 0 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 11px;
    background: #f1f5f9;
    color: #64748b;
}

.product-stat-content {
    min-width: 0;
}

.product-stat-number {
    display: block;
    color: var(--p-text);
    font-size: 19px;
    line-height: 1.1;
    font-weight: 800;
}

.product-stat-label {
    display: block;
    margin-top: 3px;
    color: var(--p-muted);
    font-size: 11px;
}

/* =========================================================
   FILTER CARD
========================================================= */

.products-card {
    background: var(--p-card);
    border: 1px solid var(--p-border);
    border-radius: 18px;
    box-shadow: 0 8px 30px rgba(15, 23, 42, .05);
    overflow: hidden;
}

.products-filter {
    padding: 17px;
    border-bottom: 1px solid var(--p-border);
}

.products-filter-form {
    display: grid;
    grid-template-columns: minmax(220px, 1.7fr) 170px 150px 180px auto;
    gap: 10px;
    align-items: center;
}

.product-input,
.product-select {
    width: 100%;
    height: 42px;
    box-sizing: border-box;
    padding: 0 12px;
    border: 1px solid #dfe3e8;
    border-radius: 10px;
    outline: none;
    background: #fff;
    color: var(--p-text);
    font-family: inherit;
    font-size: 13px;
    transition: .2s ease;
}

.product-input:focus,
.product-select:focus {
    border-color: var(--p-primary);
    box-shadow: 0 0 0 3px rgba(15, 118, 110, .08);
}

.product-search {
    position: relative;
}

.product-search i {
    position: absolute;
    left: 13px;
    top: 50%;
    transform: translateY(-50%);
    color: #94a3b8;
    font-size: 12px;
}

.product-search input {
    padding-left: 36px;
}

.filter-btn,
.reset-btn {
    height: 42px;
    padding: 0 14px;
    border-radius: 10px;
    border: 1px solid var(--p-border);
    font-family: inherit;
    font-size: 12px;
    font-weight: 700;
    text-decoration: none;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
}

.filter-btn {
    border-color: var(--p-primary);
    background: var(--p-primary);
    color: #fff;
}

.filter-btn:hover {
    background: var(--p-primary-dark);
}

.reset-btn {
    background: #fff;
    color: #64748b;
}

.reset-btn:hover {
    background: #f8fafc;
    color: var(--p-text);
}

/* =========================================================
   TABLE
========================================================= */

.products-table-wrap {
    width: 100%;
    overflow-x: auto;
}

.products-table {
    width: 100%;
    min-width: 1050px;
    border-collapse: collapse;
}

.products-table th {
    padding: 13px 16px;
    background: #fafbfc;
    border-bottom: 1px solid var(--p-border);
    color: #64748b;
    text-align: left;
    white-space: nowrap;
    font-size: 10px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: .45px;
}

.products-table td {
    padding: 15px 16px;
    border-bottom: 1px solid #edf0f3;
    vertical-align: middle;
}

.products-table tbody tr {
    transition: .15s ease;
}

.products-table tbody tr:hover {
    background: #fbfdfd;
}

.product-name-cell {
    min-width: 260px;
}

.product-name-wrap {
    display: flex;
    align-items: center;
    gap: 11px;
}

.product-placeholder {
    width: 44px;
    height: 44px;
    flex: 0 0 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 11px;
    background: #f1f5f9;
    color: #94a3b8;
}

.product-name {
    display: block;
    max-width: 250px;
    color: var(--p-text);
    font-size: 13px;
    font-weight: 750;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.product-slug {
    display: block;
    max-width: 250px;
    margin-top: 3px;
    color: #94a3b8;
    font-size: 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.product-code {
    color: var(--p-text);
    font-size: 12px;
    font-weight: 700;
}

.product-muted {
    color: var(--p-muted);
    font-size: 12px;
}

.product-grade {
    display: inline-flex;
    align-items: center;
    max-width: 130px;
    padding: 5px 8px;
    border-radius: 7px;
    background: #f8fafc;
    color: #475569;
    font-size: 10px;
    font-weight: 700;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* =========================================================
   STATUS
========================================================= */

.product-status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 9px;
    border-radius: 999px;
    font-size: 10px;
    font-weight: 800;
}

.product-status.published {
    background: #dcfce7;
    color: #166534;
}

.product-status.draft {
    background: #fef3c7;
    color: #92400e;
}

.product-status.inactive {
    background: #f1f5f9;
    color: #64748b;
}

.product-status i {
    font-size: 6px;
}

/* =========================================================
   FEATURED
========================================================= */

.featured-btn {
    width: 32px;
    height: 32px;
    border: 0;
    border-radius: 9px;
    background: #f8fafc;
    color: #94a3b8;
    cursor: pointer;
    transition: .2s ease;
}

.featured-btn:hover {
    background: #f1f5f9;
    color: #64748b;
}

.featured-btn.is-featured {
    background: #fef3c7;
    color: #d97706;
}

/* =========================================================
   ACTIONS
========================================================= */

.product-actions {
    display: flex;
    align-items: center;
    gap: 6px;
}

.product-action {
    width: 32px;
    height: 32px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: 1px solid var(--p-border);
    border-radius: 8px;
    background: #fff;
    color: #64748b;
    text-decoration: none;
    cursor: pointer;
    transition: .18s ease;
}

.product-action:hover {
    background: #f8fafc;
    color: var(--p-primary);
    border-color: #cbd5e1;
}

.product-action.delete:hover {
    background: #fef2f2;
    color: #dc2626;
    border-color: #fecaca;
}

/* =========================================================
   EMPTY
========================================================= */

.products-empty {
    padding: 70px 20px;
    text-align: center;
}

.products-empty-icon {
    width: 60px;
    height: 60px;
    margin: 0 auto 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 17px;
    background: #f1f5f9;
    color: #94a3b8;
    font-size: 23px;
}

.products-empty h3 {
    margin: 0;
    color: var(--p-text);
    font-size: 17px;
}

.products-empty p {
    max-width: 430px;
    margin: 7px auto 18px;
    color: var(--p-muted);
    font-size: 13px;
    line-height: 1.6;
}

/* =========================================================
   PAGINATION
========================================================= */

.products-pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 15px;
    padding: 15px 17px;
    border-top: 1px solid var(--p-border);
}

.pagination-info {
    color: var(--p-muted);
    font-size: 11px;
}

.pagination-links {
    display: flex;
    align-items: center;
    gap: 5px;
}

.pagination-link {
    min-width: 32px;
    height: 32px;
    padding: 0 9px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: 1px solid var(--p-border);
    border-radius: 8px;
    background: #fff;
    color: #64748b;
    text-decoration: none;
    font-size: 11px;
    font-weight: 700;
}

.pagination-link:hover {
    color: var(--p-primary);
    border-color: #cbd5e1;
}

.pagination-link.active {
    background: var(--p-primary);
    border-color: var(--p-primary);
    color: #fff;
}

/* =========================================================
   TOAST
========================================================= */

.products-toast {
    position: fixed;
    right: 24px;
    bottom: 24px;
    z-index: 9999;
    display: flex;
    align-items: center;
    gap: 10px;
    min-width: 250px;
    max-width: 380px;
    padding: 13px 15px;
    border-radius: 12px;
    background: #111827;
    color: #fff;
    box-shadow: 0 16px 40px rgba(15, 23, 42, .2);
    font-size: 12px;
    animation: toastIn .25s ease;
}

@keyframes toastIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* =========================================================
   RESPONSIVE
========================================================= */

@media (max-width: 1250px) {

    .products-stats {
        grid-template-columns: repeat(3, 1fr);
    }

    .products-filter-form {
        grid-template-columns: 1fr 1fr 1fr;
    }

    .product-search {
        grid-column: span 3;
    }
}

@media (max-width: 800px) {

    .products-page {
        padding: 16px;
    }

    .products-header {
        flex-direction: column;
    }

    .products-add-btn {
        width: 100%;
    }

    .products-stats {
        grid-template-columns: repeat(2, 1fr);
    }

    .products-filter-form {
        grid-template-columns: 1fr 1fr;
    }

    .product-search {
        grid-column: span 2;
    }

    .products-pagination {
        flex-direction: column;
        align-items: stretch;
    }

    .pagination-links {
        justify-content: center;
        flex-wrap: wrap;
    }
}

@media (max-width: 520px) {

    .products-page {
        padding: 12px;
    }

    .products-title {
        font-size: 23px;
    }

    .products-stats {
        grid-template-columns: 1fr;
    }

    .products-filter-form {
        grid-template-columns: 1fr;
    }

    .product-search {
        grid-column: span 1;
    }

    .filter-btn,
    .reset-btn {
        width: 100%;
    }

    .products-toast {
        left: 12px;
        right: 12px;
        bottom: 12px;
        min-width: 0;
    }
}
</style>

<div class="products-page">

    <div class="products-container">

        <!-- =====================================================
             HEADER
        ====================================================== -->

        <div class="products-header">

            <div>

                <div class="products-breadcrumb">
                    <span>Products</span>
                    <i class="fa-solid fa-chevron-right"></i>
                    <span>All Products</span>
                </div>

                <h1 class="products-title">
                    Products
                </h1>

                <p class="products-subtitle">
                    Manage your chemical products, publishing status,
                    featured products and product information.
                </p>

            </div>

            <a
                href="product_add.php"
                class="products-add-btn"
            >
                <i class="fa-solid fa-plus"></i>
                Add Product
            </a>

        </div>

        <!-- =====================================================
             STATS
        ====================================================== -->

        <div class="products-stats">

            <div class="product-stat">

                <div class="product-stat-icon">
                    <i class="fa-solid fa-flask"></i>
                </div>

                <div class="product-stat-content">

                    <span class="product-stat-number">
                        <?= number_format((int)$stats['total_products']) ?>
                    </span>

                    <span class="product-stat-label">
                        Total Products
                    </span>

                </div>

            </div>

            <div class="product-stat">

                <div class="product-stat-icon">
                    <i class="fa-solid fa-circle-check"></i>
                </div>

                <div class="product-stat-content">

                    <span class="product-stat-number">
                        <?= number_format((int)$stats['published_products']) ?>
                    </span>

                    <span class="product-stat-label">
                        Published
                    </span>

                </div>

            </div>

            <div class="product-stat">

                <div class="product-stat-icon">
                    <i class="fa-solid fa-pen-ruler"></i>
                </div>

                <div class="product-stat-content">

                    <span class="product-stat-number">
                        <?= number_format((int)$stats['draft_products']) ?>
                    </span>

                    <span class="product-stat-label">
                        Draft
                    </span>

                </div>

            </div>

            <div class="product-stat">

                <div class="product-stat-icon">
                    <i class="fa-solid fa-ban"></i>
                </div>

                <div class="product-stat-content">

                    <span class="product-stat-number">
                        <?= number_format((int)$stats['inactive_products']) ?>
                    </span>

                    <span class="product-stat-label">
                        Inactive
                    </span>

                </div>

            </div>

            <div class="product-stat">

                <div class="product-stat-icon">
                    <i class="fa-solid fa-star"></i>
                </div>

                <div class="product-stat-content">

                    <span class="product-stat-number">
                        <?= number_format((int)$stats['featured_products']) ?>
                    </span>

                    <span class="product-stat-label">
                        Featured
                    </span>

                </div>

            </div>

        </div>

        <!-- =====================================================
             MAIN CARD
        ====================================================== -->

        <div class="products-card">

            <!-- FILTER -->

            <div class="products-filter">

                <form
                    method="GET"
                    action="products.php"
                    class="products-filter-form"
                >

                    <div class="product-search">

                        <i class="fa-solid fa-magnifying-glass"></i>

                        <input
                            type="search"
                            name="search"
                            class="product-input"
                            placeholder="Search name, product code, CAS, grade or SKU..."
                            value="<?= e($search) ?>"
                        >

                    </div>

                    <select
                        name="status"
                        class="product-select"
                    >

                        <option value="">
                            All Status
                        </option>

                        <option
                            value="published"
                            <?= $status === 'published' ? 'selected' : '' ?>
                        >
                            Published
                        </option>

                        <option
                            value="draft"
                            <?= $status === 'draft' ? 'selected' : '' ?>
                        >
                            Draft
                        </option>

                        <option
                            value="inactive"
                            <?= $status === 'inactive' ? 'selected' : '' ?>
                        >
                            Inactive
                        </option>

                    </select>

                    <select
                        name="featured"
                        class="product-select"
                    >

                        <option value="">
                            All Products
                        </option>

                        <option
                            value="1"
                            <?= $featured === '1' ? 'selected' : '' ?>
                        >
                            Featured
                        </option>

                        <option
                            value="0"
                            <?= $featured === '0' ? 'selected' : '' ?>
                        >
                            Not Featured
                        </option>

                    </select>

                    <select
                        name="sort"
                        class="product-select"
                    >

                        <option
                            value="newest"
                            <?= $sort === 'newest' ? 'selected' : '' ?>
                        >
                            Newest First
                        </option>

                        <option
                            value="oldest"
                            <?= $sort === 'oldest' ? 'selected' : '' ?>
                        >
                            Oldest First
                        </option>

                        <option
                            value="name_asc"
                            <?= $sort === 'name_asc' ? 'selected' : '' ?>
                        >
                            Name A-Z
                        </option>

                        <option
                            value="name_desc"
                            <?= $sort === 'name_desc' ? 'selected' : '' ?>
                        >
                            Name Z-A
                        </option>

                        <option
                            value="sort_asc"
                            <?= $sort === 'sort_asc' ? 'selected' : '' ?>
                        >
                            Sort Order ↑
                        </option>

                        <option
                            value="sort_desc"
                            <?= $sort === 'sort_desc' ? 'selected' : '' ?>
                        >
                            Sort Order ↓
                        </option>

                    </select>

                    <div style="
                        display:flex;
                        gap:7px;
                    ">

                        <button
                            type="submit"
                            class="filter-btn"
                        >
                            <i class="fa-solid fa-filter"></i>
                            Filter
                        </button>

                        <a
                            href="products.php"
                            class="reset-btn"
                        >
                            Reset
                        </a>

                    </div>

                </form>

            </div>

            <!-- =================================================
                 TABLE
            ================================================== -->

            <?php if (!empty($products)): ?>

                <div class="products-table-wrap">

                    <table class="products-table">

                        <thead>

                            <tr>

                                <th>
                                    Product
                                </th>

                                <th>
                                    Product Code
                                </th>

                                <th>
                                    CAS Number
                                </th>

                                <th>
                                    Grade
                                </th>

                                <th>
                                    Formula
                                </th>

                                <th>
                                    Weight
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Featured
                                </th>

                                <th>
                                    Order
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>

                        <tbody>

                        <?php foreach ($products as $product): ?>

                            <?php
                            $productId = (int)$product['id'];

                            $productStatus =
                                (string)$product['status'];

                            $isFeatured =
                                (int)$product['featured'] === 1;
                            ?>

                            <tr>

                                <!-- PRODUCT -->

                                <td class="product-name-cell">

                                    <div class="product-name-wrap">

                                        <div class="product-placeholder">

                                            <i class="fa-solid fa-flask"></i>

                                        </div>

                                        <div>

                                            <span
                                                class="product-name"
                                                title="<?= e($product['name']) ?>"
                                            >
                                                <?= e($product['name']) ?>
                                            </span>

                                            <span
                                                class="product-slug"
                                                title="<?= e($product['slug']) ?>"
                                            >
                                                /<?= e($product['slug']) ?>
                                            </span>

                                        </div>

                                    </div>

                                </td>

                                <!-- CODE -->

                                <td>

                                    <?php if (!empty($product['product_code'])): ?>

                                        <span class="product-code">
                                            <?= e($product['product_code']) ?>
                                        </span>

                                    <?php else: ?>

                                        <span class="product-muted">
                                            —
                                        </span>

                                    <?php endif; ?>

                                </td>

                                <!-- CAS -->

                                <td>

                                    <?php if (!empty($product['cas_number'])): ?>

                                        <span class="product-muted">
                                            <?= e($product['cas_number']) ?>
                                        </span>

                                    <?php else: ?>

                                        <span class="product-muted">
                                            —
                                        </span>

                                    <?php endif; ?>

                                </td>

                                <!-- GRADE -->

                                <td>

                                    <?php if (!empty($product['grade'])): ?>

                                        <span
                                            class="product-grade"
                                            title="<?= e($product['grade']) ?>"
                                        >
                                            <?= e($product['grade']) ?>
                                        </span>

                                    <?php else: ?>

                                        <span class="product-muted">
                                            —
                                        </span>

                                    <?php endif; ?>

                                </td>

                                <!-- FORMULA -->

                                <td>

                                    <?php if (!empty($product['molecular_formula'])): ?>

                                        <span class="product-muted">
                                            <?= e($product['molecular_formula']) ?>
                                        </span>

                                    <?php else: ?>

                                        <span class="product-muted">
                                            —
                                        </span>

                                    <?php endif; ?>

                                </td>

                                <!-- MOLECULAR WEIGHT -->

                                <td>

                                    <?php if (!empty($product['molecular_weight'])): ?>

                                        <span class="product-muted">
                                            <?= e($product['molecular_weight']) ?>
                                        </span>

                                    <?php else: ?>

                                        <span class="product-muted">
                                            —
                                        </span>

                                    <?php endif; ?>

                                </td>

                                <!-- STATUS -->

                                <td>

                                    <form
                                        method="POST"
                                        style="margin:0;"
                                        class="status-form"
                                    >

                                        <?php if (function_exists('csrf_field')): ?>
                                            <?= csrf_field() ?>
                                        <?php endif; ?>

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="update_status"
                                        >

                                        <input
                                            type="hidden"
                                            name="product_id"
                                            value="<?= $productId ?>"
                                        >

                                        <select
                                            name="status"
                                            class="product-select"
                                            style="
                                                width:125px;
                                                height:32px;
                                                padding:0 8px;
                                                font-size:10px;
                                                font-weight:700;
                                            "
                                            onchange="this.form.submit()"
                                        >

                                            <option
                                                value="published"
                                                <?= $productStatus === 'published' ? 'selected' : '' ?>
                                            >
                                                Published
                                            </option>

                                            <option
                                                value="draft"
                                                <?= $productStatus === 'draft' ? 'selected' : '' ?>
                                            >
                                                Draft
                                            </option>

                                            <option
                                                value="inactive"
                                                <?= $productStatus === 'inactive' ? 'selected' : '' ?>
                                            >
                                                Inactive
                                            </option>

                                        </select>

                                    </form>

                                </td>

                                <!-- FEATURED -->

                                <td>

                                    <form
                                        method="POST"
                                        style="margin:0;"
                                    >

                                        <?php if (function_exists('csrf_field')): ?>
                                            <?= csrf_field() ?>
                                        <?php endif; ?>

                                        <input
                                            type="hidden"
                                            name="action"
                                            value="toggle_featured"
                                        >

                                        <input
                                            type="hidden"
                                            name="product_id"
                                            value="<?= $productId ?>"
                                        >

                                        <button
                                            type="submit"
                                            class="featured-btn <?= $isFeatured ? 'is-featured' : '' ?>"
                                            title="<?= $isFeatured ? 'Remove Featured' : 'Mark Featured' ?>"
                                        >

                                            <i class="fa-solid fa-star"></i>

                                        </button>

                                    </form>

                                </td>

                                <!-- SORT ORDER -->

                                <td>

                                    <span class="product-muted">
                                        <?= (int)$product['sort_order'] ?>
                                    </span>

                                </td>

                                <!-- ACTIONS -->

                                <td>

                                    <div class="product-actions">

                                        <a
                                            href="product_edit.php?id=<?= $productId ?>"
                                            class="product-action"
                                            title="Edit Product"
                                        >
                                            <i class="fa-solid fa-pen"></i>
                                        </a>

                                        <a
                                            href="product_view.php?id=<?= $productId ?>"
                                            class="product-action"
                                            title="View Product"
                                        >
                                            <i class="fa-solid fa-eye"></i>
                                        </a>

                                        <form
                                            method="POST"
                                            style="margin:0;"
                                            onsubmit="return confirmDelete('<?= e(addslashes($product['name'])) ?>');"
                                        >

                                            <?php if (function_exists('csrf_field')): ?>
                                                <?= csrf_field() ?>
                                            <?php endif; ?>

                                            <input
                                                type="hidden"
                                                name="action"
                                                value="delete_product"
                                            >

                                            <input
                                                type="hidden"
                                                name="product_id"
                                                value="<?= $productId ?>"
                                            >

                                            <button
                                                type="submit"
                                                class="product-action delete"
                                                title="Delete Product"
                                            >
                                                <i class="fa-solid fa-trash"></i>
                                            </button>

                                        </form>

                                    </div>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

                <!-- =================================================
                     PAGINATION
                ================================================== -->

                <div class="products-pagination">

                    <div class="pagination-info">

                        Showing
                        <strong>
                            <?= $totalFiltered > 0
                                ? (($page - 1) * $perPage + 1)
                                : 0
                            ?>
                        </strong>

                        -
                        <strong>
                            <?= min($page * $perPage, $totalFiltered) ?>
                        </strong>

                        of
                        <strong>
                            <?= number_format($totalFiltered) ?>
                        </strong>
                        products

                    </div>

                    <?php if ($totalPages > 1): ?>

                        <div class="pagination-links">

                            <?php if ($page > 1): ?>

                                <a
                                    href="<?= e(buildProductUrl(['page' => $page - 1])) ?>"
                                    class="pagination-link"
                                >
                                    <i class="fa-solid fa-chevron-left"></i>
                                </a>

                            <?php endif; ?>

                            <?php

                            $startPage = max(1, $page - 2);
                            $endPage   = min($totalPages, $page + 2);

                            for ($i = $startPage; $i <= $endPage; $i++):
                            ?>

                                <a
                                    href="<?= e(buildProductUrl(['page' => $i])) ?>"
                                    class="pagination-link <?= $i === $page ? 'active' : '' ?>"
                                >
                                    <?= $i ?>
                                </a>

                            <?php endfor; ?>

                            <?php if ($page < $totalPages): ?>

                                <a
                                    href="<?= e(buildProductUrl(['page' => $page + 1])) ?>"
                                    class="pagination-link"
                                >
                                    <i class="fa-solid fa-chevron-right"></i>
                                </a>

                            <?php endif; ?>

                        </div>

                    <?php endif; ?>

                </div>

            <?php else: ?>

                <!-- =================================================
                     EMPTY
                ================================================== -->

                <div class="products-empty">

                    <div class="products-empty-icon">

                        <i class="fa-solid fa-flask"></i>

                    </div>

                    <h3>
                        No products found
                    </h3>

                    <p>

                        <?php if ($search !== '' || $status !== '' || $featured !== ''): ?>

                            No products match your current filters.
                            Try changing the search or filters.

                        <?php else: ?>

                            You haven't added any products yet.
                            Start by creating your first chemical product.

                        <?php endif; ?>

                    </p>

                    <?php if ($search !== '' || $status !== '' || $featured !== ''): ?>

                        <a
                            href="products.php"
                            class="products-add-btn"
                            style="display:inline-flex;"
                        >
                            <i class="fa-solid fa-rotate-left"></i>
                            Clear Filters
                        </a>

                    <?php else: ?>

                        <a
                            href="product_add.php"
                            class="products-add-btn"
                            style="display:inline-flex;"
                        >
                            <i class="fa-solid fa-plus"></i>
                            Add First Product
                        </a>

                    <?php endif; ?>

                </div>

            <?php endif; ?>

        </div>

    </div>

</div>

<?php if (isset($_GET['deleted'])): ?>

    <div class="products-toast" id="productToast">

        <i class="fa-solid fa-circle-check"></i>

        <span>
            Product deleted successfully.
        </span>

    </div>

<?php elseif (isset($_GET['updated'])): ?>

    <div class="products-toast" id="productToast">

        <i class="fa-solid fa-circle-check"></i>

        <span>
            Product updated successfully.
        </span>

    </div>

<?php endif; ?>

<script>
function confirmDelete(productName) {

    return confirm(
        'Are you sure you want to delete "' +
        productName +
        '"?\n\nThis action cannot be undone.'
    );
}

document.addEventListener('DOMContentLoaded', function () {

    const toast = document.getElementById('productToast');

    if (toast) {

        setTimeout(function () {

            toast.style.transition =
                'opacity .3s ease, transform .3s ease';

            toast.style.opacity = '0';
            toast.style.transform = 'translateY(8px)';

            setTimeout(function () {
                toast.remove();
            }, 350);

        }, 3000);
    }

    /*
     * Prevent accidental duplicate submit
     */
    document.querySelectorAll('.status-form').forEach(function (form) {

        form.addEventListener('submit', function () {

            const select = form.querySelector('select');

            if (select) {
                select.disabled = true;
                select.style.opacity = '.6';
            }

        });

    });

});
</script>

<?php
require_once __DIR__ . '/footer.php';
?>