<?php
/**
 * Pure Chemical Admin
 * File: admin/industry_products.php
 *
 * Existing table used:
 * industry_products
 * - industry_id
 * - product_id
 * - sort_order
 *
 * IMPORTANT:
 * admin/sidebar.php is included separately.
 * admin/includes/header.php is NOT included.
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

/* -----------------------------------------------------------
   AUTH
----------------------------------------------------------- */
if (function_exists('requireAdmin')) {
    requireAdmin();
} else {
    if (
        empty($_SESSION['admin_id']) &&
        empty($_SESSION['admin_logged_in'])
    ) {
        header('Location: login.php');
        exit;
    }
}

/* -----------------------------------------------------------
   HELPERS
----------------------------------------------------------- */
if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('redirect_self')) {
    function redirect_self($params = [])
    {
        $url = basename($_SERVER['PHP_SELF']);

        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }

        header('Location: ' . $url);
        exit;
    }
}

/* -----------------------------------------------------------
   CSRF
----------------------------------------------------------- */
if (empty($_SESSION['industry_products_csrf'])) {
    $_SESSION['industry_products_csrf'] = bin2hex(random_bytes(32));
}

$csrfToken = $_SESSION['industry_products_csrf'];

function verifyIndustryProductsCsrf()
{
    global $csrfToken;

    $token = $_POST['csrf_token'] ?? '';

    if (
        !$token ||
        !hash_equals($csrfToken, $token)
    ) {
        http_response_code(419);
        exit('Invalid or expired security token.');
    }
}

/* -----------------------------------------------------------
   FLASH MESSAGE
----------------------------------------------------------- */
$success = $_SESSION['industry_products_success'] ?? '';
$error   = $_SESSION['industry_products_error'] ?? '';

unset($_SESSION['industry_products_success']);
unset($_SESSION['industry_products_error']);

/* -----------------------------------------------------------
   GET INDUSTRIES
----------------------------------------------------------- */
$industries = [];

