<?php
/**
 * Pure Chemical
 * Product Status Management
 *
 * File:
 * admin/product_status.php
 *
 * Existing table used:
 * products
 *
 * Existing status values:
 * draft
 * published
 * inactive
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}


/* =========================================================
   DATABASE
========================================================= */

require_once __DIR__ . '/includes/db.php';


/* =========================================================
   OPTIONAL AUTH / FUNCTIONS / CSRF
========================================================= */

$authFile = __DIR__ . '/includes/auth.php';
$functionsFile = __DIR__ . '/includes/functions.php';
$csrfFile = __DIR__ . '/includes/csrf.php';

if (file_exists($authFile)) {
    require_once $authFile;
}

if (file_exists($functionsFile)) {
    require_once $functionsFile;
}

if (file_exists($csrfFile)) {
    require_once $csrfFile;
}


/* =========================================================
   FALLBACK HELPERS
========================================================= */

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars(
            (string)$value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}


if (!function_exists('requireAdmin')) {
    function requireAdmin()
    {
        if (
            empty($_SESSION['admin_id']) &&
            empty($_SESSION['admin_logged_in'])
        ) {
            header('Location: login.php');
            exit;
        }
    }
}


if (!function_exists('csrf_token')) {
    function csrf_token()
    {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] =
                bin2hex(random_bytes(32));
        }

        return $_SESSION['csrf_token'];
    }
}


if (!function_exists('csrf_field')) {
    function csrf_field()
    {
        return
            '<input type="hidden" name="csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}


if (!function_exists('csrf_verify')) {
    function csrf_verify()
    {
        $token = $_POST['csrf_token'] ?? '';

        return
            !empty($_SESSION['csrf_token']) &&
            hash_equals(
                $_SESSION['csrf_token'],
                $token
            );
    }
}


if (!function_exists('redirectWithMessage')) {
    function redirectWithMessage(
        $type,
        $message,
        $extra = []
    ) {
        $params = array_merge(
            [
                'message_type' => $type,
                'message' => $message
            ],
            $extra
        );

        header(
            'Location: product_status.php?' .
            http_build_query($params)
        );

        exit;
    }
}


/* =========================================================
   AUTH
========================================================= */

requireAdmin();


/* =========================================================
   PAGE CONFIG
========================================================= */

$page_title = 'Product Status';
$active_menu = 'product_status';


/* =========================================================
   ALLOWED STATUS
========================================================= */

$allowedStatuses = [
    'draft',
    'published',
    'inactive'
];


/* =========================================================
   FLASH MESSAGE
========================================================= */

$message = $_GET['message'] ?? '';
$messageType = $_GET['message_type'] ?? '';


/* =========================================================
   STATUS UPDATE
========================================================= */

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['update_status'])
) {

    if (!csrf_verify()) {

        redirectWithMessage(
            'error',
            'Invalid security token. Please try again.'
        );
    }


    $productId =
        (int)($_POST['product_id'] ?? 0);

    $newStatus =
        trim($_POST['status'] ?? '');


    if ($productId <= 0) {

        redirectWithMessage(
            'error',
            'Invalid product selected.'
        );
    }


    if (!in_array(
        $newStatus,
        $allowedStatuses,
        true
    )) {

        redirectWithMessage(
            'error',
            'Invalid product status.'
        );
    }


    try {

        $check = $pdo->prepare("
            SELECT
                id,
                name,
                status
            FROM products
            WHERE id = ?
            LIMIT 1
        ");

        $check->execute([
            $productId
        ]);

        $product = $check->fetch();

        if (!$product) {

            redirectWithMessage(
                'error',
                'Product not found.'
            );
        }


        /*
         * Published date handling:
         *
         * If product is being published for the first time,
         * published_at will be set automatically.
         *
         * If moving away from published,
         * existing published_at is retained.
         */

        if ($newStatus === 'published') {

            $update = $pdo->prepare("
                UPDATE products
                SET
                    status = 'published',
                    published_at =
                        CASE
                            WHEN published_at IS NULL
                            THEN NOW()
                            ELSE published_at
                        END,
                    updated_at = CURRENT_TIMESTAMP
                WHERE id = ?
                LIMIT 1
            ");

            $update->execute([
                $productId
            ]);

        } else {

            $update = $pdo->prepare("
                UPDATE products
                SET
                    status = ?,
                    updated_at = CURRENT_TIMESTAMP
                WHERE id = ?
                LIMIT 1
            ");

            $update->execute([
                $newStatus,
                $productId
            ]);
        }


        redirectWithMessage(
            'success',
            'Product status updated successfully.'
        );

    } catch (Throwable $e) {

        error_log(
            'Product Status Update Error: ' .
            $e->getMessage()
        );

        redirectWithMessage(
            'error',
            'Unable to update product status.'
        );
    }
}


/* =========================================================
   FEATURED TOGGLE
========================================================= */

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['toggle_featured'])
) {

    if (!csrf_verify()) {

        redirectWithMessage(
            'error',
            'Invalid security token.'
        );
    }


    $productId =
        (int)($_POST['product_id'] ?? 0);


    if ($productId <= 0) {

        redirectWithMessage(
            'error',
            'Invalid product.'
        );
    }


    try {

        $stmt = $pdo->prepare("
            UPDATE products
            SET
                featured =
                    CASE
                        WHEN featured = 1
                        THEN 0
                        ELSE 1
                    END,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $productId
        ]);


        redirectWithMessage(
            'success',
            'Featured status updated.'
        );

    } catch (Throwable $e) {

        error_log(
            'Product Featured Toggle Error: ' .
            $e->getMessage()
        );

        redirectWithMessage(
            'error',
            'Unable to update featured status.'
        );
    }
}


