```php
<?php
/**
 * File: admin/product_categories.php
 *
 * Product ↔ Category Relationship Manager
 *
 * Existing tables only:
 * products
 * categories
 * product_categories
 *
 * No new table.
 * No duplicate relationship.
 */

/* =========================================================
   DATABASE / AUTH / HELPERS
========================================================= */

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();


/* =========================================================
   BASIC ESCAPE HELPER
========================================================= */

if (!function_exists('e')) {

    function e($value)
    {
        return htmlspecialchars(
            (string) $value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}


/* =========================================================
   JSON RESPONSE
========================================================= */

function pc_json($success, $message, $extra = array())
{
    header(
        'Content-Type: application/json; charset=utf-8'
    );

    echo json_encode(
        array_merge(
            array(
                'success' => $success,
                'message' => $message
            ),
            $extra
        ),
        JSON_UNESCAPED_UNICODE
    );

    exit;
}


/* =========================================================
   CSRF
========================================================= */

function pc_verify_csrf()
{
    if (function_exists('requireCsrf')) {

        requireCsrf();

        return;
    }

    if (function_exists('csrf_verify')) {

        csrf_verify();

        return;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {

        $token = isset($_POST['csrf_token'])
            ? $_POST['csrf_token']
            : '';

        if (
            empty($_SESSION['csrf_token']) ||
            !hash_equals(
                $_SESSION['csrf_token'],
                $token
            )
        ) {

            http_response_code(419);

            exit('Invalid CSRF token.');
        }
    }
}


/* =========================================================
   DETECT PRODUCT_CATEGORIES COLUMNS
========================================================= */

try {

    $columnsQuery = $pdo->query(
        "SHOW COLUMNS FROM product_categories"
    );

    $columns = $columnsQuery->fetchAll(
        PDO::FETCH_ASSOC
    );

} catch (Throwable $e) {

    http_response_code(500);

    exit(
        'Unable to read product_categories table.'
    );
}


$availableColumns = array();

foreach ($columns as $column) {

    if (!empty($column['Field'])) {

        $availableColumns[] =
            $column['Field'];
    }
}


/* =========================================================
   PRODUCT COLUMN
========================================================= */

$productColumn = null;

foreach (
    array(
        'product_id',
        'productId',
        'product'
    )
    as $candidate
) {

    if (
        in_array(
            $candidate,
            $availableColumns,
            true
        )
    ) {

        $productColumn =
            $candidate;

        break;
    }
}


/* =========================================================
   CATEGORY COLUMN
========================================================= */

$categoryColumn = null;

foreach (
    array(
        'category_id',
        'categoryId',
        'category'
    )
    as $candidate
) {

    if (
        in_array(
            $candidate,
            $availableColumns,
            true
        )
    ) {

        $categoryColumn =
            $candidate;

        break;
    }
}


if (
    !$productColumn ||
    !$categoryColumn
) {

    http_response_code(500);

    exit(
        'product_categories table must contain product_id and category_id columns.'
    );
}


/* =========================================================
   POST ACTIONS
========================================================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    pc_verify_csrf();

    $action = isset($_POST['action'])
        ? trim($_POST['action'])
        : '';


    /* =====================================================
       ADD CATEGORY
    ===================================================== */

    if ($action === 'add') {

        $productId = isset($_POST['product_id'])
            ? (int) $_POST['product_id']
            : 0;

        $categoryId = isset($_POST['category_id'])
            ? (int) $_POST['category_id']
            : 0;


        if (
            $productId <= 0 ||
            $categoryId <= 0
        ) {

            pc_json(
                false,
                'Please select a product and category.'
            );
        }


        /* Product exists */

        $productCheck = $pdo->prepare(
            "SELECT id, name
             FROM products
             WHERE id = ?
             LIMIT 1"
        );

        $productCheck->execute(
            array($productId)
        );

        $product =
            $productCheck->fetch();


        if (!$product) {

            pc_json(
                false,
                'Selected product does not exist.'
            );
        }


        /* Category exists */

        $categoryCheck = $pdo->prepare(
            "SELECT id, name
             FROM categories
             WHERE id = ?
             LIMIT 1"
        );

        $categoryCheck->execute(
            array($categoryId)
        );

        $category =
            $categoryCheck->fetch();


        if (!$category) {

            pc_json(
                false,
                'Selected category does not exist.'
            );
        }


        /* Duplicate relation check */

        $duplicateCheck = $pdo->prepare(
            "SELECT 1
             FROM product_categories
             WHERE `{$productColumn}` = ?
             AND `{$categoryColumn}` = ?
             LIMIT 1"
        );

        $duplicateCheck->execute(
            array(
                $productId,
                $categoryId
            )
        );


        if (
            $duplicateCheck->fetchColumn()
        ) {

            pc_json(
                false,
                'This category is already assigned to this product.'
            );
        }


        /* Insert relation */

        $insert = $pdo->prepare(
            "INSERT INTO product_categories
             (`{$productColumn}`, `{$categoryColumn}`)
             VALUES (?, ?)"
        );

        $insert->execute(
            array(
                $productId,
                $categoryId
            )
        );


        pc_json(
            true,
            'Category assigned successfully.'
        );
    }


    /* =====================================================
       REMOVE CATEGORY
    ===================================================== */

    if ($action === 'remove') {

        $productId = isset($_POST['product_id'])
            ? (int) $_POST['product_id']
            : 0;

        $categoryId = isset($_POST['category_id'])
            ? (int) $_POST['category_id']
            : 0;


        if (
            $productId <= 0 ||
            $categoryId <= 0
        ) {

            pc_json(
                false,
                'Invalid product/category.'
            );
        }


        $delete = $pdo->prepare(
            "DELETE FROM product_categories
             WHERE `{$productColumn}` = ?
             AND `{$categoryColumn}` = ?
             LIMIT 1"
        );

        $delete->execute(
            array(
                $productId,
                $categoryId
            )
        );


        if (
            $delete->rowCount() === 0
        ) {

            pc_json(
                false,
                'Category relationship was not found.'
            );
        }


        pc_json(
            true,
            'Category removed successfully.'
        );
    }


    pc_json(
        false,
        'Invalid action.'
    );
}


/* =========================================================
   FILTERS
========================================================= */

$search = isset($_GET['search'])
    ? trim($_GET['search'])
    : '';

$productFilter = isset($_GET['product_id'])
    ? (int) $_GET['product_id']
    : 0;

$categoryFilter = isset($_GET['category_id'])
    ? (int) $_GET['category_id']
    : 0;

$page = isset($_GET['page'])
    ? max(
        1,
        (int) $_GET['page']
    )
    : 1;

$perPage = 20;

$offset =
    ($page - 1) *
    $perPage;


/* =========================================================
   PRODUCTS
========================================================= */

$productsQuery = $pdo->query(
    "SELECT
        id,
        name,
        slug,
        product_code,
        status,
        featured
     FROM products
     ORDER BY name ASC"
);

$products =
    $productsQuery->fetchAll(
        PDO::FETCH_ASSOC
    );


/* =========================================================
   CATEGORIES
========================================================= */

$categoriesQuery = $pdo->query(
    "SELECT
        id,
        name,
        slug,
        parent_id
     FROM categories
     ORDER BY name ASC"
);

$categories =
    $categoriesQuery->fetchAll(
        PDO::FETCH_ASSOC
    );


/* =========================================================
   CATEGORY MAP
========================================================= */

$categoryMap = array();

foreach ($categories as $category) {

    $categoryMap[
        (int) $category['id']
    ] = $category;
}


/* =========================================================
   CATEGORY FULL PATH
========================================================= */

function pc_category_path(
    $categoryId,
    $categoryMap
) {

    if (
        !isset(
            $categoryMap[$categoryId]
        )
    ) {

        return 'Unknown Category';
    }


    $parts = array();

    $currentId =
        (int) $categoryId;

    $guard = 0;


    while (
        isset(
            $categoryMap[$currentId]
        ) &&
        $guard < 50
    ) {

        $parts[] =
            $categoryMap[$currentId]['name'];


        $parentId = isset(
            $categoryMap[$currentId]['parent_id']
        )
            ? (int)
                $categoryMap[$currentId]['parent_id']
            : 0;


        if (
            $parentId <= 0 ||
            $parentId === $currentId
        ) {

            break;
        }


        $currentId =
            $parentId;

        $guard++;
    }


    return implode(
        ' / ',
        array_reverse($parts)
    );
}


/* =========================================================
   BUILD WHERE
========================================================= */

$where = array();

$params = array();


if ($productFilter > 0) {

    $where[] =
        "pc.`{$productColumn}` = ?";

    $params[] =
        $productFilter;
}


if ($categoryFilter > 0) {

    $where[] =
        "pc.`{$categoryColumn}` = ?";

    $params[] =
        $categoryFilter;
}


if ($search !== '') {

    $where[] = "
        (
            p.name LIKE ?
            OR p.slug LIKE ?
            OR p.product_code LIKE ?
            OR c.name LIKE ?
            OR c.slug LIKE ?
        )
    ";

    $like =
        '%' . $search . '%';

    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}


$whereSql = '';

if (!empty($where)) {

    $whereSql =
        'WHERE ' .
        implode(
            ' AND ',
            $where
        );
}


/* =========================================================
   TOTAL
========================================================= */

$countSql = "
    SELECT COUNT(*)

    FROM product_categories pc

    INNER JOIN products p
        ON p.id =
        pc.`{$productColumn}`

    INNER JOIN categories c
        ON c.id =
        pc.`{$categoryColumn}`

    {$whereSql}
";


$countStmt =
    $pdo->prepare(
        $countSql
    );

$countStmt->execute(
    $params
);

$totalRows =
    (int)
    $countStmt->fetchColumn();


$totalPages =
    max(
        1,
        (int)
        ceil(
            $totalRows /
            $perPage
        )
    );


/* =========================================================
   RELATIONSHIP DATA
========================================================= */

$dataSql = "
    SELECT

        pc.`{$productColumn}`
            AS product_id,

        pc.`{$categoryColumn}`
            AS category_id,

        p.name
            AS product_name,

        p.slug
            AS product_slug,

        p.product_code,

        p.status
            AS product_status,

        p.featured,

        c.name
            AS category_name,

        c.slug
            AS category_slug,

        c.parent_id
            AS category_parent_id

    FROM product_categories pc

    INNER JOIN products p
        ON p.id =
        pc.`{$productColumn}`

    INNER JOIN categories c
        ON c.id =
        pc.`{$categoryColumn}`

    {$whereSql}

    ORDER BY
        p.name ASC,
        c.name ASC

    LIMIT {$perPage}
    OFFSET {$offset}
";


$dataStmt =
    $pdo->prepare(
        $dataSql
    );

$dataStmt->execute(
    $params
);

$relationships =
    $dataStmt->fetchAll(
        PDO::FETCH_ASSOC
    );


/* =========================================================
   STATISTICS
========================================================= */

$totalAssignments =
    (int)
    $pdo->query(
        "SELECT COUNT(*)
         FROM product_categories"
    )->fetchColumn();


$totalProducts =
    (int)
    $pdo->query(
        "SELECT COUNT(*)
         FROM products"
    )->fetchColumn();


$totalCategories =
    (int)
    $pdo->query(
        "SELECT COUNT(*)
         FROM categories"
    )->fetchColumn();


$assignedProducts =
    (int)
    $pdo->query(
        "SELECT COUNT(
            DISTINCT `{$productColumn}`
        )
        FROM product_categories"
    )->fetchColumn();


$unassignedProducts =
    max(
        0,
        $totalProducts -
        $assignedProducts
    );


/* =========================================================
   CSRF TOKEN
========================================================= */

$csrfToken = '';

if (
    function_exists('csrf_token')
) {

    $csrfToken =
        (string)
        csrf_token();

} elseif (
    !empty(
        $_SESSION['csrf_token']
    )
) {

    $csrfToken =
        (string)
        $_SESSION['csrf_token'];

} else {

    $csrfToken =
        bin2hex(
            random_bytes(32)
        );

    $_SESSION['csrf_token'] =
        $csrfToken;
}


/* =========================================================
   PAGE VARIABLES
========================================================= */

$page_title =
    'Product Categories';

$active_menu =
    'product_categories';


/* =========================================================
   LOAD ADMIN HEADER
   Current project structure:
   admin/header.php
========================================================= */

if (
    file_exists(
        __DIR__ . '/header.php'
    )
) {

    require_once
        __DIR__ . '/header.php';

} elseif (
    file_exists(
        __DIR__ . '/includes/header.php'
    )
) {

    require_once
        __DIR__ . '/includes/header.php';

} else {

    exit(
        'Admin header file not found. Expected admin/header.php'
    );
}

?>

<style>

/* =========================================================
   PRODUCT CATEGORY PAGE
========================================================= */

.pc-page {
    padding: 28px;
    max-width: 1600px;
    margin: 0 auto;
}

.pc-head {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 20px;
    margin-bottom: 26px;
}

.pc-title h1 {
    margin: 0;
    color: #111827;
    font-size: 30px;
    line-height: 1.2;
    font-weight: 800;
    letter-spacing: -.7px;
}

.pc-title p {
    margin: 8px 0 0;
    color: #6b7280;
    font-size: 14px;
}

.pc-add-btn {
    border: 0;
    border-radius: 12px;
    padding: 12px 18px;
    background: linear-gradient(
        135deg,
        #111827,
        #374151
    );
    color: #fff;
    display: inline-flex;
    align-items: center;
    gap: 9px;
    font-size: 13px;
    font-weight: 800;
    cursor: pointer;
    box-shadow:
        0 10px 25px
        rgba(
            17,
            24,
            39,
            .16
        );
    transition: .2s ease;
}

.pc-add-btn:hover {
    transform: translateY(-2px);
    box-shadow:
        0 15px 32px
        rgba(
            17,
            24,
            39,
            .22
        );
}


/* =========================================================
   STATS
========================================================= */

.pc-stats {
    display: grid;
    grid-template-columns:
        repeat(
            4,
            minmax(0, 1fr)
        );
    gap: 16px;
    margin-bottom: 22px;
}

.pc-stat {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 17px;
    padding: 19px;
    display: flex;
    align-items: center;
    gap: 14px;
    box-shadow:
        0 7px 24px
        rgba(
            15,
            23,
            42,
            .045
        );
}

.pc-stat-icon {
    width: 46px;
    height: 46px;
    border-radius: 13px;
    background: #f3f4f6;
    color: #111827;
    display: grid;
    place-items: center;
    font-size: 17px;
}

.pc-stat strong {
    display: block;
    color: #111827;
    font-size: 23px;
    line-height: 1;
}

.pc-stat span {
    display: block;
    margin-top: 6px;
    color: #6b7280;
    font-size: 12px;
    font-weight: 600;
}


/* =========================================================
   MAIN CARD
========================================================= */

.pc-card {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 18px;
    overflow: hidden;
    box-shadow:
        0 8px 30px
        rgba(
            15,
            23,
            42,
            .055
        );
}

.pc-filters {
    padding: 20px;
    border-bottom: 1px solid #edf0f3;
    display: grid;
    grid-template-columns:
        1.3fr 1fr 1fr auto;
    gap: 12px;
}

.pc-input,
.pc-select {
    width: 100%;
    min-height: 44px;
    box-sizing: border-box;
    border: 1px solid #dfe3e8;
    border-radius: 11px;
    background: #fff;
    padding: 0 13px;
    color: #111827;
    font-size: 13px;
    outline: none;
}

.pc-input:focus,
.pc-select:focus {
    border-color: #9ca3af;
    box-shadow:
        0 0 0 4px
        rgba(
            17,
            24,
            39,
            .06
        );
}

.pc-filter-buttons {
    display: flex;
    gap: 8px;
}

.pc-filter,
.pc-reset {
    min-height: 44px;
    border-radius: 11px;
    padding: 0 16px;
    font-size: 13px;
    font-weight: 800;
    cursor: pointer;
}

.pc-filter {
    border: 0;
    background: #111827;
    color: #fff;
}

.pc-reset {
    border: 1px solid #e5e7eb;
    background: #fff;
    color: #374151;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
}


/* =========================================================
   TABLE
========================================================= */

.pc-table-wrap {
    overflow-x: auto;
}

.pc-table {
    width: 100%;
    min-width: 900px;
    border-collapse: collapse;
}

.pc-table th {
    padding: 13px 18px;
    background: #f9fafb;
    border-bottom: 1px solid #e5e7eb;
    color: #6b7280;
    text-align: left;
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: .65px;
    font-weight: 800;
}

.pc-table td {
    padding: 15px 18px;
    border-bottom: 1px solid #f0f2f5;
    color: #374151;
    font-size: 13px;
    vertical-align: middle;
}

.pc-table tr:hover td {
    background: #fafafa;
}


/* =========================================================
   PRODUCT
========================================================= */

.pc-product {
    display: flex;
    align-items: center;
    gap: 12px;
}

.pc-product-icon,
.pc-category-icon {
    width: 40px;
    height: 40px;
    flex: 0 0 40px;
    border-radius: 11px;
    background: #f3f4f6;
    display: grid;
    place-items: center;
    color: #374151;
}

.pc-product-name {
    color: #111827;
    font-weight: 800;
}

.pc-product-code {
    margin-top: 4px;
    color: #9ca3af;
    font-size: 11px;
}


/* =========================================================
   CATEGORY
========================================================= */

.pc-category {
    display: flex;
    align-items: center;
    gap: 10px;
}

.pc-category-name {
    color: #111827;
    font-weight: 750;
}

.pc-category-path {
    margin-top: 4px;
    color: #9ca3af;
    font-size: 11px;
}


/* =========================================================
   BADGES
========================================================= */

.pc-badge {
    display: inline-flex;
    align-items: center;
    min-height: 25px;
    padding: 0 9px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 800;
}

.pc-published {
    background: #ecfdf3;
    color: #047857;
}

.pc-draft {
    background: #fff7ed;
    color: #c2410c;
}

.pc-inactive {
    background: #f3f4f6;
    color: #6b7280;
}

.pc-featured {
    color: #b45309;
    font-size: 12px;
    font-weight: 800;
}


/* =========================================================
   REMOVE
========================================================= */

.pc-remove {
    border: 0;
    border-radius: 9px;
    padding: 8px 11px;
    background: #fff1f2;
    color: #be123c;
    font-size: 12px;
    font-weight: 800;
    cursor: pointer;
}

.pc-remove:hover {
    background: #ffe4e6;
}


/* =========================================================
   EMPTY
========================================================= */

.pc-empty {
    text-align: center;
    padding: 70px 20px;
}

.pc-empty-icon {
    width: 62px;
    height: 62px;
    margin: 0 auto 14px;
    border-radius: 18px;
    background: #f3f4f6;
    display: grid;
    place-items: center;
    color: #6b7280;
    font-size: 24px;
}

.pc-empty h3 {
    margin: 0;
    color: #111827;
    font-size: 17px;
}

.pc-empty p {
    margin: 7px 0 0;
    color: #9ca3af;
    font-size: 13px;
}


/* =========================================================
   PAGINATION
========================================================= */

.pc-pagination {
    padding: 16px 20px;
    border-top: 1px solid #edf0f3;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 15px;
}

.pc-page-info {
    color: #6b7280;
    font-size: 12px;
    font-weight: 600;
}

.pc-pages {
    display: flex;
    gap: 6px;
}

.pc-pages a {
    min-width: 34px;
    height: 34px;
    padding: 0 10px;
    box-sizing: border-box;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #e5e7eb;
    border-radius: 9px;
    background: #fff;
    color: #374151;
    text-decoration: none;
    font-size: 12px;
    font-weight: 800;
}

.pc-pages a.active {
    background: #111827;
    border-color: #111827;
    color: #fff;
}


/* =========================================================
   MODAL
========================================================= */

.pc-modal {
    position: fixed;
    inset: 0;
    z-index: 9999;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 20px;
    background: rgba(
        15,
        23,
        42,
        .55
    );
    backdrop-filter: blur(6px);
}

.pc-modal.show {
    display: flex;
}

.pc-modal-box {
    width: 100%;
    max-width: 560px;
    background: #fff;
    border-radius: 20px;
    overflow: hidden;
    box-shadow:
        0 30px 80px
        rgba(
            15,
            23,
            42,
            .25
        );
}

.pc-modal-head {
    padding: 20px 22px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #edf0f3;
}

.pc-modal-head h2 {
    margin: 0;
    color: #111827;
    font-size: 18px;
}

.pc-close {
    width: 34px;
    height: 34px;
    border: 0;
    border-radius: 9px;
    background: #f3f4f6;
    color: #374151;
    cursor: pointer;
}

.pc-modal-body {
    padding: 22px;
}

.pc-field {
    margin-bottom: 18px;
}

.pc-field:last-child {
    margin-bottom: 0;
}

.pc-field label {
    display: block;
    margin-bottom: 7px;
    color: #374151;
    font-size: 12px;
    font-weight: 800;
}

.pc-required {
    color: #dc2626;
}

.pc-modal-footer {
    padding: 16px 22px;
    border-top: 1px solid #edf0f3;
    display: flex;
    justify-content: flex-end;
    gap: 9px;
}

.pc-cancel,
.pc-save {
    min-height: 40px;
    border-radius: 10px;
    padding: 0 15px;
    font-weight: 800;
    cursor: pointer;
}

.pc-cancel {
    border: 1px solid #e5e7eb;
    background: #fff;
    color: #374151;
}

.pc-save {
    border: 0;
    background: #111827;
    color: #fff;
}


/* =========================================================
   TOAST
========================================================= */

.pc-toast {
    position: fixed;
    right: 22px;
    bottom: 22px;
    z-index: 10001;
    min-width: 280px;
    max-width: 420px;
    padding: 13px 16px;
    border-radius: 13px;
    background: #111827;
    color: #fff;
    display: none;
    box-shadow:
        0 15px 40px
        rgba(
            15,
            23,
            42,
            .25
        );
    font-size: 13px;
    font-weight: 700;
}

.pc-toast.show {
    display: block;
}

.pc-toast.error {
    background: #991b1b;
}


/* =========================================================
   RESPONSIVE
========================================================= */

@media (max-width: 1100px) {

    .pc-stats {
        grid-template-columns:
            repeat(
                2,
                1fr
            );
    }

    .pc-filters {
        grid-template-columns:
            1fr 1fr;
    }
}


@media (max-width: 700px) {

    .pc-page {
        padding: 18px;
    }

    .pc-head {
        flex-direction: column;
    }

    .pc-add-btn {
        width: 100%;
        justify-content: center;
    }

    .pc-stats {
        grid-template-columns: 1fr;
    }

    .pc-filters {
        grid-template-columns: 1fr;
    }

    .pc-filter-buttons {
        width: 100%;
    }

    .pc-filter,
    .pc-reset {
        flex: 1;
        justify-content: center;
    }

    .pc-pagination {
        flex-direction: column;
        align-items: flex-start;
    }
}

</style>


<div class="pc-page">


    <!-- =====================================================
         PAGE HEADER
    ====================================================== -->

    <div class="pc-head">

        <div class="pc-title">

            <h1>
                Product Categories
            </h1>

            <p>
                Manage categories assigned to your chemical products.
            </p>

        </div>


        <button
            type="button"
            class="pc-add-btn"
            onclick="openPcModal()"
        >

            <i class="fa-solid fa-plus"></i>

            Assign Category

        </button>

    </div>


    <!-- =====================================================
         STATISTICS
    ====================================================== -->

    <div class="pc-stats">


        <div class="pc-stat">

            <div class="pc-stat-icon">
                <i class="fa-solid fa-link"></i>
            </div>

            <div>

                <strong>
                    <?= number_format(
                        $totalAssignments
                    ) ?>
                </strong>

                <span>
                    Total Assignments
                </span>

            </div>

        </div>


        <div class="pc-stat">

            <div class="pc-stat-icon">
                <i class="fa-solid fa-flask"></i>
            </div>

            <div>

                <strong>
                    <?= number_format(
                        $totalProducts
                    ) ?>
                </strong>

                <span>
                    Total Products
                </span>

            </div>

        </div>


        <div class="pc-stat">

            <div class="pc-stat-icon">
                <i class="fa-solid fa-layer-group"></i>
            </div>

            <div>

                <strong>
                    <?= number_format(
                        $totalCategories
                    ) ?>
                </strong>

                <span>
                    Total Categories
                </span>

            </div>

        </div>


        <div class="pc-stat">

            <div class="pc-stat-icon">
                <i class="fa-solid fa-circle-exclamation"></i>
            </div>

            <div>

                <strong>
                    <?= number_format(
                        $unassignedProducts
                    ) ?>
                </strong>

                <span>
                    Unassigned Products
                </span>

            </div>

        </div>


    </div>


    <!-- =====================================================
         MAIN CARD
    ====================================================== -->

    <div class="pc-card">


        <!-- FILTERS -->

        <form
            method="get"
            action="product_categories.php"
            class="pc-filters"
        >


            <input
                type="text"
                name="search"
                class="pc-input"
                placeholder="Search product or category..."
                value="<?= e($search) ?>"
            >


            <select
                name="product_id"
                class="pc-select"
            >

                <option value="">
                    All Products
                </option>


                <?php foreach (
                    $products
                    as $product
                ): ?>

                    <option
                        value="<?= (int)
                            $product['id'] ?>"
                        <?= (
                            $productFilter ===
                            (int)
                            $product['id']
                        )
                            ? 'selected'
                            : ''
                        ?>
                    >

                        <?= e(
                            $product['name']
                        ) ?>

                        <?php
                        if (
                            !empty(
                                $product['product_code']
                            )
                        ):
                        ?>

                            —
                            <?= e(
                                $product['product_code']
                            ) ?>

                        <?php endif; ?>

                    </option>

                <?php endforeach; ?>

            </select>


            <select
                name="category_id"
                class="pc-select"
            >

                <option value="">
                    All Categories
                </option>


                <?php foreach (
                    $categories
                    as $category
                ): ?>

                    <option
                        value="<?= (int)
                            $category['id'] ?>"
                        <?= (
                            $categoryFilter ===
                            (int)
                            $category['id']
                        )
                            ? 'selected'
                            : ''
                        ?>
                    >

                        <?= e(
                            pc_category_path(
                                (int)
                                $category['id'],
                                $categoryMap
                            )
                        ) ?>

                    </option>

                <?php endforeach; ?>

            </select>


            <div class="pc-filter-buttons">

                <button
                    type="submit"
                    class="pc-filter"
                >

                    <i class="fa-solid fa-filter"></i>

                    Filter

                </button>


                <?php if (
                    $search !== '' ||
                    $productFilter > 0 ||
                    $categoryFilter > 0
                ): ?>

                    <a
                        href="product_categories.php"
                        class="pc-reset"
                    >
                        Reset
                    </a>

                <?php endif; ?>

            </div>


        </form>


        <!-- =================================================
             TABLE
        ================================================== -->

        <div class="pc-table-wrap">


            <?php if (
                empty($relationships)
            ): ?>


                <div class="pc-empty">

                    <div class="pc-empty-icon">

                        <i
                            class="
                                fa-solid
                                fa-link-slash
                            "
                        ></i>

                    </div>


                    <h3>
                        No Product Category Assignments
                    </h3>


                    <p>
                        No product-category relationships found.
                    </p>

                </div>


            <?php else: ?>


                <table class="pc-table">


                    <thead>

                        <tr>

                            <th>
                                Product
                            </th>

                            <th>
                                Category
                            </th>

                            <th>
                                Status
                            </th>

                            <th>
                                Featured
                            </th>

                            <th
                                style="text-align:right;"
                            >
                                Action
                            </th>

                        </tr>

                    </thead>


                    <tbody>


                    <?php foreach (
                        $relationships
                        as $row
                    ): ?>


                        <?php

                        $status =
                            (string)
                            $row['product_status'];


                        if (
                            $status ===
                            'published'
                        ) {

                            $statusClass =
                                'pc-published';

                        } elseif (
                            $status ===
                            'inactive'
                        ) {

                            $statusClass =
                                'pc-inactive';

                        } else {

                            $statusClass =
                                'pc-draft';
                        }


                        $categoryPath =
                            pc_category_path(
                                (int)
                                $row['category_id'],
                                $categoryMap
                            );

                        ?>


                        <tr
                            id="pc-row-<?= (int)
                                $row['product_id'] ?>-<?= (int)
                                $row['category_id'] ?>"
                        >


                            <!-- PRODUCT -->

                            <td>

                                <div
                                    class="pc-product"
                                >

                                    <div
                                        class="
                                            pc-product-icon
                                        "
                                    >

                                        <i
                                            class="
                                                fa-solid
                                                fa-flask
                                            "
                                        ></i>

                                    </div>


                                    <div>

                                        <div
                                            class="
                                                pc-product-name
                                            "
                                        >

                                            <?= e(
                                                $row['product_name']
                                            ) ?>

                                        </div>


                                        <div
                                            class="
                                                pc-product-code
                                            "
                                        >

                                            <?php
                                            if (
                                                !empty(
                                                    $row['product_code']
                                                )
                                            ):
                                            ?>

                                                Code:
                                                <?= e(
                                                    $row['product_code']
                                                ) ?>

                                            <?php
                                            else:
                                            ?>

                                                <?= e(
                                                    $row['product_slug']
                                                ) ?>

                                            <?php endif; ?>

                                        </div>

                                    </div>

                                </div>

                            </td>


                            <!-- CATEGORY -->

                            <td>

                                <div
                                    class="
                                        pc-category
                                    "
                                >

                                    <div
                                        class="
                                            pc-category-icon
                                        "
                                    >

                                        <i
                                            class="
                                                fa-solid
                                                fa-folder-tree
                                            "
                                        ></i>

                                    </div>


                                    <div>

                                        <div
                                            class="
                                                pc-category-name
                                            "
                                        >

                                            <?= e(
                                                $row['category_name']
                                            ) ?>

                                        </div>


                                        <?php
                                        if (
                                            $categoryPath !==
                                            $row['category_name']
                                        ):
                                        ?>

                                            <div
                                                class="
                                                    pc-category-path
                                                "
                                            >

                                                <?= e(
                                                    $categoryPath
                                                ) ?>

                                            </div>

                                        <?php endif; ?>

                                    </div>

                                </div>

                            </td>


                            <!-- STATUS -->

                            <td>

                                <span
                                    class="
                                        pc-badge
                                        <?= e(
                                            $statusClass
                                        ) ?>
                                    "
                                >

                                    <?= e(
                                        ucfirst(
                                            $status
                                        )
                                    ) ?>

                                </span>

                            </td>


                            <!-- FEATURED -->

                            <td>

                                <?php
                                if (
                                    (int)
                                    $row['featured']
                                    === 1
                                ):
                                ?>

                                    <span
                                        class="
                                            pc-featured
                                        "
                                    >

                                        <i
                                            class="
                                                fa-solid
                                                fa-star
                                            "
                                        ></i>

                                        Featured

                                    </span>

                                <?php else: ?>

                                    <span
                                        style="
                                            color:#9ca3af;
                                        "
                                    >
                                        —
                                    </span>

                                <?php endif; ?>

                            </td>


                            <!-- REMOVE -->

                            <td
                                style="
                                    text-align:right;
                                "
                            >

                                <button
                                    type="button"
                                    class="pc-remove"
                                    onclick="
                                        removePcRelation(
                                            <?= (int)
                                                $row['product_id'] ?>,
                                            <?= (int)
                                                $row['category_id'] ?>,
                                            this
                                        )
                                    "
                                >

                                    <i
                                        class="
                                            fa-solid
                                            fa-xmark
                                        "
                                    ></i>

                                    Remove

                                </button>

                            </td>


                        </tr>


                    <?php endforeach; ?>


                    </tbody>

                </table>


            <?php endif; ?>


        </div>


        <!-- =================================================
             PAGINATION
        ================================================== -->

        <?php if (
            $totalRows > 0
        ): ?>


            <div
                class="
                    pc-pagination
                "
            >


                <div
                    class="
                        pc-page-info
                    "
                >

                    Showing

                    <?= number_format(
                        $offset + 1
                    ) ?>

                    –

                    <?= number_format(
                        min(
                            $offset +
                            count(
                                $relationships
                            ),
                            $totalRows
                        )
                    ) ?>

                    of

                    <?= number_format(
                        $totalRows
                    ) ?>

                    assignments

                </div>


                <?php
                if (
                    $totalPages > 1
                ):
                ?>


                    <div
                        class="
                            pc-pages
                        "
                    >


                        <?php
                        $startPage =
                            max(
                                1,
                                $page - 2
                            );

                        $endPage =
                            min(
                                $totalPages,
                                $page + 2
                            );
                        ?>


                        <?php
                        if (
                            $page > 1
                        ):
                        ?>

                            <a
                                href="<?= e(
                                    'product_categories.php?' .
                                    http_build_query(
                                        array_merge(
                                            $_GET,
                                            array(
                                                'page' =>
                                                    $page - 1
                                            )
                                        )
                                    )
                                ) ?>"
                            >

                                <i
                                    class="
                                        fa-solid
                                        fa-chevron-left
                                    "
                                ></i>

                            </a>

                        <?php endif; ?>


                        <?php
                        for (
                            $p = $startPage;
                            $p <= $endPage;
                            $p++
                        ):
                        ?>

                            <a
                                href="<?= e(
                                    'product_categories.php?' .
                                    http_build_query(
                                        array_merge(
                                            $_GET,
                                            array(
                                                'page' => $p
                                            )
                                        )
                                    )
                                ) ?>"
                                class="<?= (
                                    $p === $page
                                )
                                    ? 'active'
                                    : ''
                                ?>"
                            >

                                <?= $p ?>

                            </a>

                        <?php endfor; ?>


                        <?php
                        if (
                            $page <
                            $totalPages
                        ):
                        ?>

                            <a
                                href="<?= e(
                                    'product_categories.php?' .
                                    http_build_query(
                                        array_merge(
                                            $_GET,
                                            array(
                                                'page' =>
                                                    $page + 1
                                            )
                                        )
                                    )
                                ) ?>"
                            >

                                <i
                                    class="
                                        fa-solid
                                        fa-chevron-right
                                    "
                                ></i>

                            </a>

                        <?php endif; ?>


                    </div>


                <?php endif; ?>


            </div>


        <?php endif; ?>


    </div>


</div>


<!-- =========================================================
     ASSIGN MODAL
========================================================= -->

<div
    class="pc-modal"
    id="pcModal"
>


    <div
        class="pc-modal-box"
    >


        <div
            class="pc-modal-head"
        >

            <h2>
                Assign Product Category
            </h2>


            <button
                type="button"
                class="pc-close"
                onclick="closePcModal()"
            >

                <i
                    class="
                        fa-solid
                        fa-xmark
                    "
                ></i>

            </button>

        </div>


        <form
            id="pcForm"
            onsubmit="
                submitPcRelation(event)
            "
        >


            <div
                class="pc-modal-body"
            >


                <div
                    class="pc-field"
                >

                    <label>

                        Product

                        <span
                            class="
                                pc-required
                            "
                        >
                            *
                        </span>

                    </label>


                    <select
                        name="product_id"
                        id="pcProduct"
                        class="pc-select"
                        required
                    >

                        <option value="">
                            Select Product
                        </option>


                        <?php foreach (
                            $products
                            as $product
                        ): ?>

                            <option
                                value="<?= (int)
                                    $product['id'] ?>"
                            >

                                <?= e(
                                    $product['name']
                                ) ?>

                                <?php
                                if (
                                    !empty(
                                        $product['product_code']
                                    )
                                ):
                                ?>

                                    —
                                    <?= e(
                                        $product['product_code']
                                    ) ?>

                                <?php endif; ?>

                            </option>

                        <?php endforeach; ?>

                    </select>

                </div>


                <div
                    class="pc-field"
                >

                    <label>

                        Category

                        <span
                            class="
                                pc-required
                            "
                        >
                            *
                        </span>

                    </label>


                    <select
                        name="category_id"
                        id="pcCategory"
                        class="pc-select"
                        required
                    >

                        <option value="">
                            Select Category
                        </option>


                        <?php foreach (
                            $categories
                            as $category
                        ): ?>

                            <option
                                value="<?= (int)
                                    $category['id'] ?>"
                            >

                                <?= e(
                                    pc_category_path(
                                        (int)
                                        $category['id'],
                                        $categoryMap
                                    )
                                ) ?>

                            </option>

                        <?php endforeach; ?>

                    </select>

                </div>


            </div>


            <div
                class="pc-modal-footer"
            >

                <button
                    type="button"
                    class="pc-cancel"
                    onclick="closePcModal()"
                >
                    Cancel
                </button>


                <button
                    type="submit"
                    class="pc-save"
                    id="pcSave"
                >

                    <i
                        class="
                            fa-solid
                            fa-link
                        "
                    ></i>

                    Assign Category

                </button>

            </div>


        </form>


    </div>

</div>


<!-- =========================================================
     TOAST
========================================================= -->

<div
    class="pc-toast"
    id="pcToast"
></div>


<script>

/* =========================================================
   CSRF
========================================================= */

const PC_CSRF =
    <?= json_encode(
        $csrfToken,
        JSON_UNESCAPED_UNICODE
    ) ?>;


/* =========================================================
   TOAST
========================================================= */

function pcToast(
    message,
    error
) {

    const toast =
        document.getElementById(
            'pcToast'
        );

    toast.textContent =
        message;

    toast.classList.toggle(
        'error',
        !!error
    );

    toast.classList.add(
        'show'
    );

    clearTimeout(
        window.pcToastTimer
    );

    window.pcToastTimer =
        setTimeout(
            function() {

                toast.classList.remove(
                    'show'
                );

            },
            3000
        );
}


/* =========================================================
   OPEN MODAL
========================================================= */

function openPcModal()
{
    document
        .getElementById(
            'pcModal'
        )
        .classList.add(
            'show'
        );
}


/* =========================================================
   CLOSE MODAL
========================================================= */

function closePcModal()
{
    document
        .getElementById(
            'pcModal'
        )
        .classList.remove(
            'show'
        );

    document
        .getElementById(
            'pcForm'
        )
        .reset();
}


/* =========================================================
   OUTSIDE CLICK
========================================================= */

document
    .getElementById(
        'pcModal'
    )
    .addEventListener(
        'click',
        function(event) {

            if (
                event.target === this
            ) {

                closePcModal();
            }

        }
    );


/* =========================================================
   ADD RELATIONSHIP
========================================================= */

async function submitPcRelation(
    event
) {

    event.preventDefault();

    const product =
        document.getElementById(
            'pcProduct'
        ).value;

    const category =
        document.getElementById(
            'pcCategory'
        ).value;

    const button =
        document.getElementById(
            'pcSave'
        );


    if (
        !product ||
        !category
    ) {

        pcToast(
            'Please select product and category.',
            true
        );

        return;
    }


    button.disabled =
        true;

    button.innerHTML =
        '<i class="fa-solid fa-spinner fa-spin"></i> Saving...';


    const body =
        new URLSearchParams();

    body.append(
        'action',
        'add'
    );

    body.append(
        'product_id',
        product
    );

    body.append(
        'category_id',
        category
    );

    body.append(
        'csrf_token',
        PC_CSRF
    );


    try {

        const response =
            await fetch(
                'product_categories.php',
                {
                    method: 'POST',

                    headers: {
                        'Content-Type':
                            'application/x-www-form-urlencoded'
                    },

                    body:
                        body.toString()
                }
            );


        const data =
            await response.json();


        if (
            !data.success
        ) {

            throw new Error(
                data.message ||
                'Unable to assign category.'
            );
        }


        pcToast(
            data.message,
            false
        );


        closePcModal();


        setTimeout(
            function() {

                window.location.reload();

            },
            600
        );


    } catch (error) {

        pcToast(
            error.message ||
            'Something went wrong.',
            true
        );


    } finally {

        button.disabled =
            false;

        button.innerHTML =
            '<i class="fa-solid fa-link"></i> Assign Category';
    }
}


/* =========================================================
   REMOVE RELATIONSHIP
========================================================= */

async function removePcRelation(
    productId,
    categoryId,
    button
) {


    if (
        !confirm(
            'Are you sure you want to remove this category from the product?'
        )
    ) {

        return;
    }


    const original =
        button.innerHTML;


    button.disabled =
        true;

    button.innerHTML =
        '<i class="fa-solid fa-spinner fa-spin"></i>';


    const body =
        new URLSearchParams();

    body.append(
        'action',
        'remove'
    );

    body.append(
        'product_id',
        productId
    );

    body.append(
        'category_id',
        categoryId
    );

    body.append(
        'csrf_token',
        PC_CSRF
    );


    try {

        const response =
            await fetch(
                'product_categories.php',
                {
                    method: 'POST',

                    headers: {
                        'Content-Type':
                            'application/x-www-form-urlencoded'
                    },

                    body:
                        body.toString()
                }
            );


        const data =
            await response.json();


        if (
            !data.success
        ) {

            throw new Error(
                data.message ||
                'Unable to remove category.'
            );
        }


        const row =
            document.getElementById(
                'pc-row-' +
                productId +
                '-' +
                categoryId
            );


        if (row) {

            row.style.transition =
                'opacity .2s, transform .2s';

            row.style.opacity =
                '0';

            row.style.transform =
                'translateX(10px)';


            setTimeout(
                function() {

                    row.remove();

                    const remaining =
                        document.querySelectorAll(
                            '.pc-table tbody tr'
                        );


                    if (
                        remaining.length === 0
                    ) {

                        window.location.reload();
                    }

                },
                220
            );
        }


        pcToast(
            data.message,
            false
        );


    } catch (error) {

        button.disabled =
            false;

        button.innerHTML =
            original;


        pcToast(
            error.message ||
            'Something went wrong.',
            true
        );
    }
}


/* =========================================================
   ESC
========================================================= */

document.addEventListener(
    'keydown',
    function(event) {

        if (
            event.key === 'Escape'
        ) {

            closePcModal();
        }

    }
);

</script>


<?php

/* =========================================================
   LOAD ADMIN FOOTER
========================================================= */

if (
    file_exists(
        __DIR__ . '/footer.php'
    )
) {

    require_once
        __DIR__ . '/footer.php';

} elseif (
    file_exists(
        __DIR__ . '/footer.php'
    )
) {

    require_once
        __DIR__ . '/footer.php';

} else {

    exit(
        'Admin footer file not found. Expected admin/footer.php'
    );
}

?>

