<?php
/*
|--------------------------------------------------------------------------
| Pure Chemical Admin - Brands Manager
|--------------------------------------------------------------------------
| File: admin/brands.php
| Database Table: brands
|
| Existing tables used:
|   - brands
|
| No new table required.
|--------------------------------------------------------------------------
*/

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/includes/db.php';

/*
|--------------------------------------------------------------------------
| Optional Authentication
|--------------------------------------------------------------------------
*/
$authFile = __DIR__ . '/includes/auth.php';

if (file_exists($authFile)) {
    require_once $authFile;

    if (function_exists('requireAdmin')) {
        requireAdmin();
    }
}

/*
|--------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------
*/
if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars(
            (string)$value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}

/*
|--------------------------------------------------------------------------
| CSRF
|--------------------------------------------------------------------------
*/
$csrfFile = __DIR__ . '/includes/csrf.php';

if (file_exists($csrfFile)) {
    require_once $csrfFile;
}

if (!function_exists('csrf_token')) {
    function csrf_token()
    {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] =
                bin2hex(random_bytes(32));
        }

        return $_SESSION['csrf_token'];
    }
}

if (!function_exists('csrf_field')) {
    function csrf_field()
    {
        return '<input type="hidden" name="csrf_token" value="' .
            e(csrf_token()) .
            '">';
    }
}

if (!function_exists('verify_csrf')) {
    function verify_csrf()
    {
        $token = $_POST['csrf_token'] ?? '';

        if (
            empty($_SESSION['csrf_token']) ||
            !hash_equals(
                $_SESSION['csrf_token'],
                $token
            )
        ) {
            throw new Exception(
                'Invalid security token. Please refresh the page and try again.'
            );
        }
    }
}

/*
|--------------------------------------------------------------------------
| Flash Messages
|--------------------------------------------------------------------------
*/
$success = $_SESSION['brands_success'] ?? '';
$error   = $_SESSION['brands_error'] ?? '';

unset(
    $_SESSION['brands_success'],
    $_SESSION['brands_error']
);

/*
|--------------------------------------------------------------------------
| Brand Type ENUM - Read Dynamically
|--------------------------------------------------------------------------
*/
$brandTypes = [];

try {

    $enumStmt = $pdo->query(
        "SHOW COLUMNS FROM brands LIKE 'brand_type'"
    );

    $enumColumn = $enumStmt->fetch();

    if (
        $enumColumn &&
        !empty($enumColumn['Type'])
    ) {

        if (
            preg_match(
                '/^enum\((.*)\)$/i',
                $enumColumn['Type'],
                $matches
            )
        ) {

            preg_match_all(
                "/'((?:[^'\\\\]|\\\\.)*)'/",
                $matches[1],
                $enumMatches
            );

            if (!empty($enumMatches[1])) {

                foreach (
                    $enumMatches[1]
                    as $brandType
                ) {
                    $brandTypes[] =
                        stripslashes($brandType);
                }
            }
        }
    }

} catch (Throwable $e) {
    $brandTypes = [];
}

/*
|--------------------------------------------------------------------------
| Fallback only if ENUM couldn't be detected
|--------------------------------------------------------------------------
*/
if (empty($brandTypes)) {

    $brandTypes = [
        'brand',
        'principal',
        'division',
        'partner'
    ];
}

/*
|--------------------------------------------------------------------------
| Slug Generator
|--------------------------------------------------------------------------
*/
function brandSlug($text)
{
    $text = trim($text);

    if ($text === '') {
        return '';
    }

    $text = mb_strtolower(
        $text,
        'UTF-8'
    );

    if (function_exists('iconv')) {

        $converted = @iconv(
            'UTF-8',
            'ASCII//TRANSLIT//IGNORE',
            $text
        );

        if ($converted !== false) {
            $text = $converted;
        }
    }

    $text = preg_replace(
        '/[^a-z0-9]+/',
        '-',
        $text
    );

    $text = trim(
        $text,
        '-'
    );

    return $text;
}

/*
|--------------------------------------------------------------------------
| Parent Cycle Check
|--------------------------------------------------------------------------
*/
function brandWouldCreateCycle(
    PDO $pdo,
    $brandId,
    $parentId
) {

    if (
        !$brandId ||
        !$parentId
    ) {
        return false;
    }

    $current = (int)$parentId;

    $visited = [];

    while ($current > 0) {

        if ($current === (int)$brandId) {
            return true;
        }

        if (isset($visited[$current])) {
            return true;
        }

        $visited[$current] = true;

        $stmt = $pdo->prepare("
            SELECT parent_id
            FROM brands
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $current
        ]);

        $row = $stmt->fetch();

        if (!$row) {
            break;
        }

        $current = !empty($row['parent_id'])
            ? (int)$row['parent_id']
            : 0;
    }

    return false;
}

/*
|--------------------------------------------------------------------------
| Brands for Parent Dropdown
|--------------------------------------------------------------------------
*/
$allBrands = [];