/* =========================================================
   BULK STATUS UPDATE
========================================================= */

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['bulk_update'])
) {

    if (!csrf_verify()) {

        redirectWithMessage(
            'error',
            'Invalid security token.'
        );
    }


    $bulkStatus =
        trim($_POST['bulk_status'] ?? '');

    $productIds =
        $_POST['product_ids'] ?? [];


    if (!in_array(
        $bulkStatus,
        $allowedStatuses,
        true
    )) {

        redirectWithMessage(
            'error',
            'Please select a valid status.'
        );
    }


    if (
        !is_array($productIds) ||
        empty($productIds)
    ) {

        redirectWithMessage(
            'error',
            'Please select at least one product.'
        );
    }


    $cleanIds = [];

    foreach ($productIds as $id) {

        $id = (int)$id;

        if ($id > 0) {
            $cleanIds[] = $id;
        }
    }


    $cleanIds =
        array_values(
            array_unique($cleanIds)
        );


    if (empty($cleanIds)) {

        redirectWithMessage(
            'error',
            'No valid products selected.'
        );
    }


    try {

        $pdo->beginTransaction();


        foreach ($cleanIds as $id) {

            if ($bulkStatus === 'published') {

                $stmt = $pdo->prepare("
                    UPDATE products
                    SET
                        status = 'published',
                        published_at =
                            CASE
                                WHEN published_at IS NULL
                                THEN NOW()
                                ELSE published_at
                            END,
                        updated_at = CURRENT_TIMESTAMP
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $id
                ]);

            } else {

                $stmt = $pdo->prepare("
                    UPDATE products
                    SET
                        status = ?,
                        updated_at = CURRENT_TIMESTAMP
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $bulkStatus,
                    $id
                ]);
            }
        }


        $pdo->commit();


        redirectWithMessage(
            'success',
            count($cleanIds) .
            ' product(s) updated successfully.'
        );

    } catch (Throwable $e) {

        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        error_log(
            'Bulk Product Status Error: ' .
            $e->getMessage()
        );

        redirectWithMessage(
            'error',
            'Unable to update selected products.'
        );
    }
}


/* =========================================================
   FILTERS
========================================================= */

$search =
    trim($_GET['search'] ?? '');

$statusFilter =
    trim($_GET['status'] ?? '');

$featuredFilter =
    $_GET['featured'] ?? '';

$page =
    max(
        1,
        (int)($_GET['page'] ?? 1)
    );

$perPage = 15;


/* =========================================================
   BUILD WHERE
========================================================= */

$where = [
    '1 = 1'
];

$params = [];


/* Search */

if ($search !== '') {

    $where[] = "
        (
            p.name LIKE ?
            OR p.slug LIKE ?
            OR p.product_code LIKE ?
            OR p.cas_number LIKE ?
            OR p.sku LIKE ?
        )
    ";

    $searchValue =
        '%' . $search . '%';

    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;
}


/* Status */

if (
    $statusFilter !== '' &&
    in_array(
        $statusFilter,
        $allowedStatuses,
        true
    )
) {

    $where[] = 'p.status = ?';

    $params[] =
        $statusFilter;
}


/* Featured */

if ($featuredFilter !== '') {

    if ($featuredFilter === '1') {

        $where[] =
            'p.featured = 1';

    } elseif ($featuredFilter === '0') {

        $where[] =
            'p.featured = 0';
    }
}


$whereSql =
    implode(
        ' AND ',
        $where
    );


/* =========================================================
   TOTAL RECORDS
========================================================= */

$countStmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM products p
    WHERE {$whereSql}
");

$countStmt->execute(
    $params
);

$totalRecords =
    (int)$countStmt->fetchColumn();


$totalPages =
    max(
        1,
        (int)ceil(
            $totalRecords /
            $perPage
        )
    );


if ($page > $totalPages) {
    $page = $totalPages;
}


$offset =
    ($page - 1) *
    $perPage;


/* =========================================================
   PRODUCT LIST
========================================================= */

