<?php
/**
 * Pure Chemical Admin - Brand Manager
 * Uses existing brands and media tables only.
 */
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once __DIR__ . '/includes/db.php';
if (file_exists(__DIR__ . '/includes/auth.php')) require_once __DIR__ . '/includes/auth.php';
if (function_exists('requireAdmin')) requireAdmin();
if (file_exists(__DIR__ . '/includes/functions.php')) require_once __DIR__ . '/includes/functions.php';
if (file_exists(__DIR__ . '/includes/csrf.php')) require_once __DIR__ . '/includes/csrf.php';

if (!function_exists('e')) {
    function e($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('add_brand_slugify')) {
    function add_brand_slugify($text) {
        $text = function_exists('mb_strtolower') ? mb_strtolower(trim((string)$text), 'UTF-8') : strtolower(trim((string)$text));
        return trim((string)preg_replace('/[^\pL\pN]+/u', '-', $text), '-');
    }
}
if (empty($_SESSION['add_brand_csrf'])) $_SESSION['add_brand_csrf'] = bin2hex(random_bytes(32));
function add_brand_csrf_field() {
    return '<input type="hidden" name="csrf_token" value="' . e($_SESSION['add_brand_csrf'] ?? '') . '">';
}
function add_brand_verify_csrf() {
    return isset($_SESSION['add_brand_csrf'], $_POST['csrf_token']) &&
        hash_equals($_SESSION['add_brand_csrf'], (string)$_POST['csrf_token']);
}
function brand_flash_redirect($type, $message, $url = 'add_brand.php') {
    $_SESSION['add_brand_flash'] = ['type'=>$type, 'message'=>$message];
    header('Location: ' . $url);
    exit;
}
function brand_upload_image(PDO $pdo, string $field): ?int {
    if (!isset($_FILES[$field]) || ($_FILES[$field]['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) return null;
    $file = $_FILES[$field];
    if (($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) throw new RuntimeException('Image upload failed. Please try again.');
    if (($file['size'] ?? 0) > 8 * 1024 * 1024) throw new RuntimeException('Image size must be 8 MB or less.');
    $tmp = $file['tmp_name'] ?? '';
    if (!$tmp || !is_uploaded_file($tmp)) throw new RuntimeException('Invalid uploaded image.');
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($tmp);
    $allowed = ['image/jpeg'=>'jpg','image/png'=>'png','image/webp'=>'webp','image/gif'=>'gif'];
    if (!isset($allowed[$mime])) throw new RuntimeException('Only JPG, PNG, WEBP or GIF images are allowed.');
    $uploadDir = dirname(__DIR__) . '/uploads/media';
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) throw new RuntimeException('Could not create uploads/media folder.');
    if (!is_writable($uploadDir)) throw new RuntimeException('The uploads/media folder is not writable.');
    $ext = $allowed[$mime];
    $fileName = bin2hex(random_bytes(16)) . '.' . $ext;
    if (!move_uploaded_file($tmp, $uploadDir . '/' . $fileName)) throw new RuntimeException('Could not store the uploaded image.');
    $relativePath = 'uploads/media/' . $fileName;
    try {
        $stmt = $pdo->prepare("INSERT INTO media (original_name, file_name, file_path, mime_type, file_type, extension, file_size, status) VALUES (?, ?, ?, ?, 'image', ?, ?, 1)");
        $stmt->execute([substr(basename((string)$file['name']), 0, 255), $fileName, $relativePath, $mime, $ext, (int)$file['size']]);
        return (int)$pdo->lastInsertId();
    } catch (Throwable $ex) {
        @unlink($uploadDir . '/' . $fileName);
        throw $ex;
    }
}
$flash = $_SESSION['add_brand_flash'] ?? null;
unset($_SESSION['add_brand_flash']);
$errors = [];
$editId = isset($_GET['edit']) && ctype_digit((string)$_GET['edit']) ? (int)$_GET['edit'] : 0;
$form = [
    'parent_id'=>'','name'=>'','slug'=>'','brand_type'=>'brand','short_description'=>'',
    'description'=>'','website_url'=>'','logo_id'=>'','banner_id'=>'','status'=>'1',
    'featured'=>'0','sort_order'=>'0'
];

$brandTypeOptions = [];
try {
    $enumStmt = $pdo->query("SHOW COLUMNS FROM brands LIKE 'brand_type'");
    $enumColumn = $enumStmt->fetch(PDO::FETCH_ASSOC);
    if ($enumColumn && preg_match("/^enum\\((.*)\\)$/i", $enumColumn['Type'] ?? '', $matches)) {
        foreach (str_getcsv($matches[1], ',', "'") as $value) {
            $value = str_replace("''", "'", $value);
            if ($value !== '') $brandTypeOptions[] = $value;
        }
    }
} catch (Throwable $ex) {}
if (!$brandTypeOptions) $brandTypeOptions = ['brand','principal','division','partner'];
$form['brand_type'] = $brandTypeOptions[0];

if ($editId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM brands WHERE id = ? LIMIT 1");
    $stmt->execute([$editId]);
    $editBrand = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$editBrand) {
        $editId = 0;
        $flash = ['type'=>'error','message'=>'Brand not found.'];
    } else {
        foreach ($form as $key => $value) {
            if (array_key_exists($key, $editBrand)) $form[$key] = $editBrand[$key] === null ? '' : (string)$editBrand[$key];
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['form_action'] ?? 'save');
    if (!add_brand_verify_csrf()) {
        $errors[] = 'Security verification failed. Refresh the page and try again.';
    } elseif ($action === 'delete') {
        $id = filter_var($_POST['brand_id'] ?? null, FILTER_VALIDATE_INT, ['options'=>['min_range'=>1]]);
        if (!$id) {
            brand_flash_redirect('error', 'Invalid brand selected.');
        }
        try {
            $check = $pdo->prepare("SELECT id FROM brands WHERE parent_id = ? LIMIT 1");
            $check->execute([$id]);
            if ($check->fetch()) brand_flash_redirect('error', 'This brand has child brands. Move or delete its child brands before deleting it.');
            $del = $pdo->prepare("DELETE FROM brands WHERE id = ?");
            $del->execute([$id]);
            brand_flash_redirect('success', $del->rowCount() ? 'Brand deleted successfully.' : 'Brand was not found.');
        } catch (Throwable $ex) {
            error_log('Brand delete failed: '.$ex->getMessage());
            brand_flash_redirect('error', 'Brand could not be deleted. It may be referenced by another record.');
        }
    } else {
        $editId = (int)($_POST['brand_id'] ?? 0);
        foreach (['parent_id','name','slug','brand_type','short_description','description','website_url','logo_id','banner_id','sort_order'] as $key) {
            $form[$key] = trim((string)($_POST[$key] ?? ''));
        }
        $form['status'] = isset($_POST['status']) ? '1' : '0';
        $form['featured'] = isset($_POST['featured']) ? '1' : '0';
        if ($form['name'] === '') $errors[] = 'Brand name is required.';
        if (function_exists('mb_strlen') ? mb_strlen($form['name'], 'UTF-8') > 255 : strlen($form['name']) > 255) $errors[] = 'Brand name cannot exceed 255 characters.';
        $form['slug'] = add_brand_slugify($form['slug'] !== '' ? $form['slug'] : $form['name']);
        if ($form['slug'] === '') $errors[] = 'A valid slug is required.';
        if (!in_array($form['brand_type'], $brandTypeOptions, true)) $errors[] = 'Please select a valid brand type.';
        $parentId = $form['parent_id'] !== '' ? (int)$form['parent_id'] : null;
        if ($parentId !== null && ($parentId <= 0 || $parentId === $editId)) $errors[] = 'Please select a valid parent brand.';
        if ($form['website_url'] !== '') {
            if (!filter_var($form['website_url'], FILTER_VALIDATE_URL) || !in_array(strtolower((string)parse_url($form['website_url'], PHP_URL_SCHEME)), ['http','https'], true)) $errors[] = 'Website URL must be a valid http:// or https:// URL.';
        }
        foreach (['logo_id','banner_id'] as $mediaField) {
            if ($form[$mediaField] !== '' && (!ctype_digit($form[$mediaField]) || (int)$form[$mediaField] < 1)) $errors[] = 'Invalid media selection.';
        }
        if ($parentId !== null && !$errors) {
            $q = $pdo->prepare("SELECT id FROM brands WHERE id = ? LIMIT 1");
            $q->execute([$parentId]);
            if (!$q->fetch()) $errors[] = 'Selected parent brand does not exist.';
        }
        if (!$errors) {
            $slugSql = "SELECT id FROM brands WHERE slug = ? AND id <> ? LIMIT 1";
            $q = $pdo->prepare($slugSql);
            $q->execute([$form['slug'], $editId]);
            if ($q->fetch()) $errors[] = 'This slug is already used by another brand.';
        }
        if (!$errors) {
            try {
                $pdo->beginTransaction();
                $newLogo = brand_upload_image($pdo, 'logo_upload');
                $newBanner = brand_upload_image($pdo, 'banner_upload');
                if ($newLogo !== null) $form['logo_id'] = (string)$newLogo;
                if ($newBanner !== null) $form['banner_id'] = (string)$newBanner;
                foreach (['logo_id','banner_id'] as $mediaField) {
                    if ($form[$mediaField] !== '') {
                        $m = $pdo->prepare("SELECT id FROM media WHERE id = ? AND file_type = 'image' LIMIT 1");
                        $m->execute([(int)$form[$mediaField]]);
                        if (!$m->fetch()) throw new RuntimeException('Selected logo/banner was not found as an active image in the Media library.');
                    }
                }
                $params = [
                    $parentId, $form['name'], $form['slug'], $form['brand_type'],
                    $form['short_description'] !== '' ? $form['short_description'] : null,
                    $form['description'] !== '' ? $form['description'] : null,
                    $form['website_url'] !== '' ? $form['website_url'] : null,
                    $form['logo_id'] !== '' ? (int)$form['logo_id'] : null,
                    $form['banner_id'] !== '' ? (int)$form['banner_id'] : null,
                    (int)$form['status'], (int)$form['featured'], max(0, (int)$form['sort_order'])
                ];
                if ($editId > 0) {
                    $params[] = $editId;
                    $stmt = $pdo->prepare("UPDATE brands SET parent_id=?, name=?, slug=?, brand_type=?, short_description=?, description=?, website_url=?, logo_id=?, banner_id=?, status=?, featured=?, sort_order=? WHERE id=?");
                    $stmt->execute($params);
                    $message = 'Brand updated successfully.';
                } else {
                    $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 (?,?,?,?,?,?,?,?,?,?,?,?)");
                    $stmt->execute($params);
                    $editId = (int)$pdo->lastInsertId();
                    $message = 'Brand added successfully.';
                }
                $pdo->commit();
                brand_flash_redirect('success', $message);
            } catch (Throwable $ex) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                error_log('Brand save failed: '.$ex->getMessage());
                $errors[] = $ex instanceof RuntimeException ? $ex->getMessage() : 'Brand could not be saved. Please verify the database fields and try again.';
            }
        }
    }
}
$parentBrands = $pdo->query("SELECT id, parent_id, name, slug, brand_type FROM brands ORDER BY sort_order ASC, name ASC")->fetchAll(PDO::FETCH_ASSOC);
$mediaImages = [];
try {
    $mediaImages = $pdo->query("SELECT id, original_name, file_path, mime_type FROM media WHERE file_type='image' ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $ex) {}
$brandsList = $pdo->query("SELECT b.*, lm.original_name AS logo_name, lm.file_path AS logo_path, bm.original_name AS banner_name, bm.file_path AS banner_path FROM brands b LEFT JOIN media lm ON lm.id=b.logo_id LEFT JOIN media bm ON bm.id=b.banner_id ORDER BY b.sort_order ASC, b.id DESC")->fetchAll(PDO::FETCH_ASSOC);
$adminName = $_SESSION['ADMIN_NAME'] ?? $_SESSION['admin_name'] ?? $_SESSION['name'] ?? 'Administrator';
$adminRole = $_SESSION['ADMIN_ROLE'] ?? $_SESSION['admin_role'] ?? 'Administrator';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>Brand Manager | Pure Chemical Admin</title>

    <meta
        name="robots"
        content="noindex,nofollow"
    >

    <link
        rel="preconnect"
        href="https://fonts.googleapis.com"
    >

    <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossorigin
    >

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
        rel="stylesheet"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
    >

    <style>

        :root {
            --pc-primary: #0f766e;
            --pc-primary-dark: #115e59;
            --pc-primary-soft: #ecfdf5;

            --pc-bg: #f5f7fb;
            --pc-card: #ffffff;
            --pc-text: #172033;
            --pc-muted: #6b7280;
            --pc-border: #e5e7eb;

            --pc-success: #15803d;
            --pc-danger: #dc2626;
            --pc-warning: #d97706;

            --pc-shadow:
                0 10px 35px rgba(15, 23, 42, .07);

            --pc-radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            padding: 0;
            background: var(--pc-bg);
            color: var(--pc-text);
            font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont,
                "Segoe UI", sans-serif;
            -webkit-font-smoothing: antialiased;
        }

        button,
        input,
        select,
        textarea {
            font-family: inherit;
        }

        a {
            text-decoration: none;
        }


        /* =====================================================
           MAIN LAYOUT
        ===================================================== */

        .pc-page {
            margin-left: 280px;
            min-height: 100vh;
        }


        /* =====================================================
           PREMIUM STICKY TOPBAR
        ===================================================== */

        .pc-topbar {
            position: sticky;
            top: 0;
            z-index: 900;

            height: 76px;

            display: flex;
            align-items: center;
            justify-content: space-between;

            padding: 0 30px;

            background: rgba(255, 255, 255, .88);
            backdrop-filter: blur(18px);
            -webkit-backdrop-filter: blur(18px);

            border-bottom: 1px solid rgba(226, 232, 240, .9);

            box-shadow:
                0 8px 30px rgba(15, 23, 42, .045);
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 16px;
            min-width: 0;
        }

        .page-icon {
            width: 44px;
            height: 44px;

            display: flex;
            align-items: center;
            justify-content: center;

            flex: 0 0 44px;

            color: #ffffff;
            background:
                linear-gradient(
                    135deg,
                    var(--pc-primary),
                    #14b8a6
                );

            border-radius: 13px;

            box-shadow:
                0 8px 20px rgba(15, 118, 110, .22);
        }

        .page-heading {
            min-width: 0;
        }

        .page-heading h1 {
            margin: 0;

            font-size: 17px;
            line-height: 1.3;
            font-weight: 800;

            letter-spacing: -.02em;

            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .breadcrumb {
            margin-top: 4px;

            display: flex;
            align-items: center;
            gap: 7px;

            color: var(--pc-muted);

            font-size: 12px;
            font-weight: 500;
        }

        .breadcrumb a {
            color: var(--pc-primary);
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .admin-pill {
            display: flex;
            align-items: center;
            gap: 10px;

            padding: 7px 12px 7px 7px;

            background: #ffffff;

            border: 1px solid var(--pc-border);
            border-radius: 14px;
        }

        .admin-avatar {
            width: 34px;
            height: 34px;

            display: flex;
            align-items: center;
            justify-content: center;

            color: #ffffff;

            background:
                linear-gradient(
                    135deg,
                    #0f766e,
                    #14b8a6
                );

            border-radius: 10px;

            font-size: 13px;
            font-weight: 800;
        }

        .admin-info strong {
            display: block;

            max-width: 150px;

            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;

            font-size: 12px;
            font-weight: 700;
        }

        .admin-info span {
            display: block;
            margin-top: 1px;

            color: var(--pc-muted);

            font-size: 10px;
            font-weight: 500;
        }


        /* =====================================================
           CONTENT
        ===================================================== */

        .pc-content {
            padding: 30px;
            max-width: 1500px;
            margin: 0 auto;
        }


        /* =====================================================
           PAGE INTRO
        ===================================================== */

        .content-header {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 20px;

            margin-bottom: 24px;
        }

        .content-title h2 {
            margin: 0;

            font-size: 27px;
            line-height: 1.2;
            font-weight: 800;

            letter-spacing: -.04em;
        }

        .content-title p {
            margin: 8px 0 0;

            color: var(--pc-muted);

            font-size: 14px;
            line-height: 1.6;
        }

        .header-actions {
            display: flex;
            gap: 10px;
        }


        /* =====================================================
           BUTTONS
        ===================================================== */

        .btn {
            min-height: 44px;

            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 9px;

            padding: 0 16px;

            border: 1px solid transparent;
            border-radius: 12px;

            cursor: pointer;

            font-size: 13px;
            font-weight: 700;

            transition:
                transform .18s ease,
                box-shadow .18s ease,
                background .18s ease,
                border-color .18s ease;
        }

        .btn:hover {
            transform: translateY(-1px);
        }

        .btn-primary {
            color: #ffffff;

            background:
                linear-gradient(
                    135deg,
                    var(--pc-primary),
                    #0d9488
                );

            box-shadow:
                0 8px 18px rgba(15, 118, 110, .18);
        }

        .btn-primary:hover {
            box-shadow:
                0 11px 25px rgba(15, 118, 110, .25);
        }

        .btn-light {
            color: var(--pc-text);
            background: #ffffff;
            border-color: var(--pc-border);
        }

        .btn-light:hover {
            background: #f8fafc;
        }


        /* =====================================================
           ALERTS
        ===================================================== */

        .alert {
            display: flex;
            align-items: flex-start;
            gap: 12px;

            padding: 15px 17px;

            margin-bottom: 22px;

            border-radius: 14px;

            font-size: 13px;
            line-height: 1.55;
        }

        .alert i {
            margin-top: 2px;
        }

        .alert-danger {
            color: #991b1b;
            background: #fef2f2;
            border: 1px solid #fecaca;
        }

        .alert-success {
            color: #166534;
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
        }

        .error-list {
            margin: 7px 0 0;
            padding-left: 20px;
        }


        /* =====================================================
           FORM GRID
        ===================================================== */

        .form-layout {
            display: grid;

            grid-template-columns:
                minmax(0, 1.7fr)
                minmax(320px, .85fr);

            gap: 22px;

            align-items: start;
        }

        .card {
            background: var(--pc-card);

            border: 1px solid rgba(226, 232, 240, .95);

            border-radius: var(--pc-radius);

            box-shadow: var(--pc-shadow);
        }

        .card-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;

            padding: 20px 22px;

            border-bottom: 1px solid var(--pc-border);
        }

        .card-header h3 {
            margin: 0;

            font-size: 15px;
            font-weight: 800;
        }

        .card-header p {
            margin: 5px 0 0;

            color: var(--pc-muted);

            font-size: 11px;
            line-height: 1.5;
        }

        .card-body {
            padding: 22px;
        }


        /* =====================================================
           FORM FIELDS
        ===================================================== */

        .field-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 18px;
        }

        .field-full {
            grid-column: 1 / -1;
        }

        .form-group {
            min-width: 0;
        }

        .form-label {
            display: flex;
            align-items: center;
            gap: 4px;

            margin-bottom: 8px;

            font-size: 12px;
            font-weight: 700;

            color: #374151;
        }

        .required {
            color: var(--pc-danger);
        }

        .form-control,
        .form-select,
        .form-textarea {
            width: 100%;

            border: 1px solid #dfe4ea;

            background: #ffffff;

            color: var(--pc-text);

            border-radius: 11px;

            outline: none;

            font-size: 13px;

            transition:
                border-color .18s ease,
                box-shadow .18s ease,
                background .18s ease;
        }

        .form-control,
        .form-select {
            height: 46px;
            padding: 0 13px;
        }

        .form-textarea {
            min-height: 135px;
            padding: 12px 13px;
            resize: vertical;
            line-height: 1.6;
        }

        .form-control:focus,
        .form-select:focus,
        .form-textarea:focus {
            border-color: var(--pc-primary);

            box-shadow:
                0 0 0 4px rgba(15, 118, 110, .09);
        }

        .form-help {
            margin-top: 6px;

            color: #8a94a6;

            font-size: 10px;
            line-height: 1.5;
        }


        /* =====================================================
           INPUT WITH ICON
        ===================================================== */

        .input-wrap {
            position: relative;
        }

        .input-wrap > i {
            position: absolute;

            left: 13px;
            top: 50%;

            transform: translateY(-50%);

            color: #9ca3af;

            font-size: 13px;

            pointer-events: none;
        }

        .input-wrap .form-control {
            padding-left: 39px;
        }


        /* =====================================================
           TOGGLE
        ===================================================== */

        .toggle-row {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 12px;
        }

        .toggle-box {
            position: relative;
        }

        .toggle-box input {
            position: absolute;
            opacity: 0;
            pointer-events: none;
        }

        .toggle-label {
            min-height: 64px;

            display: flex;
            align-items: center;
            gap: 12px;

            padding: 12px 14px;

            border: 1px solid var(--pc-border);
            border-radius: 13px;

            background: #ffffff;

            cursor: pointer;

            transition:
                border-color .18s ease,
                background .18s ease,
                box-shadow .18s ease;
        }

        .toggle-icon {
            width: 37px;
            height: 37px;

            display: flex;
            align-items: center;
            justify-content: center;

            flex: 0 0 37px;

            color: var(--pc-muted);

            background: #f3f4f6;

            border-radius: 10px;

            transition: .18s ease;
        }

        .toggle-content strong {
            display: block;

            font-size: 12px;
            font-weight: 800;
        }

        .toggle-content span {
            display: block;

            margin-top: 3px;

            color: var(--pc-muted);

            font-size: 10px;
        }

        .toggle-box input:checked + .toggle-label {
            border-color: rgba(15, 118, 110, .4);

            background: var(--pc-primary-soft);

            box-shadow:
                0 6px 18px rgba(15, 118, 110, .08);
        }

        .toggle-box input:checked + .toggle-label .toggle-icon {
            color: #ffffff;

            background: var(--pc-primary);
        }


        /* =====================================================
           SIDE SETTINGS
        ===================================================== */

        .side-card {
            position: sticky;
            top: 98px;
        }

        .setting-item {
            padding: 16px 0;

            border-bottom: 1px solid var(--pc-border);
        }

        .setting-item:first-child {
            padding-top: 0;
        }

        .setting-item:last-child {
            padding-bottom: 0;
            border-bottom: 0;
        }

        .setting-title {
            margin-bottom: 9px;

            font-size: 11px;
            font-weight: 800;

            color: #4b5563;

            text-transform: uppercase;
            letter-spacing: .07em;
        }


        /* =====================================================
           INFO BOX
        ===================================================== */

        .info-box {
            display: flex;
            align-items: flex-start;
            gap: 11px;

            margin-top: 18px;
            padding: 13px;

            background: #f8fafc;

            border: 1px solid #e5e7eb;

            border-radius: 12px;
        }

        .info-icon {
            width: 31px;
            height: 31px;

            display: flex;
            align-items: center;
            justify-content: center;

            flex: 0 0 31px;

            color: var(--pc-primary);

            background: var(--pc-primary-soft);

            border-radius: 9px;

            font-size: 12px;
        }

        .info-box p {
            margin: 0;

            color: #64748b;

            font-size: 10px;
            line-height: 1.6;
        }


        /* =====================================================
           FORM FOOTER
        ===================================================== */

        .form-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;

            margin-top: 24px;
            padding-top: 20px;

            border-top: 1px solid var(--pc-border);
        }

        .form-footer-note {
            color: var(--pc-muted);

            font-size: 11px;
            line-height: 1.5;
        }

        .form-actions {
            display: flex;
            gap: 10px;
        }


        /* =====================================================
           RESPONSIVE
        ===================================================== */

        @media (max-width: 1180px) {

            .pc-page {
                margin-left: 0;
            }

            .form-layout {
                grid-template-columns: 1fr;
            }

            .side-card {
                position: static;
            }
        }


        @media (max-width: 800px) {

            .pc-topbar {
                height: auto;
                min-height: 70px;

                padding: 12px 16px;
            }

            .admin-info {
                display: none;
            }

            .pc-content {
                padding: 20px 16px;
            }

            .content-header {
                flex-direction: column;
            }

            .field-grid {
                grid-template-columns: 1fr;
            }

            .field-full {
                grid-column: auto;
            }

            .toggle-row {
                grid-template-columns: 1fr;
            }

            .form-footer {
                flex-direction: column;
                align-items: stretch;
            }

            .form-actions {
                width: 100%;
            }

            .form-actions .btn {
                flex: 1;
            }
        }


        @media (max-width: 560px) {

            .page-heading {
                display: none;
            }

            .topbar-left {
                gap: 0;
            }

            .content-title h2 {
                font-size: 23px;
            }

            .card-header,
            .card-body {
                padding: 17px;
            }

            .header-actions {
                width: 100%;
            }

            .header-actions .btn {
                flex: 1;
            }
        }

    </style>
</head>

<body>

<?php
/*
|--------------------------------------------------------------------------
| Existing Sidebar
|--------------------------------------------------------------------------
|
| IMPORTANT:
| admin/sidebar.php is included separately.
| admin/header.php is intentionally NOT included here,
| so duplicate sidebar/topbar nahi aayega.
|
*/
require_once __DIR__ . '/sidebar.php';
?>


<div class="pc-page">

    <!-- =====================================================
         STICKY TOPBAR
    ====================================================== -->

    <header class="pc-topbar">

        <div class="topbar-left">

            <div class="page-icon">
                <i class="fa-solid fa-copyright"></i>
            </div>

            <div class="page-heading">

                <h1>
                    Add Brand
                </h1>

                <div class="breadcrumb">

                    <a href="index.php">
                        Dashboard
                    </a>

                    <i class="fa-solid fa-chevron-right"></i>

                    <a href="brands.php">
                        Brands
                    </a>

                    <i class="fa-solid fa-chevron-right"></i>

                    <span>
                        <?php echo $editId > 0 ? 'Edit Brand' : 'Add Brand'; ?>
                    </span>

                </div>

            </div>

        </div>


        <div class="topbar-right">

            <div class="admin-pill">

                <div class="admin-avatar">
                    <?php
                    echo e(
                        strtoupper(
                            substr(
                                trim($adminName),
                                0,
                                1
                            )
                        )
                    );
                    ?>
                </div>

                <div class="admin-info">

                    <strong>
                        <?php echo e($adminName); ?>
                    </strong>

                    <span>
                        <?php echo e($adminRole); ?>
                    </span>

                </div>

            </div>

        </div>

    </header>


    <!-- =====================================================
         CONTENT
    ====================================================== -->

    <main class="pc-content">

        <!-- PAGE HEADER -->

        <div class="content-header">

            <div class="content-title">

                <h2>
                    <?php echo $editId > 0 ? 'Edit Brand' : 'Create New Brand'; ?>
                </h2>

                <p>
Manage brands, media uploads, visibility and ordering from one place.
                </p>

            </div>

            <div class="header-actions">

                <a
                    href="brands.php"
                    class="btn btn-light"
                >
                    <i class="fa-solid fa-arrow-left"></i>
                    Back to Brands
                </a>

            </div>

        </div>


        <!-- =================================================
             FLASH MESSAGE
        ================================================== -->

        <?php if ($flash): ?>

            <div
                class="alert
                <?php echo ($flash['type'] ?? '') === 'success'
                    ? 'alert-success'
                    : 'alert-danger'; ?>"
            >

                <i class="fa-solid
                    <?php echo ($flash['type'] ?? '') === 'success'
                        ? 'fa-circle-check'
                        : 'fa-circle-exclamation'; ?>">
                </i>

                <div>
                    <?php echo e($flash['message'] ?? ''); ?>
                </div>

            </div>

        <?php endif; ?>


        <!-- =================================================
             VALIDATION ERRORS
        ================================================== -->

        <?php if ($errors): ?>

            <div class="alert alert-danger">

                <i class="fa-solid fa-circle-exclamation"></i>

                <div>

                    <strong>
                        Please fix the following:
                    </strong>

                    <ul class="error-list">

                        <?php foreach ($errors as $error): ?>

                            <li>
                                <?php echo e($error); ?>
                            </li>

                        <?php endforeach; ?>

                    </ul>

                </div>

            </div>

        <?php endif; ?>


        <!-- =================================================
             FORM
        ================================================== -->

        <form
            method="post"
            action=""
            autocomplete="off"
            id="brandForm"
            enctype="multipart/form-data"
        >

            <?php echo add_brand_csrf_field(); ?>

            <input type="hidden" name="form_action" value="save">
            <input type="hidden" name="brand_id" value="<?php echo (int)$editId; ?>">


            <div class="form-layout">


                <!-- =========================================
                     MAIN FORM
                ========================================== -->

                <section class="card">

                    <div class="card-header">

                        <div>

                            <h3>
                                <i
                                    class="fa-solid fa-building-circle-check"
                                    style="color:#0f766e;margin-right:7px;"
                                ></i>

                                Brand Information
                            </h3>

                            <p>
                                Enter the basic information that will
                                be used across the website.
                            </p>

                        </div>

                    </div>


                    <div class="card-body">

                        <div class="field-grid">


                            <!-- BRAND NAME -->

                            <div class="form-group field-full">

                                <label class="form-label">
                                    Brand Name
                                    <span class="required">*</span>
                                </label>

                                <div class="input-wrap">

                                    <i class="fa-solid fa-copyright"></i>

                                    <input
                                        type="text"
                                        name="name"
                                        id="brandName"
                                        class="form-control"
                                        value="<?php echo e($form['name']); ?>"
                                        maxlength="255"
                                        placeholder="Enter brand name"
                                        required
                                    >

                                </div>

                                <div class="form-help">
                                    Main public name of the brand.
                                </div>

                            </div>


                            <!-- SLUG -->

                            <div class="form-group">

                                <label class="form-label">
                                    Slug
                                    <span class="required">*</span>
                                </label>

                                <div class="input-wrap">

                                    <i class="fa-solid fa-link"></i>

                                    <input
                                        type="text"
                                        name="slug"
                                        id="brandSlug"
                                        class="form-control"
                                        value="<?php echo e($form['slug']); ?>"
                                        maxlength="255"
                                        placeholder="brand-slug"
                                        required
                                    >

                                </div>

                                <div class="form-help">
                                    URL-friendly unique identifier.
                                    You can edit it manually.
                                </div>

                            </div>


                            <!-- BRAND TYPE -->

                            <div class="form-group">

                                <label class="form-label">
                                    Brand Type
                                    <span class="required">*</span>
                                </label>

                                <select
                                    name="brand_type"
                                    class="form-select"
                                    required
                                >

                                    <?php foreach ($brandTypeOptions as $type): ?>

                                        <option
                                            value="<?php echo e($type); ?>"
                                            <?php echo $form['brand_type'] === $type
                                                ? 'selected'
                                                : ''; ?>
                                        >
                                            <?php
                                            echo e(
                                                ucwords(
                                                    str_replace(
                                                        ['-', '_'],
                                                        ' ',
                                                        $type
                                                    )
                                                )
                                            );
                                            ?>
                                        </option>

                                    <?php endforeach; ?>

                                </select>

                                <div class="form-help">
                                    Options are loaded directly from
                                    the existing database enum.
                                </div>

                            </div>


                            <!-- PARENT -->

                            <div class="form-group">

                                <label class="form-label">
                                    Parent Brand
                                </label>

                                <select
                                    name="parent_id"
                                    class="form-select"
                                >

                                    <option value="">
                                        — No Parent / Root Brand —
                                    </option>

                                    <?php foreach ($parentBrands as $parent): ?>

                                        <?php
                                        /*
                                         * Calculate a simple hierarchy
                                         * level for visual indentation.
                                         */
                                        $level = 0;
                                        $currentParent = $parent['parent_id'];
                                        $guard = 0;

                                        while (
                                            $currentParent !== null &&
                                            $currentParent !== '' &&
                                            $guard < 50
                                        ) {

                                            $foundParent = null;

                                            foreach ($parentBrands as $candidate) {

                                                if (
                                                    (int)$candidate['id'] ===
                                                    (int)$currentParent
                                                ) {
                                                    $foundParent = $candidate;
                                                    break;
                                                }

                                            }

                                            if (!$foundParent) {
                                                break;
                                            }

                                            $level++;

                                            $currentParent =
                                                $foundParent['parent_id'];

                                            $guard++;
                                        }

                                        $prefix = str_repeat(
                                            '— ',
                                            min($level, 5)
                                        );
                                        ?>

                                        <option
                                            value="<?php echo (int)$parent['id']; ?>"
                                            <?php
                                            echo (string)$form['parent_id'] ===
                                                (string)$parent['id']
                                                ? 'selected'
                                                : '';
                                            ?>
                                        >
                                            <?php
                                            echo e(
                                                $prefix .
                                                $parent['name']
                                            );
                                            ?>
                                        </option>

                                    <?php endforeach; ?>

                                </select>

                                <div class="form-help">
                                    Optional. Use this when the brand
                                    belongs under another brand.
                                </div>

                            </div>


                            <!-- WEBSITE -->

                            <div class="form-group field-full">

                                <label class="form-label">
                                    Website URL
                                </label>

                                <div class="input-wrap">

                                    <i class="fa-solid fa-globe"></i>

                                    <input
                                        type="url"
                                        name="website_url"
                                        class="form-control"
                                        value="<?php echo e($form['website_url']); ?>"
                                        maxlength="1000"
                                        placeholder="https://example.com"
                                    >

                                </div>

                                <div class="form-help">
                                    Use a complete HTTP or HTTPS URL.
                                </div>

                            </div>


                            <!-- SHORT DESCRIPTION -->

                            <div class="form-group field-full">

                                <label class="form-label">
                                    Short Description
                                </label>

                                <textarea
                                    name="short_description"
                                    class="form-textarea"
                                    style="min-height:105px;"
                                    placeholder="Short description for cards, listings or introductory sections..."
                                ><?php echo e($form['short_description']); ?></textarea>

                                <div class="form-help">
                                    Keep this concise. It can be used
                                    in brand cards and listing pages.
                                </div>

                            </div>


                            <!-- DESCRIPTION -->

                            <div class="form-group field-full">

                                <label class="form-label">
                                    Full Description
                                </label>

                                <textarea
                                    name="description"
                                    class="form-textarea"
                                    style="min-height:210px;"
                                    placeholder="Enter the complete brand description..."
                                ><?php echo e($form['description']); ?></textarea>

                                <div class="form-help">
                                    Detailed brand information for the
                                    brand detail page.
                                </div>

                            </div>


                        </div>

                    </div>

                </section>


                <!-- =========================================
                     RIGHT SETTINGS
                ========================================== -->

                <aside class="card side-card">

                    <div class="card-header">

                        <div>

                            <h3>
                                Brand Settings
                            </h3>

                            <p>
                                Media, visibility and ordering.
                            </p>

                        </div>

                    </div>


                    <div class="card-body">


                        <!-- MEDIA -->
                        <div class="setting-item">
                            <div class="setting-title">Brand Media</div>
                            <div class="form-group">
                                <label class="form-label" for="logo_id">Choose existing logo</label>
                                <select name="logo_id" id="logo_id" class="form-select">
                                    <option value="">No logo selected</option>
                                    <?php foreach ($mediaImages as $media): ?>
                                    <option value="<?php echo (int)$media['id']; ?>" <?php echo (string)$form['logo_id'] === (string)$media['id'] ? 'selected' : ''; ?>>
                                        #<?php echo (int)$media['id']; ?> — <?php echo e($media['original_name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="form-help">Or upload a new logo below (JPG, PNG, WEBP, GIF; max 8 MB).</div>
                                <input type="file" name="logo_upload" class="form-control" accept="image/jpeg,image/png,image/webp,image/gif" style="margin-top:8px;padding:8px;height:auto;">
                            </div>
                            <div class="form-group" style="margin-top:16px;">
                                <label class="form-label" for="banner_id">Choose existing banner</label>
                                <select name="banner_id" id="banner_id" class="form-select">
                                    <option value="">No banner selected</option>
                                    <?php foreach ($mediaImages as $media): ?>
                                    <option value="<?php echo (int)$media['id']; ?>" <?php echo (string)$form['banner_id'] === (string)$media['id'] ? 'selected' : ''; ?>>
                                        #<?php echo (int)$media['id']; ?> — <?php echo e($media['original_name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="form-help">Or upload a new banner below (JPG, PNG, WEBP, GIF; max 8 MB).</div>
                                <input type="file" name="banner_upload" class="form-control" accept="image/jpeg,image/png,image/webp,image/gif" style="margin-top:8px;padding:8px;height:auto;">
                            </div>
                        </div>

                        <!-- STATUS -->

                        <div class="setting-item">

                            <div class="setting-title">
                                Visibility
                            </div>

                            <div class="toggle-row">


                                <!-- STATUS -->

                                <div class="toggle-box">

                                    <input
                                        type="checkbox"
                                        name="status"
                                        id="statusToggle"
                                        value="1"
                                        <?php echo $form['status'] === '1'
                                            ? 'checked'
                                            : ''; ?>
                                    >

                                    <label
                                        for="statusToggle"
                                        class="toggle-label"
                                    >

                                        <div class="toggle-icon">
                                            <i class="fa-solid fa-eye"></i>
                                        </div>

                                        <div class="toggle-content">

                                            <strong>
                                                Active
                                            </strong>

                                            <span>
                                                Show on website
                                            </span>

                                        </div>

                                    </label>

                                </div>


                                <!-- FEATURED -->

                                <div class="toggle-box">

                                    <input
                                        type="checkbox"
                                        name="featured"
                                        id="featuredToggle"
                                        value="1"
                                        <?php echo $form['featured'] === '1'
                                            ? 'checked'
                                            : ''; ?>
                                    >

                                    <label
                                        for="featuredToggle"
                                        class="toggle-label"
                                    >

                                        <div class="toggle-icon">
                                            <i class="fa-solid fa-star"></i>
                                        </div>

                                        <div class="toggle-content">

                                            <strong>
                                                Featured
                                            </strong>

                                            <span>
                                                Highlight this brand
                                            </span>

                                        </div>

                                    </label>

                                </div>


                            </div>

                        </div>


                        <!-- SORT ORDER -->

                        <div class="setting-item">

                            <div class="setting-title">
                                Ordering
                            </div>

                            <div class="form-group">

                                <label class="form-label">
                                    Sort Order
                                </label>

                                <div class="input-wrap">

                                    <i class="fa-solid fa-arrow-down-1-9"></i>

                                    <input
                                        type="number"
                                        name="sort_order"
                                        class="form-control"
                                        value="<?php echo e($form['sort_order']); ?>"
                                        min="0"
                                        step="1"
                                    >

                                </div>

                                <div class="form-help">
                                    Lower numbers appear first.
                                </div>

                            </div>

                        </div>


                        <!-- INFO -->

                        <div class="info-box">

                            <div class="info-icon">
                                <i class="fa-solid fa-circle-info"></i>
                            </div>

                            <p>
                                Brand information is stored directly in
                                the existing <strong>brands</strong>
                                table. No duplicate table or duplicate
                                content record is created.
                            </p>

                        </div>


                    </div>

                </aside>


            </div>


            <!-- =================================================
                 FORM FOOTER
            ================================================== -->

            <div class="form-footer">

                <div class="form-footer-note">

                    <i class="fa-solid fa-shield-halved"></i>

                    Changes are protected with admin
                    authentication and CSRF validation.

                </div>


                <div class="form-actions">

                    <a
                        href="add_brand.php"
                        class="btn btn-light"
                    >
                        Cancel
                    </a>

                    <button
                        type="submit"
                        class="btn btn-primary"
                        id="saveBrandBtn"
                    >
                        <i class="fa-solid <?php echo $editId > 0 ? 'fa-floppy-disk' : 'fa-plus'; ?>"></i>

                        <?php echo $editId > 0 ? 'Update Brand' : 'Save Brand'; ?>
                    </button>

                </div>

            </div>

        </form>

        <section class="card" style="margin-top:28px;overflow:hidden;">
            <div class="card-header">
                <div><h3><i class="fa-solid fa-layer-group" style="color:#0f766e;margin-right:7px;"></i>All Brands</h3>
                <p>Search, edit or delete records saved in the brands table.</p></div>
                <span class="form-help"><?php echo count($brandsList); ?> total</span>
            </div>
            <div class="card-body" style="overflow-x:auto;">
                <input type="search" id="brandSearch" class="form-control" placeholder="Search brand name, slug or type..." style="max-width:420px;margin-bottom:16px;">
                <table id="brandsTable" style="width:100%;border-collapse:collapse;font-size:12px;min-width:760px;">
                    <thead><tr style="text-align:left;background:#f8fafc;">
                        <th style="padding:12px;">Brand</th><th style="padding:12px;">Type</th><th style="padding:12px;">Logo / Banner</th><th style="padding:12px;">Status</th><th style="padding:12px;">Actions</th>
                    </tr></thead>
                    <tbody>
                    <?php if (!$brandsList): ?><tr><td colspan="5" style="padding:20px;color:#6b7280;">No brands yet. Add your first brand using the form above.</td></tr><?php endif; ?>
                    <?php foreach ($brandsList as $brand): ?>
                    <tr class="brand-row" style="border-top:1px solid #e5e7eb;">
                        <td style="padding:12px;"><strong><?php echo e($brand['name']); ?></strong><div style="color:#6b7280;margin-top:4px;"><?php echo e($brand['slug']); ?></div><small style="color:#9ca3af;">ID #<?php echo (int)$brand['id']; ?></small></td>
                        <td style="padding:12px;"><?php echo e($brand['brand_type']); ?></td>
                        <td style="padding:12px;">
                            <?php if (!empty($brand['logo_path'])): ?><a href="<?php echo e('../' . ltrim($brand['logo_path'], '/')); ?>" target="_blank" rel="noopener">Logo</a><?php else: ?><span style="color:#9ca3af;">No logo</span><?php endif; ?>
                            &nbsp;·&nbsp;
                            <?php if (!empty($brand['banner_path'])): ?><a href="<?php echo e('../' . ltrim($brand['banner_path'], '/')); ?>" target="_blank" rel="noopener">Banner</a><?php else: ?><span style="color:#9ca3af;">No banner</span><?php endif; ?>
                        </td>
                        <td style="padding:12px;"><span style="display:inline-block;padding:5px 9px;border-radius:20px;background:<?php echo (int)$brand['status'] ? '#dcfce7' : '#fee2e2'; ?>;color:<?php echo (int)$brand['status'] ? '#166534' : '#991b1b'; ?>;"><?php echo (int)$brand['status'] ? 'Active' : 'Hidden'; ?></span><?php if ((int)$brand['featured']): ?><div style="margin-top:5px;color:#0f766e;">Featured</div><?php endif; ?></td>
                        <td style="padding:12px;white-space:nowrap;">
                            <a class="btn btn-light" style="min-height:34px;padding:0 10px;" href="add_brand.php?edit=<?php echo (int)$brand['id']; ?>"><i class="fa-solid fa-pen"></i> Edit</a>
                            <form method="post" action="" style="display:inline;" onsubmit="return confirm('Delete this brand? This cannot be undone.');">
                                <?php echo add_brand_csrf_field(); ?>
                                <input type="hidden" name="form_action" value="delete">
                                <input type="hidden" name="brand_id" value="<?php echo (int)$brand['id']; ?>">
                                <button type="submit" class="btn btn-light" style="min-height:34px;padding:0 10px;color:#dc2626;"><i class="fa-solid fa-trash"></i> Delete</button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>

    </main>

</div>


<script>

document.addEventListener('DOMContentLoaded', function () {

    const brandName = document.getElementById('brandName');
    const brandSlug = document.getElementById('brandSlug');
    const brandForm = document.getElementById('brandForm');
    const saveBrandBtn = document.getElementById('saveBrandBtn');

    let slugManuallyEdited = false;


    /* =====================================================
       AUTO SLUG
    ===================================================== */

    if (brandSlug) {

        brandSlug.addEventListener('input', function () {
            slugManuallyEdited = this.value.trim() !== '';
        });

    }


    if (brandName && brandSlug) {

        brandName.addEventListener('input', function () {

            if (slugManuallyEdited) {
                return;
            }

            let value = this.value
                .toLowerCase()
                .trim();

            value = value
                .replace(/[^a-z0-9]+/g, '-')
                .replace(/^-+|-+$/g, '');

            brandSlug.value = value;

        });

    }


    /* =====================================================
       FORM SUBMIT UX
    ===================================================== */

    if (brandForm) {

        brandForm.addEventListener('submit', function () {

            if (saveBrandBtn) {

                saveBrandBtn.disabled = true;

                saveBrandBtn.innerHTML =
                    '<i class="fa-solid fa-spinner fa-spin"></i> Saving...';

            }

        });

    }


    /* =====================================================
       WEBSITE URL NORMALIZATION
    ===================================================== */

    const websiteInput =
        document.querySelector('input[name="website_url"]');

    if (websiteInput) {

        websiteInput.addEventListener('blur', function () {

            let value = this.value.trim();

            if (
                value !== '' &&
                !/^https?:\/\//i.test(value)
            ) {

                this.value = 'https://' + value;

            }

        });

    }


    const brandSearch = document.getElementById('brandSearch');
    if (brandSearch) {
        brandSearch.addEventListener('input', function () {
            const query = this.value.toLowerCase().trim();
            document.querySelectorAll('#brandsTable tbody .brand-row').forEach(function (row) {
                row.style.display = row.innerText.toLowerCase().includes(query) ? '' : 'none';
            });
        });
    }

});

</script>

</body>
</html>