try {

    $stmt = $pdo->query("
        SELECT
            id,
            parent_id,
            name,
            slug,
            brand_type,
            status
        FROM brands
        ORDER BY
            sort_order ASC,
            name ASC
    ");

    $allBrands = $stmt->fetchAll();

} catch (Throwable $e) {
    $allBrands = [];
}

/*
|--------------------------------------------------------------------------
| Build Brand Tree
|--------------------------------------------------------------------------
*/
$brandTree = [];

foreach ($allBrands as $brand) {

    $parentId = !empty($brand['parent_id'])
        ? (int)$brand['parent_id']
        : 0;

    if (!isset($brandTree[$parentId])) {
        $brandTree[$parentId] = [];
    }

    $brandTree[$parentId][] = $brand;
}

/*
|--------------------------------------------------------------------------
| Render Parent Options
|--------------------------------------------------------------------------
*/
function renderBrandOptions(
    $parentId,
    $tree,
    $selectedId = 0,
    $excludeId = 0,
    $level = 0,
    $visited = []
) {

    if (empty($tree[$parentId])) {
        return;
    }

    foreach ($tree[$parentId] as $brand) {

        $id = (int)$brand['id'];

        if ($id === (int)$excludeId) {
            continue;
        }

        if (isset($visited[$id])) {
            continue;
        }

        $visited[$id] = true;

        $prefix = str_repeat(
            '— ',
            $level
        );

        $selected =
            ((int)$selectedId === $id)
                ? ' selected'
                : '';

        $statusText =
            ((int)$brand['status'] === 1)
                ? ''
                : ' (Inactive)';

        echo '<option value="' .
            e($id) .
            '"' .
            $selected .
            '>';

        echo e(
            $prefix .
            $brand['name'] .
            $statusText
        );

        echo '</option>';

        renderBrandOptions(
            $id,
            $tree,
            $selectedId,
            $excludeId,
            $level + 1,
            $visited
        );
    }
}

/*
|--------------------------------------------------------------------------
| POST Actions
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    try {

        verify_csrf();

        $action = $_POST['action'] ?? '';

        /*
        |--------------------------------------------------------------------------
        | SAVE BRAND
        |--------------------------------------------------------------------------
        */
        if (
            $action === 'add' ||
            $action === 'update'
        ) {

            $id = (int)(
                $_POST['id'] ?? 0
            );

            $parentId = (int)(
                $_POST['parent_id'] ?? 0
            );

            $name = trim(
                $_POST['name'] ?? ''
            );

            $slug = trim(
                $_POST['slug'] ?? ''
            );

            $brandType = trim(
                $_POST['brand_type'] ?? 'brand'
            );

            $shortDescription = trim(
                $_POST['short_description'] ?? ''
            );

            $description = trim(
                $_POST['description'] ?? ''
            );

            $websiteUrl = trim(
                $_POST['website_url'] ?? ''
            );

            $logoId = (int)(
                $_POST['logo_id'] ?? 0
            );

            $bannerId = (int)(
                $_POST['banner_id'] ?? 0
            );

            $status = isset(
                $_POST['status']
            ) ? 1 : 0;

            $featured = isset(
                $_POST['featured']
            ) ? 1 : 0;

            $sortOrder = (int)(
                $_POST['sort_order'] ?? 0
            );

            /*
            |--------------------------------------------------------------------------
            | Validation
            |--------------------------------------------------------------------------
            */

            if ($name === '') {

                throw new Exception(
                    'Brand name is required.'
                );
            }

            if (mb_strlen($name) > 255) {

                throw new Exception(
                    'Brand name cannot exceed 255 characters.'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | Generate Slug
            |--------------------------------------------------------------------------
            */
            if ($slug === '') {
                $slug = brandSlug($name);
            } else {
                $slug = brandSlug($slug);
            }

            if ($slug === '') {

                throw new Exception(
                    'A valid slug could not be generated.'
                );
            }

            if (mb_strlen($slug) > 255) {

                throw new Exception(
                    'Slug cannot exceed 255 characters.'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | Brand Type
            |--------------------------------------------------------------------------
            */
            if (
                !in_array(
                    $brandType,
                    $brandTypes,
                    true
                )
            ) {

                throw new Exception(
                    'Invalid brand type selected.'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | Parent
            |--------------------------------------------------------------------------
            */
            if ($parentId <= 0) {
                $parentId = null;
            }

            if (
                $parentId !== null &&
                $action === 'update' &&
                $id > 0 &&
                $parentId === $id
            ) {

                throw new Exception(
                    'A brand cannot be its own parent.'
                );
            }

            if (
                $parentId !== null
            ) {

                $parentStmt = $pdo->prepare("
                    SELECT id
                    FROM brands
                    WHERE id = ?
                    LIMIT 1
                ");

                $parentStmt->execute([
                    $parentId
                ]);

                if (!$parentStmt->fetch()) {

                    throw new Exception(
                        'Selected parent brand does not exist.'
                    );
                }
            }

            /*
            |--------------------------------------------------------------------------
            | Circular Parent Validation
            |--------------------------------------------------------------------------
            */
            if (
                $parentId !== null &&
                $action === 'update' &&
                $id > 0
            ) {

                if (
                    brandWouldCreateCycle(
                        $pdo,
                        $id,
                        $parentId
                    )
                ) {

                    throw new Exception(
                        'Invalid parent selection. It would create a circular brand hierarchy.'
                    );
                }
            }

            /*
            |--------------------------------------------------------------------------
            | Website URL
            |--------------------------------------------------------------------------
            */
            if ($websiteUrl !== '') {

                if (
                    mb_strlen($websiteUrl) > 1000
                ) {

                    throw new Exception(
                        'Website URL cannot exceed 1000 characters.'
                    );
                }

                if (
                    !filter_var(
                        $websiteUrl,
                        FILTER_VALIDATE_URL
                    )
                ) {

                    throw new Exception(
                        'Please enter a valid website URL.'
                    );
                }
            }

            /*
            |--------------------------------------------------------------------------
            | Numeric IDs
            |--------------------------------------------------------------------------
            */
            if ($logoId < 0) {
                $logoId = 0;
            }

            if ($bannerId < 0) {
                $bannerId = 0;
            }

            if ($sortOrder < 0) {
                $sortOrder = 0;
            }

            /*
            |--------------------------------------------------------------------------
            | Slug Duplicate Check
            |--------------------------------------------------------------------------
            */
            if ($action === 'add') {

                $slugStmt = $pdo->prepare("
                    SELECT id
                    FROM brands
                    WHERE slug = ?
                    LIMIT 1
                ");

                $slugStmt->execute([
                    $slug
                ]);

            } else {

                $slugStmt = $pdo->prepare("
                    SELECT id
                    FROM brands
                    WHERE slug = ?
                      AND id != ?
                    LIMIT 1
                ");

                $slugStmt->execute([
                    $slug,
                    $id
                ]);
            }

            if ($slugStmt->fetch()) {

                throw new Exception(
                    'This slug is already used by another brand.'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | ADD
            |--------------------------------------------------------------------------
            */
            if ($action === 'add') {

                $stmt = $pdo->prepare("
                    INSERT INTO brands (
                        parent_id,
                        name,
                        slug,
                        brand_type,
                        short_description,
                        description,
                        website_url,
                        logo_id,
                        banner_id,
                        status,
                        featured,
                        sort_order
                    ) VALUES (
                        :parent_id,
                        :name,
                        :slug,
                        :brand_type,
                        :short_description,
                        :description,
                        :website_url,
                        :logo_id,
                        :banner_id,
                        :status,
                        :featured,
                        :sort_order
                    )
                ");

                $stmt->execute([
                    ':parent_id' =>
                        $parentId,

                    ':name' =>
                        $name,

                    ':slug' =>
                        $slug,

                    ':brand_type' =>
                        $brandType,

                    ':short_description' =>
                        $shortDescription !== ''
                            ? $shortDescription
                            : null,

                    ':description' =>
                        $description !== ''
                            ? $description
                            : null,

                    ':website_url' =>
                        $websiteUrl !== ''
                            ? $websiteUrl
                            : null,

                    ':logo_id' =>
                        $logoId > 0
                            ? $logoId
                            : null,

                    ':banner_id' =>
                        $bannerId > 0
                            ? $bannerId
                            : null,

                    ':status' =>
                        $status,

                    ':featured' =>
                        $featured,

                    ':sort_order' =>
                        $sortOrder
                ]);

                $_SESSION['brands_success'] =
                    'Brand added successfully.';

                header(
                    'Location: brands.php'
                );

                exit;
            }

            /*
            |--------------------------------------------------------------------------
            | UPDATE
            |--------------------------------------------------------------------------
            */
            if ($action === 'update') {

                if ($id <= 0) {

                    throw new Exception(
                        'Invalid brand ID.'
                    );
                }

                $existsStmt = $pdo->prepare("
                    SELECT id
                    FROM brands
                    WHERE id = ?
                    LIMIT 1
                ");

                $existsStmt->execute([
                    $id
                ]);

                if (!$existsStmt->fetch()) {

                    throw new Exception(
                        'Brand record not found.'
                    );
                }

                $stmt = $pdo->prepare("
                    UPDATE brands
                    SET
                        parent_id = :parent_id,
                        name = :name,
                        slug = :slug,
                        brand_type = :brand_type,
                        short_description = :short_description,
                        description = :description,
                        website_url = :website_url,
                        logo_id = :logo_id,
                        banner_id = :banner_id,
                        status = :status,
                        featured = :featured,
                        sort_order = :sort_order
                    WHERE id = :id
                    LIMIT 1
                ");

                $stmt->execute([
                    ':parent_id' =>
                        $parentId,

                    ':name' =>
                        $name,

                    ':slug' =>
                        $slug,

                    ':brand_type' =>
                        $brandType,

                    ':short_description' =>
                        $shortDescription !== ''
                            ? $shortDescription
                            : null,

                    ':description' =>
                        $description !== ''
                            ? $description
                            : null,

                    ':website_url' =>
                        $websiteUrl !== ''
                            ? $websiteUrl
                            : null,

                    ':logo_id' =>
                        $logoId > 0
                            ? $logoId
                            : null,

                    ':banner_id' =>
                        $bannerId > 0
                            ? $bannerId
                            : null,

                    ':status' =>
                        $status,

                    ':featured' =>
                        $featured,

                    ':sort_order' =>
                        $sortOrder,

                    ':id' =>
                        $id
                ]);

                $_SESSION['brands_success'] =
                    'Brand updated successfully.';

                header(
                    'Location: brands.php'
                );

                exit;
            }
        }

        /*
        |--------------------------------------------------------------------------
        | DELETE
        |--------------------------------------------------------------------------
        */
        if ($action === 'delete') {

            $id = (int)(
                $_POST['id'] ?? 0
            );

            if ($id <= 0) {

                throw new Exception(
                    'Invalid brand ID.'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | Protect Child Brands
            |--------------------------------------------------------------------------
            */
            $childStmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM brands
                WHERE parent_id = ?
            ");

            $childStmt->execute([
                $id
            ]);

            $childCount =
                (int)$childStmt->fetchColumn();

            if ($childCount > 0) {

                throw new Exception(
                    'This brand has child brands. Please move or delete the child brands first.'
                );
            }

            /*
            |--------------------------------------------------------------------------
            | Delete
            |--------------------------------------------------------------------------
            */
            $deleteStmt = $pdo->prepare("
                DELETE FROM brands
                WHERE id = ?
                LIMIT 1
            ");

            $deleteStmt->execute([
                $id
            ]);

            $_SESSION['brands_success'] =
                'Brand deleted successfully.';

            header(
                'Location: brands.php'
            );

            exit;
        }

    } catch (Throwable $e) {

        $error = $e->getMessage();
    }
}

/*
|--------------------------------------------------------------------------
| Edit Record
|--------------------------------------------------------------------------
*/
$editId = isset($_GET['edit'])
    ? (int)$_GET['edit']
    : 0;

$editBrand = null;

if ($editId > 0) {

    try {

        $stmt = $pdo->prepare("
            SELECT
                id,
                parent_id,
                name,
                slug,
                brand_type,
                short_description,
                description,
                website_url,
                logo_id,
                banner_id,
                status,
                featured,
                sort_order
            FROM brands
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $editId
        ]);

        $editBrand = $stmt->fetch();

        if (!$editBrand) {

            $error =
                'Selected brand could not be found.';

            $editId = 0;
        }

    } catch (Throwable $e) {

        $error = $e->getMessage();

        $editId = 0;
    }
}

/*
|--------------------------------------------------------------------------
| Search / Filters
|--------------------------------------------------------------------------
*/
$search = trim(
    $_GET['search'] ?? ''
);

$typeFilter = trim(
    $_GET['type'] ?? ''
);

$statusFilter = $_GET['status'] ?? '';

$featuredFilter = $_GET['featured'] ?? '';

$page = max(
    1,
    (int)($_GET['page'] ?? 1)
);

$perPage = 12;

$offset = ($page - 1) * $perPage;

/*
|--------------------------------------------------------------------------
| Filter Conditions
|--------------------------------------------------------------------------
*/
$where = [];
$params = [];

if ($search !== '') {

    $where[] = "
        (
            b.name LIKE ?
            OR b.slug LIKE ?
            OR b.short_description LIKE ?
            OR b.description LIKE ?
        )
    ";

    $like = '%' . $search . '%';

    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

if ($typeFilter !== '') {

    $where[] =
        'b.brand_type = ?';

    $params[] =
        $typeFilter;
}

if (
    $statusFilter === '0' ||
    $statusFilter === '1'
) {

    $where[] =
        'b.status = ?';

    $params[] =
        (int)$statusFilter;
}

if (
    $featuredFilter === '0' ||
    $featuredFilter === '1'
) {

    $where[] =
        'b.featured = ?';

    $params[] =
        (int)$featuredFilter;
}

$whereSql = '';

if (!empty($where)) {

    $whereSql =
        'WHERE ' .
        implode(
            ' AND ',
            $where
        );
}

/*
|--------------------------------------------------------------------------
| Statistics
|--------------------------------------------------------------------------
*/
$totalBrands = 0;
$activeBrands = 0;
$featuredBrands = 0;
$parentBrands = 0;

try {

    $totalBrands = (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM brands
        ")
        ->fetchColumn();

    $activeBrands = (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM brands
            WHERE status = 1
        ")
        ->fetchColumn();

    $featuredBrands = (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM brands
            WHERE featured = 1
        ")
        ->fetchColumn();

    $parentBrands = (int)$pdo
        ->query("
            SELECT COUNT(*)
            FROM brands
            WHERE parent_id IS NULL
        ")
        ->fetchColumn();

} catch (Throwable $e) {
    // Keep zero if statistics fail.
}

/*
|--------------------------------------------------------------------------
| Filtered Count
|--------------------------------------------------------------------------
*/
$filteredTotal = 0;

try {

    $countSql = "
        SELECT COUNT(*)
        FROM brands b
        {$whereSql}
    ";

    $countStmt =
        $pdo->prepare($countSql);

    $countStmt->execute(
        $params
    );

    $filteredTotal =
        (int)$countStmt->fetchColumn();

} catch (Throwable $e) {

    $filteredTotal = 0;
}

/*
|--------------------------------------------------------------------------
| Pagination
|--------------------------------------------------------------------------
*/
$totalPages = max(
    1,
    (int)ceil(
        $filteredTotal / $perPage
    )
);

if ($page > $totalPages) {

    $page = $totalPages;

    $offset =
        ($page - 1) * $perPage;
}

/*
|--------------------------------------------------------------------------
| Brand List
|--------------------------------------------------------------------------
*/
$brands = [];

try {

    $sql = "
        SELECT
            b.id,
            b.parent_id,
            b.name,
            b.slug,
            b.brand_type,
            b.short_description,
            b.website_url,
            b.logo_id,
            b.banner_id,
            b.status,
            b.featured,
            b.sort_order,
            b.created_at,
            p.name AS parent_name
        FROM brands b
        LEFT JOIN brands p
            ON p.id = b.parent_id
        {$whereSql}
        ORDER BY
            b.sort_order ASC,
            b.name ASC,
            b.id DESC
        LIMIT {$perPage}
        OFFSET {$offset}
    ";

    $stmt =
        $pdo->prepare($sql);

    $stmt->execute(
        $params
    );

    $brands =
        $stmt->fetchAll();

} catch (Throwable $e) {

    $error =
        $error ?: $e->getMessage();
}

/*
|--------------------------------------------------------------------------
| URL Builder
|--------------------------------------------------------------------------
*/
function buildBrandUrl(
    $overrides = []
) {

    $query = [
        'search' =>
            $_GET['search'] ?? '',

        'type' =>
            $_GET['type'] ?? '',

        'status' =>
            $_GET['status'] ?? '',

        'featured' =>
            $_GET['featured'] ?? '',

        'page' =>
            $_GET['page'] ?? 1,

        'edit' =>
            $_GET['edit'] ?? ''
    ];

    foreach (
        $overrides
        as $key => $value
    ) {

        if (
            $value === null ||
            $value === ''
        ) {

            unset(
                $query[$key]
            );

        } else {

            $query[$key] =
                $value;
        }
    }

    $query = array_filter(
        $query,
        function ($value) {
            return $value !== '';
        }
    );

    return
        'brands.php?' .
        http_build_query($query);
}

/*
|--------------------------------------------------------------------------
| Admin
|--------------------------------------------------------------------------
*/
$adminName =
    $_SESSION['ADMIN_NAME']
    ?? $_SESSION['admin_name']
    ?? $_SESSION['name']
    ?? 'Administrator';

$adminInitial =
    strtoupper(
        mb_substr(
            trim($adminName),
            0,
            1,
            'UTF-8'
        )
    );

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>
        Brands | Pure Chemical Admin
    </title>

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {

            --primary: #2563eb;
            --primary-dark: #1d4ed8;
            --primary-soft: #eff6ff;

            --success: #16a34a;
            --danger: #dc2626;
            --warning: #d97706;
            --purple: #7c3aed;

            --text: #172033;
            --muted: #667085;

            --border: #e7eaf0;

            --bg: #f5f7fb;

            --white: #ffffff;

            --sidebar-width: 280px;

            --radius: 18px;

            --shadow-sm:
                0 2px 10px
                rgba(16, 24, 40, .045);

            --shadow:
                0 14px 40px
                rgba(16, 24, 40, .075);
        }

        * {
            box-sizing: border-box;
        }

        body {

            margin: 0;

            background: var(--bg);

            color: var(--text);

            font-family:
                Inter,
                -apple-system,
                BlinkMacSystemFont,
                "Segoe UI",
                Roboto,
                Arial,
                sans-serif;
        }

        a {
            text-decoration: none;
            color: inherit;
        }

        button,
        input,
        select,
        textarea {
            font: inherit;
        }

        /* =====================================================
           PAGE WRAPPER
        ====================================================== */

        .page-wrapper {

            margin-left:
                var(--sidebar-width);

            min-height: 100vh;
        }

        /* =====================================================
           PREMIUM STICKY TOPBAR
        ====================================================== */

        .topbar {

            height: 78px;

            padding:
                0 32px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            background:
                rgba(255, 255, 255, .94);

            border-bottom:
                1px solid var(--border);

            position: sticky;

            top: 0;

            z-index: 100;

            backdrop-filter:
                blur(18px);
        }

        .topbar-left {

            display: flex;

            align-items: center;

            gap: 14px;
        }

        .page-icon {

            width: 46px;
            height: 46px;

            display: flex;

            align-items: center;

            justify-content: center;

            color: #fff;

            border-radius: 14px;

            background:
                linear-gradient(
                    135deg,
                    #2563eb,
                    #4f46e5
                );

            box-shadow:
                0 9px 22px
                rgba(37, 99, 235, .22);
        }

        .topbar-title {

            margin: 0;

            font-size: 18px;

            font-weight: 850;

            letter-spacing: -.4px;
        }

        .breadcrumb {

            display: flex;

            align-items: center;

            gap: 8px;

            margin-top: 3px;

            color: var(--muted);

            font-size: 10px;
        }

        .breadcrumb i {
            font-size: 8px;
        }

        .topbar-right {

            display: flex;

            align-items: center;

            gap: 12px;
        }

        .admin-profile {

            display: flex;

            align-items: center;

            gap: 9px;

            padding:
                5px 12px 5px 5px;

            border:
                1px solid var(--border);

            border-radius: 50px;

            background: #fff;
        }

        .admin-avatar {

            width: 38px;
            height: 38px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 50%;

            background:
                linear-gradient(
                    135deg,
                    #111827,
                    #374151
                );

            color: #fff;

            font-size: 13px;

            font-weight: 800;
        }

        .admin-name {

            font-size: 11px;

            font-weight: 800;
        }

        .admin-role {

            margin-top: 2px;

            color: var(--muted);

            font-size: 9px;
        }

        /* =====================================================
           MAIN
        ====================================================== */

        .main-content {

            max-width: 1600px;

            margin: auto;

            padding: 30px;
        }

        .page-heading {

            display: flex;

            align-items: flex-end;

            justify-content: space-between;

            gap: 20px;

            margin-bottom: 24px;
        }

        .page-heading h1 {

            margin: 0;

            font-size: 29px;

            font-weight: 850;

            letter-spacing: -.8px;
        }

        .page-heading p {

            margin:
                7px 0 0;

            color: var(--muted);

            font-size: 13px;
        }

        .add-btn {

            display: inline-flex;

            align-items: center;

            gap: 8px;

            padding:
                12px 17px;

            border: 0;

            border-radius: 11px;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #2563eb,
                    #4f46e5
                );

            box-shadow:
                0 8px 20px
                rgba(37, 99, 235, .20);

            cursor: pointer;

            font-size: 12px;

            font-weight: 750;
        }

        /* =====================================================
           ALERT
        ====================================================== */

        .alert {

            display: flex;

            align-items: flex-start;

            gap: 10px;

            padding:
                14px 16px;

            margin-bottom: 20px;

            border-radius: 13px;

            font-size: 12px;

            line-height: 1.55;
        }

        .alert-success {

            color: #166534;

            background: #ecfdf3;

            border:
                1px solid #bbf7d0;
        }

        .alert-danger {

            color: #991b1b;

            background: #fef2f2;

            border:
                1px solid #fecaca;
        }

        /* =====================================================
           STATS
        ====================================================== */

        .stats-grid {

            display: grid;

            grid-template-columns:
                repeat(4, 1fr);

            gap: 15px;

            margin-bottom: 20px;
        }

        .stat-card {

            padding: 18px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            background: #fff;

            border:
                1px solid var(--border);

            border-radius: 16px;

            box-shadow: var(--shadow-sm);
        }

        .stat-label {

            color: var(--muted);

            font-size: 11px;

            font-weight: 650;
        }

        .stat-value {

            margin-top: 5px;

            font-size: 24px;

            font-weight: 850;

            letter-spacing: -.6px;
        }

        .stat-icon {

            width: 43px;
            height: 43px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 12px;

            font-size: 15px;
        }

        .blue {
            color: #2563eb;
            background: #eff6ff;
        }

        .green {
            color: #16a34a;
            background: #ecfdf3;
        }

        .purple {
            color: #7c3aed;
            background: #f5f3ff;
        }

        .orange {
            color: #ea580c;
            background: #fff7ed;
        }

        /* =====================================================
           CARD
        ====================================================== */

        .card {

            overflow: hidden;

            background: #fff;

            border:
                1px solid var(--border);

            border-radius: var(--radius);

            box-shadow: var(--shadow-sm);
        }

        /* =====================================================
           FILTER
        ====================================================== */

        .filter-bar {

            padding: 18px;

            display: grid;

            grid-template-columns:
                minmax(200px, 1.4fr)
                minmax(150px, .7fr)
                minmax(130px, .55fr)
                minmax(130px, .55fr)
                auto;

            gap: 10px;

            background: #fcfdff;

            border-bottom:
                1px solid var(--border);
        }

        .input-wrap {
            position: relative;
        }

        .input-icon {

            position: absolute;

            top: 50%;
            left: 13px;

            transform:
                translateY(-50%);

            color: #98a2b3;

            font-size: 12px;

            pointer-events: none;
        }

        .form-control {

            width: 100%;

            min-height: 43px;

            padding:
                10px 12px;

            color: var(--text);

            background: #fff;

            border:
                1px solid #dfe3ea;

            border-radius: 10px;

            outline: none;

            font-size: 12px;

            transition: .2s ease;
        }

        .input-wrap .form-control {
            padding-left: 37px;
        }

        textarea.form-control {

            min-height: 110px;

            resize: vertical;

            line-height: 1.6;
        }

        .form-control:focus {

            border-color:
                var(--primary);

            box-shadow:
                0 0 0 4px
                rgba(37, 99, 235, .08);
        }

        .filter-btn {

            min-height: 43px;

            padding:
                0 16px;

            border: 0;

            border-radius: 10px;

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #2563eb,
                    #4f46e5
                );

            cursor: pointer;

            font-size: 12px;

            font-weight: 750;
        }

        .reset-btn {

            min-height: 43px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 7px;

            padding:
                0 14px;

            border:
                1px solid #dfe3ea;

            border-radius: 10px;

            color: #475467;

            background: #fff;

            font-size: 12px;

            font-weight: 700;
        }

        /* =====================================================
           TABLE HEADER
        ====================================================== */

        .table-header {

            padding:
                19px 21px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            border-bottom:
                1px solid var(--border);
        }

        .table-title {

            display: flex;

            align-items: center;

            gap: 10px;
        }

        .table-title-icon {

            width: 35px;
            height: 35px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 9px;

            color: var(--primary);

            background: var(--primary-soft);
        }

        .table-title h2 {

            margin: 0;

            font-size: 14px;

            font-weight: 800;
        }

        .table-title p {

            margin:
                3px 0 0;

            color: var(--muted);

            font-size: 10px;
        }

        .record-count {

            padding:
                7px 10px;

            border-radius: 8px;

            color: #667085;

            background: #f8fafc;

            font-size: 10px;

            font-weight: 750;
        }

        /* =====================================================
           TABLE
        ====================================================== */

        .table-scroll {
            overflow-x: auto;
        }

        table {

            width: 100%;

            min-width: 1150px;

            border-collapse: collapse;
        }

        thead th {

            padding:
                12px 16px;

            color: #667085;

            background: #f8fafc;

            border-bottom:
                1px solid var(--border);

            text-align: left;

            text-transform: uppercase;

            letter-spacing: .45px;

            font-size: 10px;

            font-weight: 800;
        }

        tbody td {

            padding:
                15px 16px;

            border-bottom:
                1px solid #f0f2f5;

            vertical-align: middle;

            font-size: 12px;
        }

        tbody tr {

            transition: .18s ease;
        }

        tbody tr:hover {
            background: #fbfdff;
        }

        tbody tr:last-child td {
            border-bottom: 0;
        }

        .id-badge {

            display: inline-flex;

            align-items: center;

            justify-content: center;

            min-width: 37px;

            padding:
                6px 8px;

            border-radius: 7px;

            color: #667085;

            background: #f8fafc;

            border:
                1px solid #edf0f4;

            font-size: 10px;

            font-weight: 800;
        }

        .brand-cell {

            display: flex;

            align-items: center;

            gap: 10px;
        }

        .brand-avatar {

            width: 40px;
            height: 40px;

            display: flex;

            align-items: center;

            justify-content: center;

            flex-shrink: 0;

            border-radius: 11px;

            color: #2563eb;

            background:
                linear-gradient(
                    135deg,
                    #eff6ff,
                    #eef2ff
                );

            font-size: 15px;
        }

        .brand-name {

            color: #1f2937;

            font-weight: 800;
        }

        .brand-slug {

            margin-top: 3px;

            color: #98a2b3;

            font-size: 10px;
        }

        .parent-name {

            display: inline-flex;

            align-items: center;

            gap: 6px;

            color: #667085;

            font-size: 10px;

            font-weight: 650;
        }

        .parent-name i {
            color: #98a2b3;
        }

        .root-badge {

            display: inline-flex;

            align-items: center;

            gap: 5px;

            padding:
                6px 9px;

            border-radius: 7px;

            color: #2563eb;

            background: #eff6ff;

            font-size: 10px;

            font-weight: 750;
        }

        .type-badge {

            display: inline-flex;

            align-items: center;

            gap: 6px;

            padding:
                6px 9px;

            border-radius: 7px;

            color: #475467;

            background: #f8fafc;

            border:
                1px solid #edf0f4;

            text-transform: capitalize;

            font-size: 10px;

            font-weight: 750;
        }

        .type-brand {
            color: #2563eb;
            background: #eff6ff;
        }

        .type-principal {
            color: #7c3aed;
            background: #f5f3ff;
        }

        .type-division {
            color: #d97706;
            background: #fff7ed;
        }

        .type-partner {
            color: #059669;
            background: #ecfdf5;
        }

        .status-badge,
        .featured-badge {

            display: inline-flex;

            align-items: center;

            gap: 5px;

            padding:
                6px 9px;

            border-radius: 7px;

            font-size: 10px;

            font-weight: 750;
        }

        .status-active {

            color: #15803d;

            background: #ecfdf3;
        }

        .status-inactive {

            color: #b42318;

            background: #fef3f2;
        }

        .featured-badge {

            color: #a16207;

            background: #fefce8;
        }

        .normal-badge {

            color: #667085;

            background: #f8fafc;
        }

        .sort-badge {

            width: 29px;
            height: 29px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            border-radius: 8px;

            color: #667085;

            background: #f8fafc;

            font-size: 10px;

            font-weight: 800;
        }

        .actions {

            display: flex;

            align-items: center;

            gap: 6px;
        }

        .action-btn {

            width: 34px;
            height: 34px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            border:
                1px solid #e7eaf0;

            border-radius: 9px;

            background: #fff;

            cursor: pointer;

            transition: .2s ease;

            font-size: 11px;
        }

        .edit-btn {
            color: #2563eb;
        }

        .edit-btn:hover {

            background: #eff6ff;

            border-color: #bfdbfe;
        }

        .delete-btn {
            color: #dc2626;
        }

        .delete-btn:hover {

            background: #fef2f2;

            border-color: #fecaca;
        }

        /* =====================================================
           EMPTY
        ====================================================== */

        .empty-state {

            padding:
                70px 20px;

            text-align: center;
        }

        .empty-icon {

            width: 66px;
            height: 66px;

            margin:
                0 auto 15px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 18px;

            color: #2563eb;

            background: #eff6ff;

            font-size: 23px;
        }

        .empty-state h3 {

            margin: 0;

            font-size: 15px;

            font-weight: 800;
        }

        .empty-state p {

            max-width: 430px;

            margin:
                7px auto 0;

            color: var(--muted);

            font-size: 11px;

            line-height: 1.6;
        }

        /* =====================================================
           PAGINATION
        ====================================================== */

        .pagination {

            padding:
                17px 20px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            gap: 15px;

            border-top:
                1px solid var(--border);
        }

        .pagination-info {

            color: var(--muted);

            font-size: 10px;
        }

        .pagination-links {

            display: flex;

            align-items: center;

            gap: 5px;
        }

        .page-link {

            min-width: 34px;
            height: 34px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            border:
                1px solid var(--border);

            border-radius: 8px;

            color: #475467;

            background: #fff;

            font-size: 10px;

            font-weight: 700;
        }

        .page-link.active {

            color: #fff;

            background: var(--primary);

            border-color:
                var(--primary);
        }

        /* =====================================================
           MODAL - FIX OVERLAP WITH SIDEBAR
        ====================================================== */

        .modal-overlay {

            position: fixed;

            /* Fixed positioning aur proper coordinates taki sidebar ke upar overlap na ho */
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;

            z-index: 9999;

            display: none;

            align-items: center;

            justify-content: center;

            padding: 20px;

            background:
                rgba(15, 23, 42, .55);

            backdrop-filter:
                blur(7px);
        }

        .modal-overlay.show {
            display: flex;
        }

        .modal {

            width: 100%;

            max-width: 820px;

            max-height:
                calc(100vh - 40px);

            overflow-y: auto;

            border-radius: 21px;

            background: #fff;

            box-shadow:
                0 30px 80px
                rgba(15, 23, 42, .25);

            animation:
                modalIn .2s ease;
        }

        @keyframes modalIn {

            from {

                opacity: 0;

                transform:
                    translateY(10px)
                    scale(.98);
            }

            to {

                opacity: 1;

                transform:
                    translateY(0)
                    scale(1);
            }
        }

        .modal-header {

            padding:
                20px 22px;

            display: flex;

            align-items: center;

            justify-content: space-between;

            border-bottom:
                1px solid var(--border);
        }

        .modal-heading {

            display: flex;

            align-items: center;

            gap: 11px;
        }

        .modal-heading-icon {

            width: 39px;
            height: 39px;

            display: flex;

            align-items: center;

            justify-content: center;

            border-radius: 10px;

            color: var(--primary);

            background:
                var(--primary-soft);
        }

        .modal-header h2 {

            margin: 0;

            font-size: 16px;

            font-weight: 800;
        }

        .modal-header p {

            margin:
                3px 0 0;

            color: var(--muted);

            font-size: 10px;
        }

        .modal-close {

            width: 35px;
            height: 35px;

            display: flex;

            align-items: center;

            justify-content: center;

            border:
                1px solid var(--border);

            border-radius: 9px;

            color: #667085;

            background: #fff;

            cursor: pointer;
        }

        .modal-body {
            padding: 22px;
        }

        .modal-grid {

            display: grid;

            grid-template-columns:
                repeat(2, minmax(0, 1fr));

            gap: 17px;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

        .form-label {

            display: block;

            margin-bottom: 7px;

            color: #344054;

            font-size: 11px;

            font-weight: 750;
        }

        .required {
            color: #dc2626;
        }

        .slug-row {

            display: grid;

            grid-template-columns:
                1fr auto;

            gap: 8px;
        }

        .slug-btn {

            min-width: 115px;

            border:
                1px solid #dfe3ea;

            border-radius: 10px;

            color: #475467;

            background: #fff;

            cursor: pointer;

            font-size: 10px;

            font-weight: 750;
        }

        .toggle-row {

            display: grid;

            grid-template-columns:
                repeat(2, 1fr);

            gap: 10px;
        }

        .toggle-box {

            min-height: 50px;

            display: flex;

            align-items: center;

            gap: 10px;

            padding:
                10px 12px;

            border:
                1px solid #e4e7ec;

            border-radius: 10px;

            cursor: pointer;
        }

        .toggle-box input {

            width: 17px;
            height: 17px;

            accent-color:
                var(--primary);
        }

        .toggle-title {

            color: #344054;

            font-size: 11px;

            font-weight: 750;
        }

        .toggle-desc {

            margin-top: 2px;

            color: #98a2b3;

            font-size: 9px;
        }

        .modal-footer {

            padding:
                17px 22px;

            display: flex;

            align-items: center;

            justify-content: flex-end;

            gap: 9px;

            background: #fbfcfe;

            border-top:
                1px solid var(--border);
        }

        .btn {

            min-height: 42px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 8px;

            padding:
                10px 16px;

            border:
                1px solid transparent;

            border-radius: 10px;

            cursor: pointer;

            font-size: 11px;

            font-weight: 750;
        }

        .btn-secondary {

            color: #475467;

            background: #fff;

            border-color:
                #dfe3ea;
        }

        .btn-primary {

            color: #fff;

            background:
                linear-gradient(
                    135deg,
                    #2563eb,
                    #4f46e5
                );
        }

        /* =====================================================
           FOOTER
        ====================================================== */

        .page-footer {

            padding:
                23px 30px 30px;

            color: #98a2b3;

            text-align: center;

            font-size: 10px;
        }

        /* =====================================================
           RESPONSIVE
        ====================================================== */

        @media (max-width: 1200px) {

            .stats-grid {

                grid-template-columns:
                    repeat(2, 1fr);
            }

            .filter-bar {

                grid-template-columns:
                    1fr 1fr;
            }

        }

        @media (max-width: 1000px) {

            .page-wrapper {
                margin-left: 0;
            }

            .main-content {
                padding: 22px;
            }

            .topbar {
                padding: 0 20px;
            }

        }

        @media (max-width: 700px) {

            .topbar {
                height: 68px;
            }

            .page-icon {

                width: 40px;
                height: 40px;
            }

            .breadcrumb {
                display: none;
            }

            .admin-info {
                display: none;
            }

            .page-heading {

                align-items: flex-start;

                flex-direction: column;
            }

            .page-heading h1 {
                font-size: 24px;
            }

            .add-btn {
                width: 100%;
            }

            .stats-grid {

                grid-template-columns:
                    1fr 1fr;
            }

            .filter-bar {
                grid-template-columns: 1fr;
            }

            .modal-grid {
                grid-template-columns: 1fr;
            }

            .form-group.full {
                grid-column: auto;
            }

            .toggle-row {
                grid-template-columns: 1fr;
            }

            .pagination {

                align-items: flex-start;

                flex-direction: column;
            }

            .pagination-links {
                flex-wrap: wrap;
            }

        }

        @media (max-width: 450px) {

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .main-content {
                padding: 16px;
            }

            .slug-row {
                grid-template-columns: 1fr;
            }

        }

    </style>

</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| EXISTING SIDEBAR
|--------------------------------------------------------------------------
*/
require_once __DIR__ . '/sidebar.php';
?>


<div class="page-wrapper">

    <!-- =====================================================
         PREMIUM STICKY TOPBAR
    ====================================================== -->

    <header class="topbar">

        <div class="topbar-left">

            <div class="page-icon">

                <i class="fa-solid fa-copyright"></i>

            </div>

            <div>

                <h1 class="topbar-title">
                    Brands
                </h1>

                <div class="breadcrumb">

                    <span>
                        Admin
                    </span>

                    <i class="fa-solid fa-chevron-right"></i>

                    <strong>
                        Brands
                    </strong>

                </div>

            </div>

        </div>


        <div class="topbar-right">

            <div class="admin-profile">

                <div class="admin-avatar">
                    <?= e($adminInitial) ?>
                </div>

                <div>

                    <div class="admin-name">
                        <?= e($adminName) ?>
                    </div>

                    <div class="admin-role">
                        Administrator
                    </div>

                </div>

            </div>

        </div>

    </header>


    <!-- =====================================================
         MAIN
    ====================================================== -->

    <main class="main-content">

        <div class="page-heading">

            <div>

                <h1>
                    Brands
                </h1>

                <p>
                    Manage brands, principals, divisions and partners.
                </p>

            </div>


            <button
                type="button"
                class="add-btn"
                onclick="openAddModal()"
            >

                <i class="fa-solid fa-plus"></i>

                Add Brand

            </button>

        </div>


        <!-- =================================================
             ALERTS
        ================================================== -->

        <?php if ($success): ?>

            <div class="alert alert-success">

                <i class="fa-solid fa-circle-check"></i>

                <div>
                    <?= e($success) ?>
                </div>

            </div>

        <?php endif; ?>


        <?php if ($error): ?>

            <div class="alert alert-danger">

                <i class="fa-solid fa-circle-exclamation"></i>

                <div>
                    <?= e($error) ?>
                </div>

            </div>

        <?php endif; ?>


        <!-- =================================================
             STATISTICS
        ================================================== -->

        <div class="stats-grid">

            <div class="stat-card">

                <div>

                    <div class="stat-label">
                        Total Brands
                    </div>

                    <div class="stat-value">
                        <?= number_format($totalBrands) ?>
                    </div>

                </div>

                <div class="stat-icon blue">

                    <i class="fa-solid fa-copyright"></i>

                </div>

            </div>


            <div class="stat-card">

                <div>

                    <div class="stat-label">
                        Active
                    </div>

                    <div class="stat-value">
                        <?= number_format($activeBrands) ?>
                    </div>

                </div>

                <div class="stat-icon green">

                    <i class="fa-solid fa-circle-check"></i>

                </div>

            </div>


            <div class="stat-card">

                <div>

                    <div class="stat-label">
                        Featured
                    </div>

                    <div class="stat-value">
                        <?= number_format($featuredBrands) ?>
                    </div>

                </div>

                <div class="stat-icon purple">

                    <i class="fa-solid fa-star"></i>

                </div>

            </div>


            <div class="stat-card">

                <div>

                    <div class="stat-label">
                        Root Brands
                    </div>

                    <div class="stat-value">
                        <?= number_format($parentBrands) ?>
                    </div>

                </div>

                <div class="stat-icon orange">

                    <i class="fa-solid fa-sitemap"></i>

                </div>

            </div>

        </div>


        <!-- =================================================
             MAIN CARD
        ================================================== -->

        <div class="card">

            <!-- FILTER -->

            <form
                method="GET"
                class="filter-bar"
            >

                <div class="input-wrap">

                    <i class="fa-solid fa-magnifying-glass input-icon"></i>

                    <input
                        type="text"
                        name="search"
                        class="form-control"
                        value="<?= e($search) ?>"
                        placeholder="Search brand, slug or description..."
                    >

                </div>


                <select
                    name="type"
                    class="form-control"
                >

                    <option value="">
                        All Types
                    </option>

                    <?php foreach ($brandTypes as $type): ?>

                        <option
                            value="<?= e($type) ?>"
                            <?= $typeFilter === $type
                                ? 'selected'
                                : '' ?>
                        >
                            <?= e(
                                ucfirst($type)
                            ) ?>
                        </option>

                    <?php endforeach; ?>

                </select>


                <select
                    name="status"
                    class="form-control"
                >

                    <option value="">
                        All Status
                    </option>

                    <option
                        value="1"
                        <?= $statusFilter === '1'
                            ? 'selected'
                            : '' ?>
                    >
                        Active
                    </option>

                    <option
                        value="0"
                        <?= $statusFilter === '0'
                            ? 'selected'
                            : '' ?>
                    >
                        Inactive
                    </option>

                </select>


                <select
                    name="featured"
                    class="form-control"
                >

                    <option value="">
                        All Brands
                    </option>

                    <option
                        value="1"
                        <?= $featuredFilter === '1'
                            ? 'selected'
                            : '' ?>
                    >
                        Featured
                    </option>

                    <option
                        value="0"
                        <?= $featuredFilter === '0'
                            ? 'selected'
                            : '' ?>
                    >
                        Normal
                    </option>

                </select>


                <div
                    style="
                        display:flex;
                        gap:8px;
                    "
                >

                    <button
                        type="submit"
                        class="filter-btn"
                    >

                        <i class="fa-solid fa-filter"></i>

                        Filter

                    </button>

                    <a
                        href="brands.php"
                        class="reset-btn"
                    >

                        <i class="fa-solid fa-rotate-left"></i>

                        Reset

                    </a>

                </div>

            </form>


            <!-- TABLE HEADER -->

            <div class="table-header">

                <div class="table-title">

                    <div class="table-title-icon">

                        <i class="fa-solid fa-list"></i>

                    </div>

                    <div>

                        <h2>
                            Brand Directory
                        </h2>

                        <p>
                            All brand records
                        </p>

                    </div>

                </div>


                <div class="record-count">

                    <?= number_format($filteredTotal) ?>

                    record<?= $filteredTotal == 1 ? '' : 's' ?>

                </div>

            </div>


            <!-- TABLE -->

            <?php if (!empty($brands)): ?>

                <div class="table-scroll">

                    <table>

                        <thead>

                            <tr>

                                <th>
                                    ID
                                </th>

                                <th>
                                    Brand
                                </th>

                                <th>
                                    Parent
                                </th>

                                <th>
                                    Type
                                </th>

                                <th>
                                    Logo
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Featured
                                </th>

                                <th>
                                    Order
                                </th>

                                <th>
                                    Actions
                                </th>

                            </tr>

                        </thead>


                        <tbody>

                            <?php foreach ($brands as $brand): ?>

                                <?php

                                $typeClass =
                                    'type-' .
                                    preg_replace(
                                        '/[^a-z0-9_-]/i',
                                        '',
                                        strtolower(
                                            $brand['brand_type']
                                        )
                                    );

                                ?>

                                <tr>

                                    <!-- ID -->

                                    <td>

                                        <span class="id-badge">

                                            #
                                            <?= e(
                                                $brand['id']
                                            ) ?>

                                        </span>

                                    </td>


                                    <!-- BRAND -->

                                    <td>

                                        <div class="brand-cell">

                                            <div class="brand-avatar">

                                                <?php if (
                                                    !empty(
                                                        $brand['logo_id']
                                                    )
                                                ): ?>

                                                    <i class="fa-solid fa-image"></i>

                                                <?php else: ?>

                                                    <i class="fa-solid fa-copyright"></i>

                                                <?php endif; ?>

                                            </div>


                                            <div>

                                                <div class="brand-name">

                                                    <?= e(
                                                        $brand['name']
                                                    ) ?>

                                                </div>

                                                <div class="brand-slug">

                                                    /
                                                    <?= e(
                                                        $brand['slug']
                                                    ) ?>

                                                </div>

                                            </div>

                                        </div>

                                    </td>


                                    <!-- PARENT -->

                                    <td>

                                        <?php if (
                                            !empty(
                                                $brand['parent_name']
                                            )
                                        ): ?>

                                            <span class="parent-name">

                                                <i class="fa-solid fa-turn-up"></i>

                                                <?= e(
                                                    $brand['parent_name']
                                                ) ?>

                                            </span>

                                        <?php else: ?>

                                            <span class="root-badge">

                                                <i class="fa-solid fa-sitemap"></i>

                                                Root

                                            </span>

                                        <?php endif; ?>

                                    </td>


                                    <!-- TYPE -->

                                    <td>

                                        <span
                                            class="type-badge <?= e($typeClass) ?>"
                                        >

                                            <i class="fa-solid fa-tag"></i>

                                            <?= e(
                                                $brand['brand_type']
                                            ) ?>

                                        </span>

                                    </td>


                                    <!-- LOGO -->

                                    <td>

                                        <?php if (
                                            !empty(
                                                $brand['logo_id']
                                            )
                                        ): ?>

                                            <span
                                                style="
                                                    color:#475467;
                                                    font-size:10px;
                                                    font-weight:700;
                                                "
                                            >

                                                <i class="fa-solid fa-image"></i>

                                                #
                                                <?= e(
                                                    $brand['logo_id']
                                                ) ?>

                                            </span>

                                        <?php else: ?>

                                            <span
                                                style="
                                                    color:#98a2b3;
                                                    font-size:10px;
                                                "
                                            >
                                                Not assigned
                                            </span>

                                        <?php endif; ?>

                                    </td>


                                    <!-- STATUS -->

                                    <td>

                                        <?php if (
                                            (int)$brand['status'] === 1
                                        ): ?>

                                            <span class="status-badge status-active">

                                                <i class="fa-solid fa-circle-check"></i>

                                                Active

                                            </span>

                                        <?php else: ?>

                                            <span class="status-badge status-inactive">

                                                <i class="fa-solid fa-circle-xmark"></i>

                                                Inactive

                                            </span>

                                        <?php endif; ?>

                                    </td>


                                    <!-- FEATURED -->

                                    <td>

                                        <?php if (
                                            (int)$brand['featured'] === 1
                                        ): ?>

                                            <span class="featured-badge">

                                                <i class="fa-solid fa-star"></i>

                                                Featured

                                            </span>

                                        <?php else: ?>

                                            <span class="featured-badge normal-badge">

                                                <i class="fa-regular fa-star"></i>

                                                Normal

                                            </span>

                                        <?php endif; ?>

                                    </td>


                                    <!-- ORDER -->

                                    <td>

                                        <span class="sort-badge">

                                            <?= e(
                                                $brand['sort_order']
                                            ) ?>

                                        </span>

                                    </td>


                                    <!-- ACTIONS -->

                                    <td>

                                        <div class="actions">

                                            <a
                                                href="<?= e(
                                                    buildBrandUrl([
                                                        'edit' =>
                                                            $brand['id']
                                                    ])
                                                ) ?>"
                                                class="action-btn edit-btn"
                                                title="Edit Brand"
                                            >

                                                <i class="fa-solid fa-pen"></i>

                                            </a>


                                            <button
                                                type="button"
                                                class="action-btn delete-btn"
                                                title="Delete Brand"
                                                onclick="confirmDelete(<?= (int)$brand['id'] ?>)"
                                            >

                                                <i class="fa-solid fa-trash"></i>

                                            </button>

                                        </div>

                                    </td>

                                </tr>

                            <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php else: ?>

                <div class="empty-state">

                    <div class="empty-icon">

                        <i class="fa-solid fa-copyright"></i>

                    </div>

                    <h3>
                        No brands found
                    </h3>

                    <p>
                        No brand records match your current filters.
                        Add your first brand to get started.
                    </p>

                </div>

            <?php endif; ?>


            <!-- PAGINATION -->

            <?php if ($filteredTotal > 0): ?>

                <div class="pagination">

                    <div class="pagination-info">

                        Showing

                        <strong>
                            <?= number_format(
                                $offset + 1
                            ) ?>
                        </strong>

                        to

                        <strong>
                            <?= number_format(
                                min(
                                    $offset + $perPage,
                                    $filteredTotal
                                )
                            ) ?>
                        </strong>

                        of

                        <strong>
                            <?= number_format(
                                $filteredTotal
                            ) ?>
                        </strong>

                    </div>


                    <div class="pagination-links">

                        <?php if ($page > 1): ?>

                            <a
                                class="page-link"
                                href="<?= e(
                                    buildBrandUrl([
                                        'page' =>
                                            $page - 1
                                    ])
                                ) ?>"
                            >

                                <i class="fa-solid fa-chevron-left"></i>

                            </a>

                        <?php endif; ?>


                        <?php

                        $startPage =
                            max(
                                1,
                                $page - 2
                            );

                        $endPage =
                            min(
                                $totalPages,
                                $page + 2
                            );

                        for (
                            $p = $startPage;
                            $p <= $endPage;
                            $p++
                        ):
                        ?>

                            <a
                                class="page-link <?= $p === $page
                                    ? 'active'
                                    : '' ?>"
                                href="<?= e(
                                    buildBrandUrl([
                                        'page' => $p
                                    ])
                                ) ?>"
                            >

                                <?= $p ?>

                            </a>

                        <?php endfor; ?>


                        <?php if (
                            $page < $totalPages
                        ): ?>

                            <a
                                class="page-link"
                                href="<?= e(
                                    buildBrandUrl([
                                        'page' =>
                                            $page + 1
                                    ])
                                ) ?>"
                            >

                                <i class="fa-solid fa-chevron-right"></i>

                            </a>

                        <?php endif; ?>

                    </div>

                </div>

            <?php endif; ?>

        </div>

    </main>


    <footer class="page-footer">

        © <?= date('Y') ?> Pure Chemical.
        All rights reserved.

    </footer>

</div>


<!-- =============================================================
     ADD BRAND MODAL
============================================================== -->

<div
    class="modal-overlay"
    id="addModal"
>

    <div class="modal">

        <div class="modal-header">

            <div class="modal-heading">

                <div class="modal-heading-icon">

                    <i class="fa-solid fa-plus"></i>

                </div>

                <div>

                    <h2>
                        Add Brand
                    </h2>

                    <p>
                        Create a new brand record.
                    </p>

                </div>

            </div>


            <button
                type="button"
                class="modal-close"
                onclick="closeModal('addModal')"
            >

                <i class="fa-solid fa-xmark"></i>

            </button>

        </div>


        <form method="POST">

            <?= csrf_field() ?>

            <input
                type="hidden"
                name="action"
                value="add"
            >


            <div class="modal-body">

                <div class="modal-grid">

                    <!-- NAME -->

                    <div class="form-group">

                        <label class="form-label">

                            Brand Name

                            <span class="required">*</span>

                        </label>

                        <input
                            type="text"
                            name="name"
                            id="add_name"
                            class="form-control"
                            maxlength="255"
                            placeholder="Enter brand name"
                            required
                        >

                    </div>


                    <!-- TYPE -->

                    <div class="form-group">

                        <label class="form-label">

                            Brand Type

                            <span class="required">*</span>

                        </label>

                        <select
                            name="brand_type"
                            class="form-control"
                            required
                        >

                            <?php foreach (
                                $brandTypes
                                as $type
                            ): ?>

                                <option
                                    value="<?= e($type) ?>"
                                    <?= $type === 'brand'
                                        ? 'selected'
                                        : '' ?>
                                >

                                    <?= e(
                                        ucfirst($type)
                                    ) ?>

                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <!-- SLUG -->

                    <div class="form-group">

                        <label class="form-label">
                            Slug
                        </label>

                        <div class="slug-row">

                            <input
                                type="text"
                                name="slug"
                                id="add_slug"
                                class="form-control"
                                maxlength="255"
                                placeholder="brand-slug"
                            >

                            <button
                                type="button"
                                class="slug-btn"
                                onclick="generateAddSlug()"
                            >

                                <i class="fa-solid fa-wand-magic-sparkles"></i>

                                Generate

                            </button>

                        </div>

                    </div>


                    <!-- PARENT -->

                    <div class="form-group">

                        <label class="form-label">
                            Parent Brand
                        </label>

                        <select
                            name="parent_id"
                            class="form-control"
                        >

                            <option value="">
                                No Parent / Root Brand
                            </option>

                            <?php
                            renderBrandOptions(
                                0,
                                $brandTree
                            );
                            ?>

                        </select>

                    </div>


                    <!-- SHORT DESCRIPTION -->

                    <div class="form-group full">

                        <label class="form-label">
                            Short Description
                        </label>

                        <textarea
                            name="short_description"
                            class="form-control"
                            placeholder="Short description..."
                        ></textarea>

                    </div>


                    <!-- DESCRIPTION -->

                    <div class="form-group full">

                        <label class="form-label">
                            Description
                        </label>

                        <textarea
                            name="description"
                            class="form-control"
                            style="min-height:140px;"
                            placeholder="Full brand description..."
                        ></textarea>

                    </div>


                    <!-- WEBSITE -->

                    <div class="form-group full">

                        <label class="form-label">
                            Website URL
                        </label>

                        <input
                            type="url"
                            name="website_url"
                            class="form-control"
                            maxlength="1000"
                            placeholder="https://example.com"
                        >

                    </div>


                    <!-- LOGO -->

                    <div class="form-group">

                        <label class="form-label">
                            Logo Media ID
                        </label>

                        <input
                            type="number"
                            name="logo_id"
                            class="form-control"
                            min="0"
                            placeholder="Existing media ID"
                        >

                    </div>


                    <!-- BANNER -->

                    <div class="form-group">

                        <label class="form-label">
                            Banner Media ID
                        </label>

                        <input
                            type="number"
                            name="banner_id"
                            class="form-control"
                            min="0"
                            placeholder="Existing media ID"
                        >

                    </div>


                    <!-- SORT -->

                    <div class="form-group">

                        <label class="form-label">
                            Sort Order
                        </label>

                        <input
                            type="number"
                            name="sort_order"
                            class="form-control"
                            min="0"
                            value="0"
                        >

                    </div>


                    <!-- STATUS / FEATURED -->

                    <div class="form-group">

                        <label class="form-label">
                            Visibility
                        </label>

                        <div class="toggle-row">

                            <label class="toggle-box">

                                <input
                                    type="checkbox"
                                    name="status"
                                    value="1"
                                    checked
                                >

                                <span>

                                    <div class="toggle-title">
                                        Active
                                    </div>

                                    <div class="toggle-desc">
                                        Show this brand
                                    </div>

                                </span>

                            </label>


                            <label class="toggle-box">

                                <input
                                    type="checkbox"
                                    name="featured"
                                    value="1"
                                >

                                <span>

                                    <div class="toggle-title">
                                        Featured
                                    </div>

                                    <div class="toggle-desc">
                                        Mark as featured
                                    </div>

                                </span>

                            </label>

                        </div>

                    </div>

                </div>

            </div>


            <div class="modal-footer">

                <button
                    type="button"
                    class="btn btn-secondary"
                    onclick="closeModal('addModal')"
                >
                    Cancel
                </button>

                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i class="fa-solid fa-plus"></i>

                    Create Brand

                </button>

            </div>

        </form>

    </div>

</div>


<!-- =============================================================
     EDIT BRAND MODAL
============================================================== -->

<?php if ($editBrand): ?>

<div
    class="modal-overlay show"
    id="editModal"
>

    <div class="modal">

        <div class="modal-header">

            <div class="modal-heading">

                <div class="modal-heading-icon">

                    <i class="fa-solid fa-pen"></i>

                </div>

                <div>

                    <h2>
                        Edit Brand
                    </h2>

                    <p>
                        Update the selected brand.
                    </p>

                </div>

            </div>


            <a
                href="<?= e(
                    buildBrandUrl([
                        'edit' => null
                    ])
                ) ?>"
                class="modal-close"
            >

                <i class="fa-solid fa-xmark"></i>

            </a>

        </div>


        <form method="POST">

            <?= csrf_field() ?>

            <input
                type="hidden"
                name="action"
                value="update"
            >

            <input
                type="hidden"
                name="id"
                value="<?= e(
                    $editBrand['id']
                ) ?>"
            >


            <div class="modal-body">

                <div class="modal-grid">

                    <!-- NAME -->

                    <div class="form-group">

                        <label class="form-label">

                            Brand Name

                            <span class="required">*</span>

                        </label>

                        <input
                            type="text"
                            name="name"
                            id="edit_name"
                            class="form-control"
                            maxlength="255"
                            value="<?= e(
                                $editBrand['name']
                            ) ?>"
                            required
                        >

                    </div>


                    <!-- TYPE -->

                    <div class="form-group">

                        <label class="form-label">

                            Brand Type

                            <span class="required">*</span>

                        </label>

                        <select
                            name="brand_type"
                            class="form-control"
                            required
                        >

                            <?php foreach (
                                $brandTypes
                                as $type
                            ): ?>

                                <option
                                    value="<?= e($type) ?>"
                                    <?= $editBrand['brand_type'] === $type
                                        ? 'selected'
                                        : '' ?>
                                >

                                    <?= e(
                                        ucfirst($type)
                                    ) ?>

                                </option>

                            <?php endforeach; ?>

                        </select>

                    </div>


                    <!-- SLUG -->

                    <div class="form-group">

                        <label class="form-label">
                            Slug
                        </label>

                        <div class="slug-row">

                            <input
                                type="text"
                                name="slug"
                                id="edit_slug"
                                class="form-control"
                                maxlength="255"
                                value="<?= e(
                                    $editBrand['slug']
                                ) ?>"
                            >

                            <button
                                type="button"
                                class="slug-btn"
                                onclick="generateEditSlug()"
                            >

                                <i class="fa-solid fa-wand-magic-sparkles"></i>

                                Generate

                            </button>

                        </div>

                    </div>


                    <!-- PARENT -->

                    <div class="form-group">

                        <label class="form-label">
                            Parent Brand
                        </label>

                        <select
                            name="parent_id"
                            class="form-control"
                        >

                            <option value="">
                                No Parent / Root Brand
                            </option>

                            <?php
                            renderBrandOptions(
                                0,
                                $brandTree,
                                $editBrand['parent_id'] ?? 0,
                                $editBrand['id']
                            );
                            ?>

                        </select>

                    </div>


                    <!-- SHORT DESCRIPTION -->

                    <div class="form-group full">

                        <label class="form-label">
                            Short Description
                        </label>

                        <textarea
                            name="short_description"
                            class="form-control"
                        ><?= e(
                            $editBrand['short_description']
                        ) ?></textarea>

                    </div>


                    <!-- DESCRIPTION -->

                    <div class="form-group full">

                        <label class="form-label">
                            Description
                        </label>

                        <textarea
                            name="description"
                            class="form-control"
                            style="min-height:140px;"
                        ><?= e(
                            $editBrand['description']
                        ) ?></textarea>

                    </div>


                    <!-- WEBSITE -->

                    <div class="form-group full">

                        <label class="form-label">
                            Website URL
                        </label>

                        <input
                            type="url"
                            name="website_url"
                            class="form-control"
                            maxlength="1000"
                            value="<?= e(
                                $editBrand['website_url']
                            ) ?>"
                            placeholder="https://example.com"
                        >

                    </div>


                    <!-- LOGO -->

                    <div class="form-group">

                        <label class="form-label">
                            Logo Media ID
                        </label>

                        <input
                            type="number"
                            name="logo_id"
                            class="form-control"
                            min="0"
                            value="<?= e(
                                $editBrand['logo_id']
                            ) ?>"
                        >

                    </div>


                    <!-- BANNER -->

                    <div class="form-group">

                        <label class="form-label">
                            Banner Media ID
                        </label>

                        <input
                            type="number"
                            name="banner_id"
                            class="form-control"
                            min="0"
                            value="<?= e(
                                $editBrand['banner_id']
                            ) ?>"
                        >

                    </div>


                    <!-- SORT -->

                    <div class="form-group">

                        <label class="form-label">
                            Sort Order
                        </label>

                        <input
                            type="number"
                            name="sort_order"
                            class="form-control"
                            min="0"
                            value="<?= e(
                                $editBrand['sort_order']
                            ) ?>"
                        >

                    </div>


                    <!-- STATUS / FEATURED -->

                    <div class="form-group">

                        <label class="form-label">
                            Visibility
                        </label>

                        <div class="toggle-row">

                            <label class="toggle-box">

                                <input
                                    type="checkbox"
                                    name="status"
                                    value="1"
                                    <?= (int)$editBrand['status'] === 1
                                        ? 'checked'
                                        : '' ?>
                                >

                                <span>

                                    <div class="toggle-title">
                                        Active
                                    </div>

                                    <div class="toggle-desc">
                                        Show this brand
                                    </div>

                                </span>

                            </label>


                            <label class="toggle-box">

                                <input
                                    type="checkbox"
                                    name="featured"
                                    value="1"
                                    <?= (int)$editBrand['featured'] === 1
                                        ? 'checked'
                                        : '' ?>
                                >

                                <span>

                                    <div class="toggle-title">
                                        Featured
                                    </div>

                                    <div class="toggle-desc">
                                        Mark as featured
                                    </div>

                                </span>

                            </label>

                        </div>

                    </div>

                </div>

            </div>


            <div class="modal-footer">

                <a
                    href="<?= e(
                        buildBrandUrl([
                            'edit' => null
                        ])
                    ) ?>"
                    class="btn btn-secondary"
                >
                    Cancel
                </a>

                <button
                    type="submit"
                    class="btn btn-primary"
                >

                    <i class="fa-solid fa-check"></i>

                    Save Changes

                </button>

            </div>

        </form>

    </div>

</div>

<?php endif; ?>


<!-- =============================================================
     DELETE FORM
============================================================== -->

<form
    method="POST"
    id="deleteForm"
    style="display:none;"
>

    <?= csrf_field() ?>

    <input
        type="hidden"
        name="action"
        value="delete"
    >

    <input
        type="hidden"
        name="id"
        id="deleteId"
        value=""
    >

</form>


<script>

/*
|--------------------------------------------------------------------------
| Add Modal
|--------------------------------------------------------------------------
*/

function openAddModal() {

    const modal =
        document.getElementById(
            'addModal'
        );

    if (!modal) {
        return;
    }

    modal.classList.add(
        'show'
    );

    document.body.style.overflow =
        'hidden';
}


/*
|--------------------------------------------------------------------------
| Close Modal
|--------------------------------------------------------------------------
*/

function closeModal(id) {

    const modal =
        document.getElementById(id);

    if (!modal) {
        return;
    }

    modal.classList.remove(
        'show'
    );

    document.body.style.overflow =
        '';
}


/*
|--------------------------------------------------------------------------
| Slug Generator
|--------------------------------------------------------------------------
*/

function makeSlug(value) {

    return value
        .toString()
        .toLowerCase()
        .trim()
        .normalize('NFD')
        .replace(
            /[\u0300-\u036f]/g,
            ''
        )
        .replace(
            /[^a-z0-9]+/g,
            '-'
        )
        .replace(
            /^-+|-+$/g,
            ''
        );
}


function generateAddSlug() {

    const name =
        document.getElementById(
            'add_name'
        );

    const slug =
        document.getElementById(
            'add_slug'
        );

    if (!name || !slug) {
        return;
    }

    slug.value =
        makeSlug(
            name.value
        );
}


function generateEditSlug() {

    const name =
        document.getElementById(
            'edit_name'
        );

    const slug =
        document.getElementById(
            'edit_slug'
        );

    if (!name || !slug) {
        return;
    }

    slug.value =
        makeSlug(
            name.value
        );
}


/*
|--------------------------------------------------------------------------
| Delete Confirmation
|--------------------------------------------------------------------------
*/

function confirmDelete(id) {

    const confirmed =
        confirm(
            'Are you sure you want to delete this brand?\n\n' +
            'This action cannot be undone.'
        );

    if (!confirmed) {
        return;
    }

    document.getElementById(
        'deleteId'
    ).value = id;

    document.getElementById(
        'deleteForm'
    ).submit();
}


/*
|--------------------------------------------------------------------------
| Overlay Click
|--------------------------------------------------------------------------
*/

document.addEventListener(
    'click',
    function(event) {

        if (
            event.target.classList.contains(
                'modal-overlay'
            )
        ) {

            event.target.classList.remove(
                'show'
            );

            document.body.style.overflow =
                '';

        }

    }
);


/*
|--------------------------------------------------------------------------
| Escape
|--------------------------------------------------------------------------
*/

document.addEventListener(
    'keydown',
    function(event) {

        if (
            event.key !== 'Escape'
        ) {
            return;
        }

        document
            .querySelectorAll(
                '.modal-overlay.show'
            )
            .forEach(
                function(modal) {

                    modal.classList.remove(
                        'show'
                    );

                }
            );

        document.body.style.overflow =
            '';

    }
);


/*
|--------------------------------------------------------------------------
| Auto Slug Preview
|--------------------------------------------------------------------------
*/

const addName =
    document.getElementById(
        'add_name'
    );

const addSlug =
    document.getElementById(
        'add_slug'
    );

classCheck = true;

if (
    addName &&
    addSlug
) {

    addName.addEventListener(
        'input',
        function() {

            if (
                addSlug.dataset.manual !== '1'
            ) {

                addSlug.value =
                    makeSlug(
                        addName.value
                    );

            }

        }
    );

    addSlug.addEventListener(
        'input',
        function() {

            addSlug.dataset.manual =
                '1';

        }
    );
}

</script>

</body>

</html>