$listStmt = $pdo->prepare("
    SELECT
        p.id,
        p.name,
        p.slug,
        p.product_code,
        p.cas_number,
        p.grade,
        p.sku,
        p.status,
        p.featured,
        p.published_at,
        p.created_at,
        p.updated_at
    FROM products p
    WHERE {$whereSql}
    ORDER BY
        CASE p.status
            WHEN 'published' THEN 1
            WHEN 'draft' THEN 2
            WHEN 'inactive' THEN 3
            ELSE 4
        END,
        p.sort_order ASC,
        p.name ASC
    LIMIT {$perPage}
    OFFSET {$offset}
");

$listStmt->execute(
    $params
);

$products =
    $listStmt->fetchAll();


/* =========================================================
   STATS
========================================================= */

$totalProducts =
    (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM products
        ")
        ->fetchColumn();


$publishedProducts =
    (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM products
            WHERE status = 'published'
        ")
        ->fetchColumn();


$draftProducts =
    (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM products
            WHERE status = 'draft'
        ")
        ->fetchColumn();


$inactiveProducts =
    (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM products
            WHERE status = 'inactive'
        ")
        ->fetchColumn();


$featuredProducts =
    (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM products
            WHERE featured = 1
        ")
        ->fetchColumn();


/* =========================================================
   HELPERS
========================================================= */

function statusLabel($status)
{
    switch ($status) {

        case 'published':
            return 'Published';

        case 'inactive':
            return 'Inactive';

        default:
            return 'Draft';
    }
}


function statusClass($status)
{
    switch ($status) {

        case 'published':
            return 'status-published';

        case 'inactive':
            return 'status-inactive';

        default:
            return 'status-draft';
    }
}


function statusIcon($status)
{
    switch ($status) {

        case 'published':
            return 'fa-circle-check';

        case 'inactive':
            return 'fa-circle-pause';

        default:
            return 'fa-file-pen';
    }
}


function paginationUrl($page)
{
    $query = $_GET;

    $query['page'] =
        $page;

    return '?' .
        http_build_query(
            $query
        );
}


/* =========================================================
   HEADER
========================================================= */

$headerFile =
    __DIR__ .
    '/includes/header.php';

if (!file_exists($headerFile)) {

    $headerFile =
        __DIR__ .
        '/header.php';
}

if (file_exists($headerFile)) {
    require_once $headerFile;
}

?>

<style>

/* =========================================================
   PRODUCT STATUS
   PREMIUM MODERN ADMIN UI
========================================================= */

:root {

    --ps-primary: #2563eb;
    --ps-primary-dark: #1d4ed8;
    --ps-purple: #7c3aed;

    --ps-success: #059669;
    --ps-warning: #d97706;
    --ps-danger: #dc2626;

    --ps-text: #0f172a;
    --ps-muted: #64748b;

    --ps-border: #e2e8f0;
    --ps-bg: #f8fafc;
    --ps-card: #ffffff;

    --ps-radius: 18px;

    --ps-shadow:
        0 10px 35px
        rgba(15, 23, 42, .07);
}


.product-status-page {

    padding: 24px;

    max-width: 1750px;

    margin: 0 auto;
}


.product-status-page *,
.product-status-page *::before,
.product-status-page *::after {

    box-sizing: border-box;
}


.product-status-page a {

    text-decoration: none;
}


/* =========================================================
   HERO
========================================================= */

.ps-hero {

    display: flex;

    align-items: flex-start;

    justify-content: space-between;

    gap: 20px;

    margin-bottom: 24px;
}


.ps-eyebrow {

    display: inline-flex;

    align-items: center;

    gap: 8px;

    color: var(--ps-primary);

    font-size: 11px;

    font-weight: 850;

    letter-spacing: .08em;

    text-transform: uppercase;

    margin-bottom: 8px;
}


.ps-title {

    margin: 0;

    color: var(--ps-text);

    font-size: 30px;

    line-height: 1.15;

    font-weight: 850;

    letter-spacing: -.035em;
}


.ps-subtitle {

    margin: 9px 0 0;

    max-width: 760px;

    color: var(--ps-muted);

    font-size: 14px;

    line-height: 1.7;
}


.ps-hero-actions {

    display: flex;

    gap: 9px;

    flex-wrap: wrap;
}


/* =========================================================
   BUTTONS
========================================================= */

.ps-btn {

    min-height: 43px;

    padding: 0 15px;

    border-radius: 11px;

    border: 1px solid transparent;

    display: inline-flex;

    align-items: center;

    justify-content: center;

    gap: 8px;

    font-family: inherit;

    font-size: 12px;

    font-weight: 800;

    cursor: pointer;

    transition: .2s ease;
}


.ps-btn:hover {

    transform: translateY(-1px);
}


.ps-btn-primary {

    color: #fff;

    background:
        linear-gradient(
            135deg,
            var(--ps-primary),
            var(--ps-purple)
        );

    box-shadow:
        0 8px 20px
        rgba(37, 99, 235, .20);
}


.ps-btn-light {

    color: var(--ps-text);

    background: #fff;

    border-color: var(--ps-border);
}


.ps-btn-danger {

    color: var(--ps-danger);

    background: #fef2f2;

    border-color: #fecaca;
}


/* =========================================================
   ALERT
========================================================= */

.ps-alert {

    padding: 13px 16px;

    border-radius: 13px;

    display: flex;

    align-items: center;

    gap: 10px;

    margin-bottom: 20px;

    font-size: 12px;

    font-weight: 750;
}


.ps-alert-success {

    color: #047857;

    background: #ecfdf5;

    border: 1px solid #a7f3d0;
}


.ps-alert-error {

    color: #b91c1c;

    background: #fef2f2;

    border: 1px solid #fecaca;
}


/* =========================================================
   STATS
========================================================= */

.ps-stats {

    display: grid;

    grid-template-columns:
        repeat(
            5,
            minmax(0, 1fr)
        );

    gap: 15px;

    margin-bottom: 22px;
}


.ps-stat {

    background: var(--ps-card);

    border: 1px solid var(--ps-border);

    border-radius: var(--ps-radius);

    padding: 18px;

    box-shadow: var(--ps-shadow);

    position: relative;

    overflow: hidden;
}


.ps-stat::after {

    content: "";

    position: absolute;

    width: 90px;

    height: 90px;

    border-radius: 50%;

    right: -38px;

    top: -38px;

    background:
        rgba(37, 99, 235, .055);
}


.ps-stat-top {

    display: flex;

    align-items: center;

    justify-content: space-between;
}


.ps-stat-label {

    color: var(--ps-muted);

    font-size: 11px;

    font-weight: 750;
}


.ps-stat-icon {

    width: 40px;

    height: 40px;

    border-radius: 12px;

    display: grid;

    place-items: center;

    color: var(--ps-primary);

    background: #eff6ff;
}


.ps-stat-value {

    margin-top: 11px;

    color: var(--ps-text);

    font-size: 24px;

    font-weight: 900;

    letter-spacing: -.02em;
}


/* =========================================================
   MAIN CARD
========================================================= */

.ps-card {

    background: var(--ps-card);

    border: 1px solid var(--ps-border);

    border-radius: var(--ps-radius);

    box-shadow: var(--ps-shadow);

    overflow: hidden;
}


.ps-card-head {

    padding: 19px 21px;

    display: flex;

    align-items: center;

    justify-content: space-between;

    gap: 15px;

    border-bottom:
        1px solid
        var(--ps-border);
}


.ps-card-title {

    margin: 0;

    color: var(--ps-text);

    font-size: 16px;

    font-weight: 850;
}


.ps-card-desc {

    margin: 4px 0 0;

    color: var(--ps-muted);

    font-size: 11px;
}


/* =========================================================
   FILTER
========================================================= */

.ps-filter {

    padding: 16px;

    background: #f8fafc;

    border-bottom:
        1px solid
        var(--ps-border);
}


.ps-filter-form {

    display: grid;

    grid-template-columns:
        minmax(240px, 1.6fr)
        minmax(160px, .7fr)
        minmax(160px, .7fr)
        auto
        auto;

    gap: 9px;
}


.ps-input,
.ps-select {

    width: 100%;

    height: 43px;

    padding: 0 12px;

    border-radius: 11px;

    border:
        1px solid
        #dbe3ee;

    background: #fff;

    color: var(--ps-text);

    font-family: inherit;

    font-size: 12px;

    outline: none;

    transition: .2s ease;
}


.ps-input:focus,
.ps-select:focus {

    border-color:
        rgba(37, 99, 235, .65);

    box-shadow:
        0 0 0 4px
        rgba(37, 99, 235, .08);
}


.ps-search {

    position: relative;
}


.ps-search i {

    position: absolute;

    left: 13px;

    top: 50%;

    transform:
        translateY(-50%);

    color: #94a3b8;
}


.ps-search .ps-input {

    padding-left: 37px;
}


/* =========================================================
   BULK BAR
========================================================= */

.ps-bulk-bar {

    display: none;

    align-items: center;

    justify-content: space-between;

    gap: 12px;

    padding: 11px 16px;

    background: #eff6ff;

    border-bottom:
        1px solid
        #bfdbfe;
}


.ps-bulk-bar.show {

    display: flex;
}


.ps-selected-text {

    color: #1d4ed8;

    font-size: 12px;

    font-weight: 800;
}


.ps-bulk-controls {

    display: flex;

    gap: 8px;

    align-items: center;
}


.ps-bulk-select {

    height: 36px;

    padding: 0 10px;

    border-radius: 9px;

    border:
        1px solid
        #bfdbfe;

    background: #fff;

    color: #1e3a8a;

    font-size: 11px;

    font-weight: 700;
}


/* =========================================================
   TABLE
========================================================= */

.ps-table-wrap {

    overflow-x: auto;
}


.ps-table {

    width: 100%;

    min-width: 1250px;

    border-collapse: collapse;
}


.ps-table th {

    padding: 12px 15px;

    background: #f8fafc;

    border-bottom:
        1px solid
        var(--ps-border);

    color: #64748b;

    text-align: left;

    text-transform: uppercase;

    letter-spacing: .055em;

    font-size: 9px;

    font-weight: 900;

    white-space: nowrap;
}


.ps-table td {

    padding: 14px 15px;

    border-bottom:
        1px solid
        #eef2f7;

    vertical-align: middle;
}


.ps-table tbody tr {

    transition: .18s ease;
}


.ps-table tbody tr:hover {

    background: #fafcff;
}


/* =========================================================
   CHECKBOX
========================================================= */

.ps-checkbox {

    width: 16px;

    height: 16px;

    accent-color:
        var(--ps-primary);

    cursor: pointer;
}


/* =========================================================
   PRODUCT
========================================================= */

.ps-product {

    display: flex;

    flex-direction: column;

    gap: 3px;
}


.ps-product-name {

    color: var(--ps-text);

    font-size: 13px;

    font-weight: 850;
}


.ps-product-slug {

    color: #94a3b8;

    font-size: 10px;
}


.ps-product-code {

    display: inline-flex;

    width: fit-content;

    padding: 4px 7px;

    margin-top: 2px;

    border-radius: 6px;

    background: #f1f5f9;

    color: #475569;

    font-size: 9px;

    font-weight: 800;
}


/* =========================================================
   STATUS BADGE
========================================================= */

.ps-status {

    display: inline-flex;

    align-items: center;

    gap: 7px;

    padding: 7px 10px;

    border-radius: 999px;

    font-size: 10px;

    font-weight: 850;

    white-space: nowrap;
}


.ps-status-dot {

    width: 6px;

    height: 6px;

    border-radius: 50%;

    background:
        currentColor;
}


.status-published {

    color: #047857;

    background: #ecfdf5;
}


.status-draft {

    color: #b45309;

    background: #fffbeb;
}


.status-inactive {

    color: #b91c1c;

    background: #fef2f2;
}


/* =========================================================
   QUICK STATUS
========================================================= */

.ps-status-form {

    display: flex;

    align-items: center;

    gap: 6px;
}


.ps-status-select {

    height: 34px;

    min-width: 112px;

    padding: 0 8px;

    border:
        1px solid
        var(--ps-border);

    border-radius: 8px;

    background: #fff;

    color: var(--ps-text);

    font-size: 10px;

    font-weight: 700;

    outline: none;
}


.ps-status-save {

    width: 34px;

    height: 34px;

    border-radius: 8px;

    border:
        1px solid
        #bfdbfe;

    background: #eff6ff;

    color: var(--ps-primary);

    cursor: pointer;
}


.ps-status-save:hover {

    background: var(--ps-primary);

    color: #fff;
}


/* =========================================================
   FEATURED
========================================================= */

.ps-featured-btn {

    border: 0;

    background: transparent;

    cursor: pointer;

    padding: 4px;

    color: #cbd5e1;

    font-size: 17px;

    transition: .2s ease;
}


.ps-featured-btn:hover {

    transform: scale(1.08);

    color: #f59e0b;
}


.ps-featured-btn.active {

    color: #f59e0b;
}


/* =========================================================
   PRODUCT META
========================================================= */

.ps-meta-list {

    display: flex;

    flex-direction: column;

    gap: 4px;
}


.ps-meta-row {

    display: flex;

    gap: 6px;

    align-items: center;

    color: #64748b;

    font-size: 10px;
}


.ps-meta-label {

    color: #94a3b8;

    font-weight: 700;
}


/* =========================================================
   ACTIONS
========================================================= */

.ps-actions {

    display: flex;

    align-items: center;

    gap: 6px;
}


.ps-icon-btn {

    width: 34px;

    height: 34px;

    border-radius: 9px;

    border:
        1px solid
        var(--ps-border);

    background: #fff;

    display: grid;

    place-items: center;

    color: #475569;

    cursor: pointer;

    transition: .2s ease;
}


.ps-icon-btn:hover {

    color: var(--ps-primary);

    background: #eff6ff;

    border-color: #bfdbfe;
}


/* =========================================================
   EMPTY
========================================================= */

.ps-empty {

    padding: 65px 25px;

    text-align: center;
}


.ps-empty-icon {

    width: 58px;

    height: 58px;

    margin:
        0 auto 15px;

    border-radius: 17px;

    display: grid;

    place-items: center;

    background: #eff6ff;

    color: var(--ps-primary);

    font-size: 22px;
}


.ps-empty h3 {

    margin: 0;

    color: var(--ps-text);

    font-size: 17px;

    font-weight: 850;
}


.ps-empty p {

    max-width: 450px;

    margin: 7px auto 0;

    color: var(--ps-muted);

    font-size: 12px;

    line-height: 1.6;
}


/* =========================================================
   PAGINATION
========================================================= */

.ps-pagination {

    padding: 15px 18px;

    border-top:
        1px solid
        var(--ps-border);

    display: flex;

    align-items: center;

    justify-content: space-between;

    gap: 15px;
}


.ps-pagination-info {

    color: var(--ps-muted);

    font-size: 11px;
}


.ps-pagination-links {

    display: flex;

    gap: 5px;

    align-items: center;
}


.ps-page-link {

    min-width: 33px;

    height: 33px;

    padding: 0 8px;

    border-radius: 8px;

    border:
        1px solid
        var(--ps-border);

    background: #fff;

    display: grid;

    place-items: center;

    color: #475569;

    font-size: 10px;

    font-weight: 800;
}


.ps-page-link:hover,
.ps-page-link.active {

    color: #fff;

    background:
        var(--ps-primary);

    border-color:
        var(--ps-primary);
}


/* =========================================================
   RESPONSIVE
========================================================= */

@media (max-width: 1350px) {

    .ps-stats {

        grid-template-columns:
            repeat(
                3,
                minmax(0, 1fr)
            );
    }


    .ps-filter-form {

        grid-template-columns:
            1fr 1fr 1fr;
    }

}


@media (max-width: 950px) {

    .product-status-page {

        padding: 16px;
    }


    .ps-hero {

        flex-direction: column;
    }


    .ps-filter-form {

        grid-template-columns:
            1fr 1fr;
    }

}


@media (max-width: 650px) {

    .ps-stats {

        grid-template-columns: 1fr;
    }


    .ps-filter-form {

        grid-template-columns: 1fr;
    }


    .ps-title {

        font-size: 24px;
    }


    .ps-pagination {

        flex-direction: column;

        align-items: flex-start;
    }


    .ps-bulk-bar {

        flex-direction: column;

        align-items: flex-start;
    }

}

</style>


<div class="product-status-page">

    <!-- =====================================================
         HERO
    ====================================================== -->

    <div class="ps-hero">

        <div>

            <div class="ps-eyebrow">

                <i class="fa-solid fa-toggle-on"></i>

                Product Management

            </div>


            <h1 class="ps-title">
                Product Status
            </h1>


            <p class="ps-subtitle">
                Manage product publishing status, featured
                visibility and activation state from one
                centralized control panel.
            </p>

        </div>


        <div class="ps-hero-actions">

            <a
                href="product_status.php"
                class="ps-btn ps-btn-light"
            >

                <i class="fa-solid fa-rotate"></i>

                Refresh

            </a>

        </div>

    </div>


    <!-- =====================================================
         ALERT
    ====================================================== -->

    <?php if ($message !== ''): ?>

        <div
            class="ps-alert
            <?php echo $messageType === 'success'
                ? 'ps-alert-success'
                : 'ps-alert-error'; ?>"
        >

            <i
                class="fa-solid
                <?php echo $messageType === 'success'
                    ? 'fa-circle-check'
                    : 'fa-circle-exclamation'; ?>"
            ></i>

            <?php echo e($message); ?>

        </div>

    <?php endif; ?>


    <!-- =====================================================
         STATS
    ====================================================== -->

    <div class="ps-stats">


        <!-- TOTAL -->

        <div class="ps-stat">

            <div class="ps-stat-top">

                <div class="ps-stat-label">
                    Total Products
                </div>

                <div class="ps-stat-icon">
                    <i class="fa-solid fa-boxes-stacked"></i>
                </div>

            </div>

            <div class="ps-stat-value">
                <?php echo number_format(
                    $totalProducts
                ); ?>
            </div>

        </div>


        <!-- PUBLISHED -->

        <div class="ps-stat">

            <div class="ps-stat-top">

                <div class="ps-stat-label">
                    Published
                </div>

                <div
                    class="ps-stat-icon"
                    style="
                        color:#059669;
                        background:#ecfdf5;
                    "
                >
                    <i class="fa-solid fa-circle-check"></i>
                </div>

            </div>

            <div class="ps-stat-value">
                <?php echo number_format(
                    $publishedProducts
                ); ?>
            </div>

        </div>


        <!-- DRAFT -->

        <div class="ps-stat">

            <div class="ps-stat-top">

                <div class="ps-stat-label">
                    Draft
                </div>

                <div
                    class="ps-stat-icon"
                    style="
                        color:#d97706;
                        background:#fffbeb;
                    "
                >
                    <i class="fa-solid fa-file-pen"></i>
                </div>

            </div>

            <div class="ps-stat-value">
                <?php echo number_format(
                    $draftProducts
                ); ?>
            </div>

        </div>


        <!-- INACTIVE -->

        <div class="ps-stat">

            <div class="ps-stat-top">

                <div class="ps-stat-label">
                    Inactive
                </div>

                <div
                    class="ps-stat-icon"
                    style="
                        color:#dc2626;
                        background:#fef2f2;
                    "
                >
                    <i class="fa-solid fa-circle-pause"></i>
                </div>

            </div>

            <div class="ps-stat-value">
                <?php echo number_format(
                    $inactiveProducts
                ); ?>
            </div>

        </div>


        <!-- FEATURED -->

        <div class="ps-stat">

            <div class="ps-stat-top">

                <div class="ps-stat-label">
                    Featured
                </div>

                <div
                    class="ps-stat-icon"
                    style="
                        color:#f59e0b;
                        background:#fffbeb;
                    "
                >
                    <i class="fa-solid fa-star"></i>
                </div>

            </div>

            <div class="ps-stat-value">
                <?php echo number_format(
                    $featuredProducts
                ); ?>
            </div>

        </div>

    </div>


    <!-- =====================================================
         PRODUCT TABLE
    ====================================================== -->

    <div class="ps-card">


        <!-- HEADER -->

        <div class="ps-card-head">

            <div>

                <h2 class="ps-card-title">
                    Product Status Control
                </h2>

                <p class="ps-card-desc">
                    Update product status and featured visibility.
                </p>

            </div>


            <div
                style="
                    color:#64748b;
                    font-size:11px;
                    font-weight:750;
                "
            >

                <?php echo number_format(
                    $totalRecords
                ); ?>

                Result(s)

            </div>

        </div>


        <!-- =================================================
             FILTER
        ================================================== -->

        <div class="ps-filter">

            <form
                method="get"
                class="ps-filter-form"
            >


                <div class="ps-search">

                    <i
                        class="fa-solid fa-magnifying-glass"
                    ></i>

                    <input
                        type="search"
                        name="search"
                        class="ps-input"
                        value="<?php echo e(
                            $search
                        ); ?>"
                        placeholder="Search product, code, CAS, SKU or slug..."
                    >

                </div>


                <select
                    name="status"
                    class="ps-select"
                >

                    <option value="">
                        All Status
                    </option>

                    <option
                        value="published"
                        <?php echo $statusFilter === 'published'
                            ? 'selected'
                            : ''; ?>
                    >
                        Published
                    </option>

                    <option
                        value="draft"
                        <?php echo $statusFilter === 'draft'
                            ? 'selected'
                            : ''; ?>
                    >
                        Draft
                    </option>

                    <option
                        value="inactive"
                        <?php echo $statusFilter === 'inactive'
                            ? 'selected'
                            : ''; ?>
                    >
                        Inactive
                    </option>

                </select>


                <select
                    name="featured"
                    class="ps-select"
                >

                    <option value="">
                        All Featured
                    </option>

                    <option
                        value="1"
                        <?php echo $featuredFilter === '1'
                            ? 'selected'
                            : ''; ?>
                    >
                        Featured
                    </option>

                    <option
                        value="0"
                        <?php echo $featuredFilter === '0'
                            ? 'selected'
                            : ''; ?>
                    >
                        Not Featured
                    </option>

                </select>


                <button
                    type="submit"
                    class="ps-btn ps-btn-primary"
                >

                    <i class="fa-solid fa-filter"></i>

                    Filter

                </button>


                <a
                    href="product_status.php"
                    class="ps-btn ps-btn-light"
                >

                    Reset

                </a>

            </form>

        </div>


        <!-- =================================================
             BULK BAR
        ================================================== -->

        <div
            id="bulkBar"
            class="ps-bulk-bar"
        >

            <div class="ps-selected-text">

                <i class="fa-solid fa-check-double"></i>

                <span id="selectedCount">
                    0
                </span>

                product(s) selected

            </div>


            <div class="ps-bulk-controls">

                <select
                    id="bulkStatus"
                    class="ps-bulk-select"
                >

                    <option value="">
                        Change Status
                    </option>

                    <option value="published">
                        Published
                    </option>

                    <option value="draft">
                        Draft
                    </option>

                    <option value="inactive">
                        Inactive
                    </option>

                </select>


                <button
                    type="button"
                    id="bulkUpdateBtn"
                    class="ps-btn ps-btn-primary"
                    style="min-height:36px;"
                >

                    <i class="fa-solid fa-layer-group"></i>

                    Apply

                </button>

            </div>

        </div>


        <!-- =================================================
             TABLE
        ================================================== -->

        <?php if (empty($products)): ?>

            <div class="ps-empty">

                <div class="ps-empty-icon">

                    <i
                        class="fa-solid fa-box-open"
                    ></i>

                </div>


                <h3>
                    No Products Found
                </h3>


                <p>
                    There are no products matching your
                    current search or filter.
                </p>

            </div>

        <?php else: ?>


            <form
                method="post"
                id="bulkForm"
            >

                <?php echo csrf_field(); ?>


                <input
                    type="hidden"
                    name="bulk_update"
                    value="1"
                >


                <input
                    type="hidden"
                    name="bulk_status"
                    id="bulkStatusHidden"
                    value=""
                >


                <div class="ps-table-wrap">

                    <table class="ps-table">

                        <thead>

                            <tr>

                                <th style="width:42px;">

                                    <input
                                        type="checkbox"
                                        id="selectAll"
                                        class="ps-checkbox"
                                        title="Select all"
                                    >

                                </th>


                                <th>
                                    Product
                                </th>


                                <th>
                                    Details
                                </th>


                                <th>
                                    Current Status
                                </th>


                                <th>
                                    Quick Change
                                </th>


                                <th>
                                    Featured
                                </th>


                                <th>
                                    Published
                                </th>


                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>


                        <tbody>

                            <?php foreach (
                                $products
                                as $product
                            ): ?>

                                <tr>


                                    <!-- CHECKBOX -->

                                    <td>

                                        <input
                                            type="checkbox"
                                            name="product_ids[]"
                                            value="<?php echo (int)$product['id']; ?>"
                                            class="ps-checkbox product-checkbox"
                                        >

                                    </td>


                                    <!-- PRODUCT -->

                                    <td>

                                        <div class="ps-product">

                                            <div class="ps-product-name">

                                                <?php echo e(
                                                    $product['name']
                                                ); ?>

                                            </div>


                                            <?php if (
                                                !empty(
                                                    $product['slug']
                                                )
                                            ): ?>

                                                <div class="ps-product-slug">

                                                    /<?php echo e(
                                                        $product['slug']
                                                    ); ?>

                                                </div>

                                            <?php endif; ?>


                                            <?php if (
                                                !empty(
                                                    $product['product_code']
                                                )
                                            ): ?>

                                                <span
                                                    class="ps-product-code"
                                                >

                                                    <?php echo e(
                                                        $product['product_code']
                                                    ); ?>

                                                </span>

                                            <?php endif; ?>

                                        </div>

                                    </td>


                                    <!-- DETAILS -->

                                    <td>

                                        <div class="ps-meta-list">


                                            <?php if (
                                                !empty(
                                                    $product['cas_number']
                                                )
                                            ): ?>

                                                <div class="ps-meta-row">

                                                    <span class="ps-meta-label">
                                                        CAS:
                                                    </span>

                                                    <?php echo e(
                                                        $product['cas_number']
                                                    ); ?>

                                                </div>

                                            <?php endif; ?>


                                            <?php if (
                                                !empty(
                                                    $product['grade']
                                                )
                                            ): ?>

                                                <div class="ps-meta-row">

                                                    <span class="ps-meta-label">
                                                        Grade:
                                                    </span>

                                                    <?php echo e(
                                                        $product['grade']
                                                    ); ?>

                                                </div>

                                            <?php endif; ?>


                                            <?php if (
                                                !empty(
                                                    $product['sku']
                                                )
                                            ): ?>

                                                <div class="ps-meta-row">

                                                    <span class="ps-meta-label">
                                                        SKU:
                                                    </span>

                                                    <?php echo e(
                                                        $product['sku']
                                                    ); ?>

                                                </div>

                                            <?php endif; ?>

                                        </div>

                                    </td>


                                    <!-- CURRENT STATUS -->

                                    <td>

                                        <span
                                            class="ps-status <?php echo e(
                                                statusClass(
                                                    $product['status']
                                                )
                                            ); ?>"
                                        >

                                            <span
                                                class="ps-status-dot"
                                            ></span>

                                            <?php echo e(
                                                statusLabel(
                                                    $product['status']
                                                )
                                            ); ?>

                                        </span>

                                    </td>


                                    <!-- QUICK CHANGE -->

                                    <td>

                                        <form
                                            method="post"
                                            class="ps-status-form"
                                        >

                                            <?php echo csrf_field(); ?>


                                            <input
                                                type="hidden"
                                                name="product_id"
                                                value="<?php echo (int)$product['id']; ?>"
                                            >


                                            <select
                                                name="status"
                                                class="ps-status-select"
                                            >

                                                <option
                                                    value="published"
                                                    <?php echo $product['status'] === 'published'
                                                        ? 'selected'
                                                        : ''; ?>
                                                >
                                                    Published
                                                </option>


                                                <option
                                                    value="draft"
                                                    <?php echo $product['status'] === 'draft'
                                                        ? 'selected'
                                                        : ''; ?>
                                                >
                                                    Draft
                                                </option>


                                                <option
                                                    value="inactive"
                                                    <?php echo $product['status'] === 'inactive'
                                                        ? 'selected'
                                                        : ''; ?>
                                                >
                                                    Inactive
                                                </option>

                                            </select>


                                            <button
                                                type="submit"
                                                name="update_status"
                                                value="1"
                                                class="ps-status-save"
                                                title="Update status"
                                            >

                                                <i
                                                    class="fa-solid fa-check"
                                                ></i>

                                            </button>

                                        </form>

                                    </td>


                                    <!-- FEATURED -->

                                    <td>

                                        <form
                                            method="post"
                                            style="display:inline;"
                                        >

                                            <?php echo csrf_field(); ?>


                                            <input
                                                type="hidden"
                                                name="product_id"
                                                value="<?php echo (int)$product['id']; ?>"
                                            >


                                            <button
                                                type="submit"
                                                name="toggle_featured"
                                                value="1"
                                                class="ps-featured-btn <?php echo !empty(
                                                    $product['featured']
                                                )
                                                    ? 'active'
                                                    : ''; ?>"
                                                title="<?php echo !empty(
                                                    $product['featured']
                                                )
                                                    ? 'Remove from featured'
                                                    : 'Mark as featured'; ?>"
                                            >

                                                <i
                                                    class="<?php echo !empty(
                                                        $product['featured']
                                                    )
                                                        ? 'fa-solid'
                                                        : 'fa-regular'; ?>
                                                        fa-star"
                                                ></i>

                                            </button>

                                        </form>

                                    </td>


                                    <!-- PUBLISHED DATE -->

                                    <td>

                                        <?php if (
                                            !empty(
                                                $product['published_at']
                                            )
                                        ): ?>

                                            <div
                                                style="
                                                    color:#475569;
                                                    font-size:10px;
                                                    white-space:nowrap;
                                                "
                                            >

                                                <?php echo e(
                                                    date(
                                                        'd M Y',
                                                        strtotime(
                                                            $product['published_at']
                                                        )
                                                    )
                                                ); ?>

                                            </div>

                                            <div
                                                style="
                                                    margin-top:3px;
                                                    color:#94a3b8;
                                                    font-size:9px;
                                                "
                                            >

                                                <?php echo e(
                                                    date(
                                                        'h:i A',
                                                        strtotime(
                                                            $product['published_at']
                                                        )
                                                    )
                                                ); ?>

                                            </div>

                                        <?php else: ?>

                                            <span
                                                style="
                                                    color:#94a3b8;
                                                    font-size:10px;
                                                "
                                            >
                                                Not Published
                                            </span>

                                        <?php endif; ?>

                                    </td>


                                    <!-- ACTIONS -->

                                    <td>

                                        <div class="ps-actions">


                                            <a
                                                href="product_edit.php?id=<?php echo (int)$product['id']; ?>"
                                                class="ps-icon-btn"
                                                title="Edit Product"
                                            >

                                                <i
                                                    class="fa-solid fa-pen"
                                                ></i>

                                            </a>


                                            <a
                                                href="product_seo.php?product_id=<?php echo (int)$product['id']; ?>"
                                                class="ps-icon-btn"
                                                title="Product SEO"
                                            >

                                                <i
                                                    class="fa-solid fa-magnifying-glass-chart"
                                                ></i>

                                            </a>


                                            <a
                                                href="../product.php?slug=<?php echo urlencode(
                                                    $product['slug']
                                                ); ?>"
                                                target="_blank"
                                                rel="noopener"
                                                class="ps-icon-btn"
                                                title="View Product"
                                            >

                                                <i
                                                    class="fa-solid fa-arrow-up-right-from-square"
                                                ></i>

                                            </a>

                                        </div>

                                    </td>

                                </tr>

                            <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            </form>


            <!-- =================================================
                 PAGINATION
            ================================================== -->

            <?php if ($totalPages > 1): ?>

                <div class="ps-pagination">


                    <div class="ps-pagination-info">

                        Showing

                        <strong>
                            <?php echo $offset + 1; ?>
                        </strong>

                        –

                        <strong>
                            <?php echo min(
                                $offset + $perPage,
                                $totalRecords
                            ); ?>
                        </strong>

                        of

                        <strong>
                            <?php echo $totalRecords; ?>
                        </strong>

                        products

                    </div>


                    <div class="ps-pagination-links">


                        <?php if ($page > 1): ?>

                            <a
                                href="<?php echo e(
                                    paginationUrl(
                                        $page - 1
                                    )
                                ); ?>"
                                class="ps-page-link"
                            >

                                <i
                                    class="fa-solid fa-chevron-left"
                                ></i>

                            </a>

                        <?php endif; ?>


                        <?php

                        $startPage =
                            max(
                                1,
                                $page - 2
                            );

                        $endPage =
                            min(
                                $totalPages,
                                $page + 2
                            );

                        for (
                            $p = $startPage;
                            $p <= $endPage;
                            $p++
                        ):
                        ?>

                            <a
                                href="<?php echo e(
                                    paginationUrl($p)
                                ); ?>"
                                class="ps-page-link <?php echo $p === $page
                                    ? 'active'
                                    : ''; ?>"
                            >

                                <?php echo $p; ?>

                            </a>

                        <?php endfor; ?>


                        <?php if (
                            $page < $totalPages
                        ): ?>

                            <a
                                href="<?php echo e(
                                    paginationUrl(
                                        $page + 1
                                    )
                                ); ?>"
                                class="ps-page-link"
                            >

                                <i
                                    class="fa-solid fa-chevron-right"
                                ></i>

                            </a>

                        <?php endif; ?>


                    </div>

                </div>

            <?php endif; ?>


        <?php endif; ?>

    </div>