try {
    $stmt = $pdo->query("
        SELECT
            id,
            name,
            slug,
            status
        FROM industries
        ORDER BY sort_order ASC, name ASC
    ");

    $industries = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $error = 'Unable to load industries.';
}

/* -----------------------------------------------------------
   GET PRODUCTS
   We use SELECT * so this page does not depend on unknown
   optional product columns.
----------------------------------------------------------- */
$products = [];
$productMap = [];

try {
    $stmt = $pdo->query("
        SELECT *
        FROM products
        ORDER BY id DESC
    ");

    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($products as $product) {
        if (!isset($product['id'])) {
            continue;
        }

        $productId = (int)$product['id'];

        $displayName = '';

        $possibleNameFields = [
            'name',
            'title',
            'product_name',
            'product_title',
            'sku'
        ];

        foreach ($possibleNameFields as $field) {
            if (
                isset($product[$field]) &&
                trim((string)$product[$field]) !== ''
            ) {
                $displayName = trim((string)$product[$field]);
                break;
            }
        }

        if ($displayName === '') {
            $displayName = 'Product #' . $productId;
        }

        $productMap[$productId] = [
            'id'   => $productId,
            'name' => $displayName,
            'sku'  => isset($product['sku']) ? trim((string)$product['sku']) : ''
        ];
    }
} catch (Throwable $e) {
    $error = 'Unable to load products.';
}

/* -----------------------------------------------------------
   ADD / UPDATE / DELETE
----------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $action = $_POST['action'] ?? '';

    try {

        verifyIndustryProductsCsrf();

        /* ---------------------------------------------------
           SAVE
        --------------------------------------------------- */
        if ($action === 'save') {

            $industryId = filter_input(
                INPUT_POST,
                'industry_id',
                FILTER_VALIDATE_INT
            );

            $productId = filter_input(
                INPUT_POST,
                'product_id',
                FILTER_VALIDATE_INT
            );

            $sortOrder = filter_input(
                INPUT_POST,
                'sort_order',
                FILTER_VALIDATE_INT
            );

            $editIndustryId = filter_input(
                INPUT_POST,
                'edit_industry_id',
                FILTER_VALIDATE_INT
            );

            $editProductId = filter_input(
                INPUT_POST,
                'edit_product_id',
                FILTER_VALIDATE_INT
            );

            if (!$industryId || $industryId < 1) {
                throw new Exception('Please select an industry.');
            }

            if (!$productId || $productId < 1) {
                throw new Exception('Please select a product.');
            }

            if ($sortOrder === false || $sortOrder === null) {
                $sortOrder = 0;
            }

            if ($sortOrder < 0) {
                throw new Exception('Sort order cannot be negative.');
            }

            /* ------------------------------------------------
               VERIFY INDUSTRY EXISTS
            ------------------------------------------------ */
            $stmt = $pdo->prepare("
                SELECT id
                FROM industries
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([$industryId]);

            if (!$stmt->fetchColumn()) {
                throw new Exception('Selected industry does not exist.');
            }

            /* ------------------------------------------------
               VERIFY PRODUCT EXISTS
            ------------------------------------------------ */
            $stmt = $pdo->prepare("
                SELECT id
                FROM products
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([$productId]);

            if (!$stmt->fetchColumn()) {
                throw new Exception('Selected product does not exist.');
            }

            /* ------------------------------------------------
               UPDATE
            ------------------------------------------------ */
            if ($editIndustryId && $editProductId) {

                /* Check whether original mapping exists */
                $stmt = $pdo->prepare("
                    SELECT industry_id, product_id
                    FROM industry_products
                    WHERE industry_id = ?
                      AND product_id = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $editIndustryId,
                    $editProductId
                ]);

                $existing = $stmt->fetch(PDO::FETCH_ASSOC);

                if (!$existing) {
                    throw new Exception(
                        'The mapping you are trying to edit no longer exists.'
                    );
                }

                /* Prevent duplicate mapping */
                $stmt = $pdo->prepare("
                    SELECT industry_id
                    FROM industry_products
                    WHERE industry_id = ?
                      AND product_id = ?
                      AND NOT (
                          industry_id = ?
                          AND product_id = ?
                      )
                    LIMIT 1
                ");

                $stmt->execute([
                    $industryId,
                    $productId,
                    $editIndustryId,
                    $editProductId
                ]);

                if ($stmt->fetchColumn()) {
                    throw new Exception(
                        'This product is already assigned to this industry.'
                    );
                }

                $stmt = $pdo->prepare("
                    UPDATE industry_products
                    SET
                        industry_id = ?,
                        product_id = ?,
                        sort_order = ?
                    WHERE industry_id = ?
                      AND product_id = ?
                    LIMIT 1
                ");

                $stmt->execute([
                    $industryId,
                    $productId,
                    $sortOrder,
                    $editIndustryId,
                    $editProductId
                ]);

                $_SESSION['industry_products_success'] =
                    'Industry product mapping updated successfully.';

                redirect_self();
            }

            /* ------------------------------------------------
               INSERT
            ------------------------------------------------ */
            $stmt = $pdo->prepare("
                SELECT industry_id
                FROM industry_products
                WHERE industry_id = ?
                  AND product_id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $industryId,
                $productId
            ]);

            if ($stmt->fetchColumn()) {
                throw new Exception(
                    'This product is already assigned to this industry.'
                );
            }

            $stmt = $pdo->prepare("
                INSERT INTO industry_products
                (
                    industry_id,
                    product_id,
                    sort_order
                )
                VALUES
                (
                    ?,
                    ?,
                    ?
                )
            ");

            $stmt->execute([
                $industryId,
                $productId,
                $sortOrder
            ]);

            $_SESSION['industry_products_success'] =
                'Product assigned to industry successfully.';

            redirect_self();
        }

        /* ---------------------------------------------------
           DELETE
        --------------------------------------------------- */
        if ($action === 'delete') {

            $industryId = filter_input(
                INPUT_POST,
                'industry_id',
                FILTER_VALIDATE_INT
            );

            $productId = filter_input(
                INPUT_POST,
                'product_id',
                FILTER_VALIDATE_INT
            );

            if (!$industryId || !$productId) {
                throw new Exception('Invalid mapping selected.');
            }

            $stmt = $pdo->prepare("
                DELETE FROM industry_products
                WHERE industry_id = ?
                  AND product_id = ?
                LIMIT 1
            ");

            $stmt->execute([
                $industryId,
                $productId
            ]);

            if ($stmt->rowCount() < 1) {
                throw new Exception(
                    'Mapping not found or already deleted.'
                );
            }

            $_SESSION['industry_products_success'] =
                'Industry product mapping deleted successfully.';

            redirect_self();
        }

    } catch (Throwable $e) {

        $_SESSION['industry_products_error'] =
            $e->getMessage();

        redirect_self();
    }
}

/* -----------------------------------------------------------
   EDIT DATA
----------------------------------------------------------- */
$editIndustryId = filter_input(
    INPUT_GET,
    'edit_industry_id',
    FILTER_VALIDATE_INT
);

$editProductId = filter_input(
    INPUT_GET,
    'edit_product_id',
    FILTER_VALIDATE_INT
);

$editData = null;

if ($editIndustryId && $editProductId) {

    try {

        $stmt = $pdo->prepare("
            SELECT
                industry_id,
                product_id,
                sort_order
            FROM industry_products
            WHERE industry_id = ?
              AND product_id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $editIndustryId,
            $editProductId
        ]);

        $editData = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$editData) {
            $editIndustryId = null;
            $editProductId = null;
        }

    } catch (Throwable $e) {
        $error = 'Unable to load mapping for editing.';
    }
}

/* -----------------------------------------------------------
   FILTERS
----------------------------------------------------------- */
$search = trim($_GET['search'] ?? '');

$filterIndustry = filter_input(
    INPUT_GET,
    'industry_id',
    FILTER_VALIDATE_INT
);

$filterIndustry = $filterIndustry ?: 0;

/* -----------------------------------------------------------
   PAGINATION
----------------------------------------------------------- */
$page = filter_input(
    INPUT_GET,
    'page',
    FILTER_VALIDATE_INT
);

$page = $page && $page > 0 ? $page : 1;

$perPage = 12;

$where = [];
$params = [];

/* Industry filter */
if ($filterIndustry > 0) {
    $where[] = 'ip.industry_id = ?';
    $params[] = $filterIndustry;
}

/* Search */
if ($search !== '') {

    $where[] = "
        (
            i.name LIKE ?
            OR CAST(ip.product_id AS CHAR) LIKE ?
            OR CAST(ip.industry_id AS CHAR) LIKE ?
        )
    ";

    $searchLike = '%' . $search . '%';

    $params[] = $searchLike;
    $params[] = $searchLike;
    $params[] = $searchLike;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

/* -----------------------------------------------------------
   TOTAL
----------------------------------------------------------- */
$totalRows = 0;

try {

    $countSql = "
        SELECT COUNT(*)
        FROM industry_products ip
        INNER JOIN industries i
            ON i.id = ip.industry_id
        $whereSql
    ";

    $stmt = $pdo->prepare($countSql);
    $stmt->execute($params);

    $totalRows = (int)$stmt->fetchColumn();

} catch (Throwable $e) {
    $error = 'Unable to count industry products.';
}

$totalPages = max(
    1,
    (int)ceil($totalRows / $perPage)
);

if ($page > $totalPages) {
    $page = $totalPages;
}

$offset = ($page - 1) * $perPage;

/* -----------------------------------------------------------
   FETCH MAPPINGS
----------------------------------------------------------- */
$rows = [];

try {

    $sql = "
        SELECT
            ip.industry_id,
            ip.product_id,
            ip.sort_order,
            i.name AS industry_name,
            i.slug AS industry_slug
        FROM industry_products ip
        INNER JOIN industries i
            ON i.id = ip.industry_id
        $whereSql
        ORDER BY
            ip.sort_order ASC,
            i.name ASC,
            ip.product_id DESC
        LIMIT $perPage OFFSET $offset
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {
    $error = 'Unable to load industry product mappings.';
}

/* -----------------------------------------------------------
   STATISTICS
----------------------------------------------------------- */
$totalMappings = 0;
$totalIndustriesUsed = 0;
$totalProductsUsed = 0;

try {

    $totalMappings = (int)$pdo
        ->query("SELECT COUNT(*) FROM industry_products")
        ->fetchColumn();

    $totalIndustriesUsed = (int)$pdo
        ->query("
            SELECT COUNT(DISTINCT industry_id)
            FROM industry_products
        ")
        ->fetchColumn();

    $totalProductsUsed = (int)$pdo
        ->query("
            SELECT COUNT(DISTINCT product_id)
            FROM industry_products
        ")
        ->fetchColumn();

} catch (Throwable $e) {
    /* Statistics are optional */
}

/* -----------------------------------------------------------
   ADMIN NAME
----------------------------------------------------------- */
$adminName =
    $_SESSION['ADMIN_NAME']
    ?? $_SESSION['admin_name']
    ?? 'Administrator';

$adminInitial =
    strtoupper(
        substr(
            trim($adminName),
            0,
            1
        )
    );

if ($adminInitial === '') {
    $adminInitial = 'A';
}

?>
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>Industry Products | Pure Chemical Admin</title>

    <meta
        name="robots"
        content="noindex,nofollow"
    >

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {
            --pc-primary: #0f766e;
            --pc-primary-dark: #115e59;
            --pc-primary-soft: #ecfdf5;

            --pc-bg: #f5f7fb;
            --pc-card: #ffffff;
            --pc-border: #e7eaf0;

            --pc-text: #111827;
            --pc-muted: #6b7280;

            --pc-success: #059669;
            --pc-success-bg: #ecfdf5;

            --pc-danger: #dc2626;
            --pc-danger-bg: #fef2f2;

            --pc-warning: #d97706;
            --pc-warning-bg: #fffbeb;

            --pc-shadow:
                0 15px 45px rgba(15, 23, 42, .07);

            --pc-radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            background: var(--pc-bg);
            color: var(--pc-text);
            font-family: "Inter", sans-serif;
            font-size: 14px;
        }

        a {
            text-decoration: none;
            color: inherit;
        }

        button,
        input,
        select {
            font-family: inherit;
        }

        /* ---------------------------------------------------
           MAIN WRAPPER
        --------------------------------------------------- */

        .pc-page {
            margin-left: 280px;
            min-height: 100vh;
        }

        .pc-container {
            width: min(1500px, calc(100% - 48px));
            margin: 0 auto;
            padding: 24px 0 50px;
        }

        /* ---------------------------------------------------
           TOPBAR
        --------------------------------------------------- */

        .pc-topbar {
            position: sticky;
            top: 0;
            z-index: 50;

            height: 76px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 0 28px;

            background: rgba(255, 255, 255, .92);
            border-bottom: 1px solid var(--pc-border);

            backdrop-filter: blur(18px);
        }

        .pc-topbar-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .pc-mobile-menu {
            display: none;

            width: 42px;
            height: 42px;

            border: 1px solid var(--pc-border);
            border-radius: 12px;

            background: #fff;
            cursor: pointer;
        }

        .pc-page-title {
            margin: 0;
            font-size: 19px;
            font-weight: 800;
            letter-spacing: -.4px;
        }

        .pc-breadcrumb {
            margin-top: 4px;
            color: var(--pc-muted);
            font-size: 12px;
        }

        .pc-topbar-right {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .pc-dashboard-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;

            padding: 10px 14px;

            border: 1px solid var(--pc-border);
            border-radius: 12px;

            background: #fff;

            font-size: 13px;
            font-weight: 700;

            transition: .2s ease;
        }

        .pc-dashboard-btn:hover {
            border-color: #cbd5e1;
            transform: translateY(-1px);
        }

        .pc-admin {
            display: flex;
            align-items: center;
            gap: 10px;
            padding-left: 8px;
        }

        .pc-avatar {
            width: 40px;
            height: 40px;

            display: grid;
            place-items: center;

            border-radius: 13px;

            background:
                linear-gradient(
                    135deg,
                    var(--pc-primary),
                    #14b8a6
                );

            color: #fff;

            font-weight: 800;
        }

        .pc-admin-name {
            font-weight: 700;
            font-size: 13px;
        }

        .pc-admin-role {
            margin-top: 2px;
            color: var(--pc-muted);
            font-size: 11px;
        }

        /* ---------------------------------------------------
           PAGE HERO
        --------------------------------------------------- */

        .pc-hero {
            display: flex;
            align-items: flex-end;
            justify-content: space-between;
            gap: 25px;

            margin-bottom: 22px;
        }

        .pc-eyebrow {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            padding: 7px 11px;

            border-radius: 999px;

            background: var(--pc-primary-soft);
            color: var(--pc-primary-dark);

            font-size: 11px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: .7px;
        }

        .pc-hero h1 {
            margin: 13px 0 7px;

            font-size: 29px;
            line-height: 1.15;

            letter-spacing: -.8px;
        }

        .pc-hero p {
            margin: 0;

            max-width: 700px;

            color: var(--pc-muted);
            line-height: 1.6;
        }

        /* ---------------------------------------------------
           STATS
        --------------------------------------------------- */

        .pc-stats {
            display: grid;
            grid-template-columns:
                repeat(3, minmax(0, 1fr));

            gap: 16px;

            margin-bottom: 22px;
        }

        .pc-stat {
            position: relative;
            overflow: hidden;

            padding: 20px;

            background: var(--pc-card);
            border: 1px solid var(--pc-border);
            border-radius: var(--pc-radius);

            box-shadow: var(--pc-shadow);
        }

        .pc-stat::after {
            content: "";

            position: absolute;

            width: 90px;
            height: 90px;

            right: -30px;
            top: -35px;

            border-radius: 50%;

            background: var(--pc-primary-soft);
        }

        .pc-stat-icon {
            width: 43px;
            height: 43px;

            display: grid;
            place-items: center;

            border-radius: 13px;

            background: var(--pc-primary-soft);
            color: var(--pc-primary);

            margin-bottom: 14px;
        }

        .pc-stat-value {
            font-size: 27px;
            font-weight: 800;
            letter-spacing: -.6px;
        }

        .pc-stat-label {
            margin-top: 4px;
            color: var(--pc-muted);
            font-size: 12px;
            font-weight: 600;
        }

        /* ---------------------------------------------------
           ALERT
        --------------------------------------------------- */

        .pc-alert {
            display: flex;
            align-items: flex-start;
            gap: 12px;

            padding: 15px 17px;

            margin-bottom: 18px;

            border-radius: 14px;

            font-size: 13px;
            line-height: 1.5;
        }

        .pc-alert.success {
            background: var(--pc-success-bg);
            border: 1px solid #a7f3d0;
            color: #065f46;
        }

        .pc-alert.error {
            background: var(--pc-danger-bg);
            border: 1px solid #fecaca;
            color: #991b1b;
        }

        /* ---------------------------------------------------
           GRID
        --------------------------------------------------- */

        .pc-grid {
            display: grid;
            grid-template-columns: 380px minmax(0, 1fr);
            gap: 20px;
            align-items: start;
        }

        .pc-card {
            background: var(--pc-card);
            border: 1px solid var(--pc-border);
            border-radius: var(--pc-radius);
            box-shadow: var(--pc-shadow);
        }

        .pc-card-header {
            padding: 20px 22px;

            border-bottom: 1px solid var(--pc-border);

            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
        }

        .pc-card-title {
            margin: 0;
            font-size: 15px;
            font-weight: 800;
        }

        .pc-card-subtitle {
            margin: 4px 0 0;

            color: var(--pc-muted);

            font-size: 12px;
            line-height: 1.5;
        }

        .pc-card-body {
            padding: 22px;
        }

        /* ---------------------------------------------------
           FORM
        --------------------------------------------------- */

        .pc-form-group {
            margin-bottom: 17px;
        }

        .pc-label {
            display: block;

            margin-bottom: 8px;

            color: #374151;

            font-size: 12px;
            font-weight: 800;
        }

        .pc-required {
            color: var(--pc-danger);
        }

        .pc-input,
        .pc-select {
            width: 100%;

            min-height: 45px;

            padding: 0 13px;

            border: 1px solid #dfe3ea;
            border-radius: 12px;

            background: #fff;

            color: var(--pc-text);

            outline: none;

            font-size: 13px;

            transition: .2s ease;
        }

        .pc-input:focus,
        .pc-select:focus {
            border-color: var(--pc-primary);
            box-shadow:
                0 0 0 4px
                rgba(15, 118, 110, .09);
        }

        .pc-help {
            margin-top: 7px;

            color: var(--pc-muted);

            font-size: 11px;
            line-height: 1.5;
        }

        .pc-form-actions {
            display: flex;
            gap: 9px;
            margin-top: 22px;
        }

        .pc-btn {
            min-height: 43px;

            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;

            padding: 0 15px;

            border-radius: 11px;
            border: 1px solid transparent;

            cursor: pointer;

            font-size: 12px;
            font-weight: 800;

            transition: .2s ease;
        }

        .pc-btn:hover {
            transform: translateY(-1px);
        }

        .pc-btn-primary {
            background: var(--pc-primary);
            color: #fff;
            box-shadow:
                0 8px 20px rgba(15, 118, 110, .18);
        }

        .pc-btn-primary:hover {
            background: var(--pc-primary-dark);
        }

        .pc-btn-light {
            background: #fff;
            border-color: var(--pc-border);
            color: #374151;
        }

        .pc-btn-danger {
            background: var(--pc-danger-bg);
            color: var(--pc-danger);
            border-color: #fecaca;
        }

        /* ---------------------------------------------------
           FILTER
        --------------------------------------------------- */

        .pc-filter {
            padding: 16px 18px;

            background: #fbfcfe;

            border-bottom: 1px solid var(--pc-border);
        }

        .pc-filter-form {
            display: grid;

            grid-template-columns:
                minmax(180px, 1fr)
                210px
                auto;

            gap: 10px;
        }

        .pc-search-wrap {
            position: relative;
        }

        .pc-search-wrap i {
            position: absolute;

            left: 14px;
            top: 50%;

            transform: translateY(-50%);

            color: #9ca3af;
        }

        .pc-search-wrap .pc-input {
            padding-left: 39px;
        }

        /* ---------------------------------------------------
           TABLE
        --------------------------------------------------- */

        .pc-table-wrap {
            overflow-x: auto;
        }

        .pc-table {
            width: 100%;
            border-collapse: collapse;
        }

        .pc-table th {
            padding: 14px 18px;

            background: #fafbfc;

            border-bottom: 1px solid var(--pc-border);

            color: #6b7280;

            text-align: left;

            font-size: 10px;
            font-weight: 800;

            text-transform: uppercase;
            letter-spacing: .7px;

            white-space: nowrap;
        }

        .pc-table td {
            padding: 16px 18px;

            border-bottom: 1px solid #eef0f4;

            vertical-align: middle;
        }

        .pc-table tbody tr {
            transition: .15s ease;
        }

        .pc-table tbody tr:hover {
            background: #fbfdfd;
        }

        .pc-industry {
            display: flex;
            align-items: center;
            gap: 11px;
        }

        .pc-industry-icon {
            width: 38px;
            height: 38px;

            flex: 0 0 38px;

            display: grid;
            place-items: center;

            border-radius: 11px;

            background: var(--pc-primary-soft);
            color: var(--pc-primary);
        }

        .pc-industry-name {
            font-size: 13px;
            font-weight: 800;
        }

        .pc-industry-slug {
            margin-top: 3px;

            color: var(--pc-muted);

            font-size: 10px;
        }

        .pc-product {
            display: inline-flex;
            align-items: center;
            gap: 8px;

            padding: 8px 10px;

            background: #f8fafc;
            border: 1px solid #edf0f4;

            border-radius: 9px;

            color: #374151;

            font-size: 12px;
            font-weight: 700;
        }

        .pc-product-id {
            color: var(--pc-primary);
            font-weight: 800;
        }

        .pc-order {
            display: inline-flex;
            align-items: center;
            justify-content: center;

            min-width: 34px;
            height: 30px;

            padding: 0 8px;

            border-radius: 9px;

            background: #f3f4f6;

            font-size: 12px;
            font-weight: 800;
        }

        .pc-actions {
            display: flex;
            justify-content: flex-end;
            gap: 7px;
        }

        .pc-icon-btn {
            width: 35px;
            height: 35px;

            display: inline-grid;
            place-items: center;

            border-radius: 9px;

            border: 1px solid var(--pc-border);

            background: #fff;

            color: #4b5563;

            cursor: pointer;

            transition: .2s ease;
        }

        .pc-icon-btn:hover {
            border-color: #cbd5e1;
            transform: translateY(-1px);
        }

        .pc-icon-btn.delete {
            color: var(--pc-danger);
            background: var(--pc-danger-bg);
            border-color: #fecaca;
        }

        /* ---------------------------------------------------
           EMPTY
        --------------------------------------------------- */

        .pc-empty {
            padding: 55px 20px;
            text-align: center;
        }

        .pc-empty-icon {
            width: 58px;
            height: 58px;

            display: grid;
            place-items: center;

            margin: 0 auto 14px;

            border-radius: 17px;

            background: var(--pc-primary-soft);
            color: var(--pc-primary);

            font-size: 21px;
        }

        .pc-empty h3 {
            margin: 0 0 6px;

            font-size: 15px;
        }

        .pc-empty p {
            margin: 0;

            color: var(--pc-muted);

            font-size: 12px;
        }

        /* ---------------------------------------------------
           PAGINATION
        --------------------------------------------------- */

        .pc-pagination {
            display: flex;
            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding: 16px 18px;
        }

        .pc-page-info {
            color: var(--pc-muted);
            font-size: 11px;
            font-weight: 600;
        }

        .pc-pages {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .pc-page-btn {
            min-width: 34px;
            height: 34px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            padding: 0 8px;

            border: 1px solid var(--pc-border);
            border-radius: 9px;

            background: #fff;

            color: #4b5563;

            font-size: 11px;
            font-weight: 800;
        }

        .pc-page-btn.active {
            background: var(--pc-primary);
            border-color: var(--pc-primary);
            color: #fff;
        }

        .pc-page-btn.disabled {
            opacity: .45;
            pointer-events: none;
        }

        /* ---------------------------------------------------
           NOTICE
        --------------------------------------------------- */

        .pc-notice {
            display: flex;
            align-items: flex-start;
            gap: 10px;

            padding: 13px;

            margin-top: 16px;

            border-radius: 12px;

            background: var(--pc-warning-bg);
            border: 1px solid #fde68a;

            color: #92400e;

            font-size: 11px;
            line-height: 1.5;
        }

        /* ---------------------------------------------------
           RESPONSIVE
        --------------------------------------------------- */

        @media (max-width: 1200px) {

            .pc-grid {
                grid-template-columns: 330px minmax(0, 1fr);
            }

            .pc-container {
                width: min(100% - 32px, 1400px);
            }
        }

        @media (max-width: 1050px) {

            .pc-page {
                margin-left: 0;
            }

            .pc-mobile-menu {
                display: inline-grid;
                place-items: center;
            }

            .pc-grid {
                grid-template-columns: 1fr;
            }

            .pc-stats {
                grid-template-columns: repeat(3, 1fr);
            }
        }

        @media (max-width: 760px) {

            .pc-topbar {
                padding: 0 15px;
            }

            .pc-admin-name,
            .pc-admin-role {
                display: none;
            }

            .pc-dashboard-btn span {
                display: none;
            }

            .pc-container {
                width: calc(100% - 24px);
                padding-top: 18px;
            }

            .pc-hero {
                align-items: flex-start;
                flex-direction: column;
            }

            .pc-hero h1 {
                font-size: 24px;
            }

            .pc-stats {
                grid-template-columns: 1fr;
            }

            .pc-filter-form {
                grid-template-columns: 1fr;
            }

            .pc-card-body {
                padding: 17px;
            }

            .pc-pagination {
                align-items: flex-start;
                flex-direction: column;
            }
        }

        @media (max-width: 520px) {

            .pc-topbar {
                height: 68px;
            }

            .pc-page-title {
                font-size: 15px;
            }

            .pc-breadcrumb {
                display: none;
            }

            .pc-topbar-right {
                gap: 6px;
            }

            .pc-avatar {
                width: 36px;
                height: 36px;
            }

            .pc-hero h1 {
                font-size: 22px;
            }

            .pc-form-actions {
                flex-direction: column;
            }

            .pc-form-actions .pc-btn {
                width: 100%;
            }
        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| SEPARATE SIDEBAR
|--------------------------------------------------------------------------
|
| User requirement:
| admin/sidebar.php separately include.
|
*/
require_once __DIR__ . '/sidebar.php';
?>

<div class="pc-page">

    <!-- =====================================================
         TOPBAR
    ====================================================== -->

    <header class="pc-topbar">

        <div class="pc-topbar-left">

            <button
                type="button"
                class="pc-mobile-menu"
                onclick="toggleSidebar()"
                aria-label="Toggle sidebar"
            >
                <i class="fa-solid fa-bars"></i>
            </button>

            <div>
                <h2 class="pc-page-title">
                    Industry Products
                </h2>

                <div class="pc-breadcrumb">
                    Admin / Industries / Product Mapping
                </div>
            </div>

        </div>

        <div class="pc-topbar-right">

            <a
                href="index.php"
                class="pc-dashboard-btn"
            >
                <i class="fa-solid fa-gauge-high"></i>
                <span>Dashboard</span>
            </a>

            <div class="pc-admin">

                <div class="pc-avatar">
                    <?= e($adminInitial) ?>
                </div>

                <div>
                    <div class="pc-admin-name">
                        <?= e($adminName) ?>
                    </div>

                    <div class="pc-admin-role">
                        Administrator
                    </div>
                </div>

            </div>

        </div>

    </header>


    <!-- =====================================================
         MAIN
    ====================================================== -->

    <main class="pc-container">

        <!-- HERO -->

        <section class="pc-hero">

            <div>

                <span class="pc-eyebrow">
                    <i class="fa-solid fa-link"></i>
                    Industry Mapping
                </span>

                <h1>
                    Industry Products
                </h1>

                <p>
                    Products ko industries ke saath map karein aur
                    frontend par industry-wise products ko control karein.
                </p>

            </div>

        </section>


        <!-- =================================================
             FLASH MESSAGES
        ================================================== -->

        <?php if ($success): ?>

            <div class="pc-alert success">

                <i class="fa-solid fa-circle-check"></i>

                <div>
                    <?= e($success) ?>
                </div>

            </div>

        <?php endif; ?>


        <?php if ($error): ?>

            <div class="pc-alert error">

                <i class="fa-solid fa-triangle-exclamation"></i>

                <div>
                    <?= e($error) ?>
                </div>

            </div>

        <?php endif; ?>


        <!-- =================================================
             STATISTICS
        ================================================== -->

        <section class="pc-stats">

            <div class="pc-stat">

                <div class="pc-stat-icon">
                    <i class="fa-solid fa-link"></i>
                </div>

                <div class="pc-stat-value">
                    <?= number_format($totalMappings) ?>
                </div>

                <div class="pc-stat-label">
                    Total Product Mappings
                </div>

            </div>


            <div class="pc-stat">

                <div class="pc-stat-icon">
                    <i class="fa-solid fa-industry"></i>
                </div>

                <div class="pc-stat-value">
                    <?= number_format($totalIndustriesUsed) ?>
                </div>

                <div class="pc-stat-label">
                    Industries With Products
                </div>

            </div>


            <div class="pc-stat">

                <div class="pc-stat-icon">
                    <i class="fa-solid fa-boxes-stacked"></i>
                </div>

                <div class="pc-stat-value">
                    <?= number_format($totalProductsUsed) ?>
                </div>

                <div class="pc-stat-label">
                    Unique Products Used
                </div>

            </div>

        </section>


        <!-- =================================================
             MAIN GRID
        ================================================== -->

        <section class="pc-grid">


            <!-- =============================================
                 ADD / EDIT FORM
            ============================================== -->

            <div class="pc-card">

                <div class="pc-card-header">

                    <div>

                        <h3 class="pc-card-title">

                            <?php if ($editData): ?>

                                Edit Mapping

                            <?php else: ?>

                                Assign Product

                            <?php endif; ?>

                        </h3>

                        <p class="pc-card-subtitle">
                            Industry ke saath product relation manage karein.
                        </p>

                    </div>

                </div>


                <div class="pc-card-body">

                    <?php if (empty($industries)): ?>

                        <div class="pc-notice">

                            <i class="fa-solid fa-circle-info"></i>

                            <div>
                                Pehle
                                <strong>Industries</strong>
                                mein kam se kam ek industry create karein.
                            </div>

                        </div>

                    <?php endif; ?>


                    <?php if (empty($products)): ?>

                        <div class="pc-notice">

                            <i class="fa-solid fa-circle-info"></i>

                            <div>
                                Pehle
                                <strong>Products</strong>
                                mein product create karein.
                            </div>

                        </div>

                    <?php endif; ?>


                    <form
                        method="POST"
                        action="<?= e(basename($_SERVER['PHP_SELF'])) ?>"
                    >

                        <input
                            type="hidden"
                            name="csrf_token"
                            value="<?= e($csrfToken) ?>"
                        >

                        <input
                            type="hidden"
                            name="action"
                            value="save"
                        >


                        <?php if ($editData): ?>

                            <input
                                type="hidden"
                                name="edit_industry_id"
                                value="<?= (int)$editData['industry_id'] ?>"
                            >

                            <input
                                type="hidden"
                                name="edit_product_id"
                                value="<?= (int)$editData['product_id'] ?>"
                            >

                        <?php endif; ?>


                        <!-- INDUSTRY -->

                        <div class="pc-form-group">

                            <label
                                class="pc-label"
                                for="industry_id"
                            >
                                Industry
                                <span class="pc-required">*</span>
                            </label>

                            <select
                                name="industry_id"
                                id="industry_id"
                                class="pc-select"
                                required
                            >

                                <option value="">
                                    Select Industry
                                </option>

                                <?php foreach ($industries as $industry): ?>

                                    <option
                                        value="<?= (int)$industry['id'] ?>"
                                        <?= (
                                            (int)($editData['industry_id'] ?? 0)
                                            === (int)$industry['id']
                                        ) ? 'selected' : '' ?>
                                    >
                                        <?= e($industry['name']) ?>
                                        — #<?= (int)$industry['id'] ?>
                                    </option>

                                <?php endforeach; ?>

                            </select>

                        </div>


                        <!-- PRODUCT -->

                        <div class="pc-form-group">

                            <label
                                class="pc-label"
                                for="product_id"
                            >
                                Product
                                <span class="pc-required">*</span>
                            </label>

                            <select
                                name="product_id"
                                id="product_id"
                                class="pc-select"
                                required
                            >

                                <option value="">
                                    Select Product
                                </option>

                                <?php foreach ($productMap as $product): ?>

                                    <option
                                        value="<?= (int)$product['id'] ?>"
                                        <?= (
                                            (int)($editData['product_id'] ?? 0)
                                            === (int)$product['id']
                                        ) ? 'selected' : '' ?>
                                    >
                                        <?= e($product['name']) ?>

                                        <?php if ($product['sku'] !== ''): ?>

                                            — SKU:
                                            <?= e($product['sku']) ?>

                                        <?php endif; ?>

                                        — #<?= (int)$product['id'] ?>

                                    </option>

                                <?php endforeach; ?>

                            </select>

                            <div class="pc-help">
                                Existing products table se product select hoga.
                            </div>

                        </div>


                        <!-- SORT ORDER -->

                        <div class="pc-form-group">

                            <label
                                class="pc-label"
                                for="sort_order"
                            >
                                Sort Order
                            </label>

                            <input
                                type="number"
                                name="sort_order"
                                id="sort_order"
                                class="pc-input"
                                min="0"
                                step="1"
                                value="<?= e($editData['sort_order'] ?? 0) ?>"
                            >

                            <div class="pc-help">
                                Lower number frontend listing mein pehle show hoga.
                            </div>

                        </div>


                        <!-- ACTIONS -->

                        <div class="pc-form-actions">

                            <button
                                type="submit"
                                class="pc-btn pc-btn-primary"
                                <?= (
                                    empty($industries)
                                    || empty($products)
                                ) ? 'disabled' : '' ?>
                            >

                                <i class="fa-solid fa-floppy-disk"></i>

                                <?php if ($editData): ?>
                                    Update Mapping
                                <?php else: ?>
                                    Assign Product
                                <?php endif; ?>

                            </button>


                            <?php if ($editData): ?>

                                <a
                                    href="<?= e(basename($_SERVER['PHP_SELF'])) ?>"
                                    class="pc-btn pc-btn-light"
                                >
                                    <i class="fa-solid fa-xmark"></i>
                                    Cancel
                                </a>

                            <?php else: ?>

                                <button
                                    type="reset"
                                    class="pc-btn pc-btn-light"
                                >
                                    <i class="fa-solid fa-rotate-left"></i>
                                    Reset
                                </button>

                            <?php endif; ?>

                        </div>

                    </form>


                    <div class="pc-notice">

                        <i class="fa-solid fa-shield-halved"></i>

                        <div>
                            Same
                            <strong>Industry + Product</strong>
                            mapping duplicate nahi banne di jayegi.
                        </div>

                    </div>

                </div>

            </div>


            <!-- =============================================
                 MAPPING LIST
            ============================================== -->

            <div class="pc-card">

                <div class="pc-card-header">

                    <div>

                        <h3 class="pc-card-title">
                            Product Mappings
                        </h3>

                        <p class="pc-card-subtitle">
                            Industry ke andar assigned products.
                        </p>

                    </div>

                    <span class="pc-eyebrow">
                        <?= number_format($totalRows) ?> Records
                    </span>

                </div>


                <!-- FILTER -->

                <div class="pc-filter">

                    <form
                        method="GET"
                        class="pc-filter-form"
                    >

                        <div class="pc-search-wrap">

                            <i class="fa-solid fa-magnifying-glass"></i>

                            <input
                                type="search"
                                name="search"
                                class="pc-input"
                                value="<?= e($search) ?>"
                                placeholder="Search industry or ID..."
                            >

                        </div>


                        <select
                            name="industry_id"
                            class="pc-select"
                        >

                            <option value="">
                                All Industries
                            </option>

                            <?php foreach ($industries as $industry): ?>

                                <option
                                    value="<?= (int)$industry['id'] ?>"
                                    <?= (
                                        $filterIndustry
                                        === (int)$industry['id']
                                    ) ? 'selected' : '' ?>
                                >
                                    <?= e($industry['name']) ?>
                                </option>

                            <?php endforeach; ?>

                        </select>


                        <button
                            type="submit"
                            class="pc-btn pc-btn-primary"
                        >
                            <i class="fa-solid fa-filter"></i>
                            Filter
                        </button>

                    </form>

                </div>


                <!-- TABLE -->

                <?php if (!empty($rows)): ?>

                    <div class="pc-table-wrap">

                        <table class="pc-table">

                            <thead>

                                <tr>

                                    <th>
                                        Industry
                                    </th>

                                    <th>
                                        Product
                                    </th>

                                    <th>
                                        Sort
                                    </th>

                                    <th style="text-align:right;">
                                        Actions
                                    </th>

                                </tr>

                            </thead>

                            <tbody>

                            <?php foreach ($rows as $row): ?>

                                <?php

                                $productId =
                                    (int)$row['product_id'];

                                $productInfo =
                                    $productMap[$productId]
                                    ?? null;

                                $productName =
                                    $productInfo['name']
                                    ?? ('Product #' . $productId);

                                ?>

                                <tr>

                                    <!-- INDUSTRY -->

                                    <td>

                                        <div class="pc-industry">

                                            <div class="pc-industry-icon">

                                                <i class="fa-solid fa-industry"></i>

                                            </div>

                                            <div>

                                                <div class="pc-industry-name">
                                                    <?= e($row['industry_name']) ?>
                                                </div>

                                                <div class="pc-industry-slug">

                                                    #<?= (int)$row['industry_id'] ?>

                                                    <?php if (!empty($row['industry_slug'])): ?>

                                                        ·
                                                        <?= e($row['industry_slug']) ?>

                                                    <?php endif; ?>

                                                </div>

                                            </div>

                                        </div>

                                    </td>


                                    <!-- PRODUCT -->

                                    <td>

                                        <div class="pc-product">

                                            <i class="fa-solid fa-box"></i>

                                            <span>
                                                <?= e($productName) ?>
                                            </span>

                                            <span class="pc-product-id">
                                                #<?= $productId ?>
                                            </span>

                                        </div>

                                    </td>


                                    <!-- SORT -->

                                    <td>

                                        <span class="pc-order">
                                            <?= (int)$row['sort_order'] ?>
                                        </span>

                                    </td>


                                    <!-- ACTIONS -->

                                    <td>

                                        <div class="pc-actions">

                                            <!-- EDIT -->

                                            <a
                                                href="?edit_industry_id=<?= (int)$row['industry_id'] ?>&edit_product_id=<?= $productId ?>"
                                                class="pc-icon-btn"
                                                title="Edit"
                                            >
                                                <i class="fa-solid fa-pen"></i>
                                            </a>


                                            <!-- DELETE -->

                                            <form
                                                method="POST"
                                                onsubmit="return confirmDelete(
                                                    '<?= e($row['industry_name']) ?>',
                                                    '<?= e($productName) ?>'
                                                );"
                                            >

                                                <input
                                                    type="hidden"
                                                    name="csrf_token"
                                                    value="<?= e($csrfToken) ?>"
                                                >

                                                <input
                                                    type="hidden"
                                                    name="action"
                                                    value="delete"
                                                >

                                                <input
                                                    type="hidden"
                                                    name="industry_id"
                                                    value="<?= (int)$row['industry_id'] ?>"
                                                >

                                                <input
                                                    type="hidden"
                                                    name="product_id"
                                                    value="<?= $productId ?>"
                                                >

                                                <button
                                                    type="submit"
                                                    class="pc-icon-btn delete"
                                                    title="Delete"
                                                >
                                                    <i class="fa-solid fa-trash"></i>
                                                </button>

                                            </form>

                                        </div>

                                    </td>

                                </tr>

                            <?php endforeach; ?>

                            </tbody>

                        </table>

                    </div>


                    <!-- PAGINATION -->

                    <?php if ($totalPages > 1): ?>

                        <div class="pc-pagination">

                            <div class="pc-page-info">

                                Showing
                                <strong>
                                    <?= $totalRows > 0
                                        ? ($offset + 1)
                                        : 0
                                    ?>
                                </strong>

                                –
                                <strong>
                                    <?= min(
                                        $offset + $perPage,
                                        $totalRows
                                    ) ?>
                                </strong>

                                of
                                <strong>
                                    <?= number_format($totalRows) ?>
                                </strong>

                            </div>


                            <div class="pc-pages">

                                <?php

                                $prevUrl = '?' . http_build_query([
                                    'search' => $search,
                                    'industry_id' => $filterIndustry,
                                    'page' => max(1, $page - 1)
                                ]);

                                ?>

                                <a
                                    href="<?= e($prevUrl) ?>"
                                    class="pc-page-btn <?= $page <= 1 ? 'disabled' : '' ?>"
                                >
                                    <i class="fa-solid fa-chevron-left"></i>
                                </a>


                                <?php

                                $startPage = max(
                                    1,
                                    $page - 2
                                );

                                $endPage = min(
                                    $totalPages,
                                    $page + 2
                                );

                                for (
                                    $p = $startPage;
                                    $p <= $endPage;
                                    $p++
                                ):

                                    $pageUrl = '?' . http_build_query([
                                        'search' => $search,
                                        'industry_id' => $filterIndustry,
                                        'page' => $p
                                    ]);

                                ?>

                                    <a
                                        href="<?= e($pageUrl) ?>"
                                        class="pc-page-btn <?= $p === $page ? 'active' : '' ?>"
                                    >
                                        <?= $p ?>
                                    </a>

                                <?php endfor; ?>


                                <?php

                                $nextUrl = '?' . http_build_query([
                                    'search' => $search,
                                    'industry_id' => $filterIndustry,
                                    'page' => min(
                                        $totalPages,
                                        $page + 1
                                    )
                                ]);

                                ?>

                                <a
                                    href="<?= e($nextUrl) ?>"
                                    class="pc-page-btn <?= $page >= $totalPages ? 'disabled' : '' ?>"
                                >
                                    <i class="fa-solid fa-chevron-right"></i>
                                </a>

                            </div>

                        </div>

                    <?php endif; ?>


                <?php else: ?>

                    <div class="pc-empty">

                        <div class="pc-empty-icon">
                            <i class="fa-solid fa-link"></i>
                        </div>

                        <h3>
                            No Product Mappings Found
                        </h3>

                        <p>
                            Abhi kisi industry ke saath koi product assigned nahi hai.
                        </p>

                    </div>

                <?php endif; ?>

            </div>

        </section>

    </main>

</div>


<script>

    /* -------------------------------------------------------
       DELETE CONFIRMATION
    ------------------------------------------------------- */

    function confirmDelete(industryName, productName) {

        return confirm(
            "Delete this product mapping?\n\n" +
            "Industry: " + industryName + "\n" +
            "Product: " + productName
        );
    }


    /* -------------------------------------------------------
       SIDEBAR MOBILE TOGGLE
    ------------------------------------------------------- */

    function toggleSidebar() {

        const sidebar =
            document.querySelector(
                '.sidebar, .admin-sidebar, #sidebar'
            );

        if (sidebar) {
            sidebar.classList.toggle('active');
        }
    }


    /* -------------------------------------------------------
       AUTO HIDE ALERTS
    ------------------------------------------------------- */

    setTimeout(function () {

        document
            .querySelectorAll('.pc-alert')
            .forEach(function (alert) {

                alert.style.transition =
                    'opacity .35s ease, transform .35s ease';

                alert.style.opacity = '0';
                alert.style.transform = 'translateY(-5px)';

                setTimeout(function () {
                    alert.remove();
                }, 400);

            });

    }, 5000);

</script>

</body>
</html>