</div>


<script>

document.addEventListener(
    'DOMContentLoaded',
    function () {


        /* =================================================
           SELECT ALL
        ================================================== */

        const selectAll =
            document.getElementById(
                'selectAll'
            );

        const checkboxes =
            document.querySelectorAll(
                '.product-checkbox'
            );

        const bulkBar =
            document.getElementById(
                'bulkBar'
            );

        const selectedCount =
            document.getElementById(
                'selectedCount'
            );


        function updateSelection() {

            let count = 0;

            checkboxes.forEach(
                function (checkbox) {

                    if (checkbox.checked) {
                        count++;
                    }

                }
            );


            selectedCount.textContent =
                count;


            if (count > 0) {

                bulkBar.classList.add(
                    'show'
                );

            } else {

                bulkBar.classList.remove(
                    'show'
                );
            }


            if (
                selectAll &&
                checkboxes.length > 0
            ) {

                selectAll.checked =
                    count ===
                    checkboxes.length;

                selectAll.indeterminate =
                    count > 0 &&
                    count <
                    checkboxes.length;
            }
        }


        if (selectAll) {

            selectAll.addEventListener(
                'change',
                function () {

                    checkboxes.forEach(
                        function (checkbox) {

                            checkbox.checked =
                                selectAll.checked;

                        }
                    );


                    updateSelection();
                }
            );
        }


        checkboxes.forEach(
            function (checkbox) {

                checkbox.addEventListener(
                    'change',
                    updateSelection
                );

            }
        );


        updateSelection();


        /* =================================================
           BULK UPDATE
        ================================================== */

        const bulkStatus =
            document.getElementById(
                'bulkStatus'
            );

        const bulkStatusHidden =
            document.getElementById(
                'bulkStatusHidden'
            );

        const bulkUpdateBtn =
            document.getElementById(
                'bulkUpdateBtn'
            );

        const bulkForm =
            document.getElementById(
                'bulkForm'
            );


        if (bulkUpdateBtn) {

            bulkUpdateBtn.addEventListener(
                'click',
                function () {

                    let selected = 0;

                    checkboxes.forEach(
                        function (checkbox) {

                            if (
                                checkbox.checked
                            ) {
                                selected++;
                            }

                        }
                    );


                    if (selected === 0) {

                        alert(
                            'Please select at least one product.'
                        );

                        return;
                    }


                    if (
                        !bulkStatus.value
                    ) {

                        alert(
                            'Please select a status.'
                        );

                        bulkStatus.focus();

                        return;
                    }


                    const statusText =
                        bulkStatus.options[
                            bulkStatus.selectedIndex
                        ].text;


                    const confirmed =
                        confirm(
                            'Change status of ' +
                            selected +
                            ' selected product(s) to "' +
                            statusText +
                            '"?'
                        );


                    if (!confirmed) {
                        return;
                    }


                    bulkStatusHidden.value =
                        bulkStatus.value;


                    bulkForm.submit();
                }
            );
        }


        /* =================================================
           CONFIRM STATUS UPDATE
        ================================================== */

        document
            .querySelectorAll(
                '.ps-status-form'
            )
            .forEach(
                function (form) {

                    form.addEventListener(
                        'submit',
                        function (event) {

                            const select =
                                form.querySelector(
                                    '.ps-status-select'
                                );

                            const selectedStatus =
                                select
                                    ? select.value
                                    : '';


                            const confirmed =
                                confirm(
                                    'Update this product status to "' +
                                    selectedStatus +
                                    '"?'
                                );


                            if (!confirmed) {

                                event.preventDefault();
                            }

                        }
                    );

                }
            );


        /* =================================================
           FEATURED CONFIRM
        ================================================== */

        document
            .querySelectorAll(
                '.ps-featured-btn'
            )
            .forEach(
                function (button) {

                    const form =
                        button.closest(
                            'form'
                        );

                    if (!form) {
                        return;
                    }


                    form.addEventListener(
                        'submit',
                        function (event) {

                            const isActive =
                                button.classList.contains(
                                    'active'
                                );


                            const message =
                                isActive
                                    ? 'Remove this product from featured?'
                                    : 'Mark this product as featured?';


                            if (
                                !confirm(
                                    message
                                )
                            ) {

                                event.preventDefault();
                            }

                        }
                    );

                }
            );

    }
);

</script>


<?php

/* =========================================================
   FOOTER
========================================================= */

$footerFile =
    __DIR__ .
    '/includes/footer.php';

if (!file_exists($footerFile)) {

    $footerFile =
        __DIR__ .
        '/footer.php';
}

if (file_exists($footerFile)) {
    require_once $footerFile;
}

?>