<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/includes/module_helpers.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (empty($_SESSION['shop_csrf_token'])) {
    $_SESSION['shop_csrf_token'] = bin2hex(random_bytes(32));
}

if (!headers_sent()) {
    header('Content-Type: text/html; charset=utf-8');
}

function shop_e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function shop_money($amount): string
{
    return number_format((float)$amount, 0, '.', ' ') . ' сом';
}

function shop_table_exists(PDO $pdo, string $table): bool
{
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?");
    $stmt->execute([$table]);
    return (int)$stmt->fetchColumn() > 0;
}

function shop_column_exists(PDO $pdo, string $table, string $column): bool
{
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?");
    $stmt->execute([$table, $column]);
    return (int)$stmt->fetchColumn() > 0;
}

function shop_asset_url(?string $path): string
{
    $path = trim((string)$path);
    if ($path === '') {
        return '';
    }
    if (preg_match('~^(https?:)?//|^/~', $path)) {
        return $path;
    }
    return '../' . ltrim($path, '/');
}

function shop_load_themes(): array
{
    $defaults = [
        'kanc' => [
            'name' => 'Kanc Light',
            'primary' => '#2367dc',
            'accent' => '#ff6b2c',
            'bg' => '#f3f6ff',
            'panel' => '#ffffff',
            'ink' => '#132044',
            'muted' => '#65759b',
            'soft' => '#eaf1ff',
        ],
        'emerald' => [
            'name' => 'Emerald Office',
            'primary' => '#0f9f6e',
            'accent' => '#f2b705',
            'bg' => '#f1fbf7',
            'panel' => '#ffffff',
            'ink' => '#10251e',
            'muted' => '#5d766e',
            'soft' => '#dff7ee',
        ],
        'graphite' => [
            'name' => 'Graphite',
            'primary' => '#374151',
            'accent' => '#3b82f6',
            'bg' => '#f4f5f7',
            'panel' => '#ffffff',
            'ink' => '#111827',
            'muted' => '#6b7280',
            'soft' => '#e5e7eb',
        ],
    ];

    $file = __DIR__ . '/themes.json';
    if (!is_file($file)) {
        file_put_contents($file, json_encode($defaults, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        return $defaults;
    }

    $custom = json_decode((string)file_get_contents($file), true);
    return is_array($custom) ? array_replace_recursive($defaults, $custom) : $defaults;
}

$themes = shop_load_themes();
$themeKey = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)($_GET['theme'] ?? 'kanc'));
if (!isset($themes[$themeKey])) {
    $themeKey = 'kanc';
}
$theme = $themes[$themeKey];

$products = [];
$categories = [];
$categoryRows = [];
$rootCategories = [];
$featuredCategories = [];
$childrenByParent = [];
$categoryDescendants = [];
$productCategories = [];
$banners = [];
$dbError = null;

try {
    ensure_shop_tables($pdo);
    seed_shop_defaults($pdo);

    if (shop_table_exists($pdo, 'shop_banners')) {
        $stmt = $pdo->query("
            SELECT kicker, title, subtitle, image, link, button_text, bg_from, bg_to, text_color
            FROM shop_banners
            WHERE visible = 1 AND position = 'home'
            ORDER BY sort_order ASC, id ASC
            LIMIT 8
        ");
        $banners = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    if (shop_table_exists($pdo, 'shop_categories')) {
        $stmt = $pdo->query("
            SELECT id, parent_id, name, url, icon, featured
            FROM shop_categories
            WHERE visible = 1
            ORDER BY parent_id ASC, position ASC, name ASC
        ");
        $categoryRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    if (shop_table_exists($pdo, 'products')) {
        $columns = [
            'id' => 'id',
            'name' => 'name',
            'description' => shop_column_exists($pdo, 'products', 'description') ? 'description' : "''",
            'price' => shop_column_exists($pdo, 'products', 'price') ? 'price' : '0',
            'quantity' => shop_column_exists($pdo, 'products', 'quantity') ? 'quantity' : '0',
            'category' => shop_column_exists($pdo, 'products', 'category') ? 'category' : "''",
            'photo' => shop_column_exists($pdo, 'products', 'photo') ? 'photo' : "''",
        ];

        $expr = [];
        foreach ($columns as $key => $column) {
            $expr[$key] = in_array($column, ["''", '0'], true) ? $column : 'p.' . $column;
        }

        $stmt = $pdo->query("
            SELECT
                {$expr['id']} AS id,
                {$expr['name']} AS name,
                {$expr['description']} AS description,
                {$expr['price']} AS price,
                {$expr['quantity']} AS quantity,
                COALESCE(NULLIF(sc.name, ''), NULLIF({$expr['category']}, ''), '') AS category,
                {$expr['photo']} AS photo,
                COALESCE(spm.slug, '') AS slug,
                COALESCE(sb.name, '') AS brand_name
            FROM products p
            LEFT JOIN shop_products_meta spm ON spm.product_id = p.id
            LEFT JOIN shop_categories sc ON sc.id = spm.category_id
            LEFT JOIN shop_brands sb ON sb.id = spm.brand_id AND sb.visible = 1
            WHERE COALESCE(spm.visible, 1) = 1
            ORDER BY p.id DESC
            LIMIT 120
        ");
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $dbError = $e->getMessage();
}

foreach ($products as &$product) {
    $product['id'] = (int)$product['id'];
    $product['name'] = (string)$product['name'];
    $product['description'] = (string)($product['description'] ?: 'Товар ALLIPE для школы, офиса и бизнеса.');
    $product['price'] = (float)$product['price'];
    $product['quantity'] = (int)$product['quantity'];
    $product['category'] = trim((string)$product['category']) ?: 'Без категории';
    $product['brand_name'] = trim((string)($product['brand_name'] ?? ''));
    $product['photo'] = shop_asset_url($product['photo'] ?? '');
    $product['slug'] = trim((string)($product['slug'] ?? ''));
    $product['url'] = $product['slug'] !== '' ? 'product/' . rawurlencode($product['slug']) : 'product.php?id=' . $product['id'];
    $product['money'] = shop_money($product['price']);
    $productCategories[$product['category']] = true;
}
unset($product);

$productCategories = array_keys($productCategories);
sort($productCategories);

if ($categoryRows) {
    foreach ($categoryRows as $category) {
        $category['id'] = (int)$category['id'];
        $category['parent_id'] = (int)$category['parent_id'];
        $name = trim((string)$category['name']);
        if ($name !== '') {
            $categories[$name] = true;
        }
        $childrenByParent[$category['parent_id']][] = $category;
        if ($category['parent_id'] === 0) {
            $rootCategories[] = $category;
        }
        if ((int)$category['featured'] === 1) {
            $featuredCategories[] = $category;
        }
    }
    $categories = array_keys($categories);
} else {
    $categories = $productCategories;
}

if (!$rootCategories) {
    foreach ($categories as $name) {
        $rootCategories[] = ['name' => $name, 'icon' => 'package', 'featured' => 0];
    }
}

if (!$featuredCategories) {
    $featuredCategories = $rootCategories;
}

foreach ($rootCategories as $rootCategory) {
    $stack = [$rootCategory['id']];
    $names = [(string)$rootCategory['name']];
    while ($stack) {
        $parentId = array_pop($stack);
        foreach ($childrenByParent[$parentId] ?? [] as $child) {
            $names[] = (string)$child['name'];
            $stack[] = (int)$child['id'];
        }
    }
    $categoryDescendants[(string)$rootCategory['name']] = array_values(array_unique($names));
}

$heroProduct = $products[0] ?? null;
$cartCount = array_sum($_SESSION['shop_cart'] ?? []);

if (!$banners) {
    $banners = [
        [
            'kicker' => 'Доставка',
            'title' => 'Быстрая доставка по Кыргызстану',
            'subtitle' => 'Получите заказ уже завтра: офис, школа, склад и бизнес.',
            'image' => '',
            'link' => 'catalog.php',
            'button_text' => 'Перейти к покупкам',
            'bg_from' => '#2459d6',
            'bg_to' => '#22c55e',
            'text_color' => '#ffffff',
        ],
    ];
}

function render_shop_mega_links(array $childrenByParent, int $parentId, int $level = 0): void
{
    foreach (($childrenByParent[$parentId] ?? []) as $child) {
        $name = (string)($child['name'] ?? '');
        $url = (string)($child['url'] ?? '');
        echo '<a class="mega-depth mega-depth-' . min($level, 4) . '" href="category.php?url=' . shop_e(urlencode($url)) . '">' . shop_e($name) . '</a>';
        render_shop_mega_links($childrenByParent, (int)$child['id'], $level + 1);
    }
}
?>
<!doctype html>
<html lang="ru">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>ALLIPE — интернет-магазин</title>
    <link rel="stylesheet" href="assets/shop/styles.css?v=20260428-2">
    <style>
        :root {
            --primary: <?= shop_e($theme['primary']) ?>;
            --accent: <?= shop_e($theme['accent']) ?>;
            --bg: <?= shop_e($theme['bg']) ?>;
            --panel: <?= shop_e($theme['panel']) ?>;
            --ink: <?= shop_e($theme['ink']) ?>;
            --muted: <?= shop_e($theme['muted']) ?>;
            --soft: <?= shop_e($theme['soft']) ?>;
        }
    </style>
    <script src="https://unpkg.com/lucide@latest"></script>
</head>
<body>
<div class="shop-shell">
    <header class="topbar">
        <a class="brand" href="index.php?theme=<?= shop_e($themeKey) ?>">
            <span>ALLIPE</span>
        </a>

        <form class="search-bar" method="get">
            <input type="hidden" name="theme" value="<?= shop_e($themeKey) ?>">
            <button class="category-chip" type="button"><i data-lucide="folder"></i> Все категории</button>
            <label class="city-chip"><i data-lucide="map-pin"></i><span>Бишкек</span></label>
            <input id="searchInput" type="search" placeholder="Поиск товаров">
            <button class="search-btn" type="button" aria-label="Поиск"><i data-lucide="search"></i></button>
        </form>

        <div class="top-actions">
            <select id="themeSelect" aria-label="Тема магазина">
                <?php foreach ($themes as $key => $item): ?>
                    <option value="<?= shop_e($key) ?>" <?= $key === $themeKey ? 'selected' : '' ?>><?= shop_e($item['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <a class="theme-link" href="theme-builder.php?theme=<?= shop_e($themeKey) ?>"><i data-lucide="palette"></i></a>
            <a class="theme-link" href="favorites.php" title="Избранное"><i data-lucide="heart"></i></a>
            <a class="theme-link" href="compare.php" title="Сравнение"><i data-lucide="scale"></i></a>
            <a class="user-card" href="account.php">
                <span class="avatar">A</span>
                <span><b>Кабинет</b><small>Заказы и профиль</small></span>
            </a>
            <button class="cart-button" id="cartToggle" type="button">
                <span id="cartCount"><?= (int)$cartCount ?></span>
                <i data-lucide="shopping-cart"></i>
            </button>
        </div>
    </header>

    <nav class="subnav">
        <a href="catalog.php">Каталог</a>
        <a href="#catalog">Акции</a>
        <a href="#catalog">Новинки</a>
        <a href="#catalog">Опт</a>
        <a href="#delivery">Доставка</a>
        <a href="#contacts">Контакты</a>
    </nav>

    <main class="layout">
        <aside class="category-sidebar">
            <button class="category-main" type="button"><i data-lucide="folder"></i> Все категории <i data-lucide="chevron-down"></i></button>
            <div class="category-menu-wrap">
                <div class="category-list" id="sideCategories">
                    <button class="active" type="button" data-category="Все"><i data-lucide="briefcase"></i><span>Все категории</span><i data-lucide="chevron-right"></i></button>
                <?php foreach ($rootCategories as $category): ?>
                    <?php $categoryName = (string)($category['name'] ?? ''); ?>
                    <?php $categoryIcon = preg_replace('/[^a-z0-9-]/i', '', (string)($category['icon'] ?? 'package')) ?: 'package'; ?>
                    <a href="category.php?url=<?= urlencode((string)($category['url'] ?? '')) ?>" data-category="<?= shop_e($categoryName) ?>" data-root-id="<?= (int)$category['id'] ?>"><i data-lucide="<?= shop_e($categoryIcon) ?>"></i><span><?= shop_e($categoryName) ?></span><i data-lucide="chevron-right"></i></a>
                <?php endforeach; ?>
                </div>

                <div class="mega-menu" id="megaMenu">
                    <?php foreach ($rootCategories as $rootCategory): ?>
                        <?php $rootId = (int)($rootCategory['id'] ?? 0); ?>
                        <div class="mega-panel" data-panel-root="<?= $rootId ?>">
                            <div class="mega-panel-head">
                                <div>
                                    <span>Каталог</span>
                                    <h3><?= shop_e($rootCategory['name'] ?? '') ?></h3>
                                </div>
                                <a class="mega-cta" href="category.php?url=<?= urlencode((string)($rootCategory['url'] ?? '')) ?>">Смотреть все</a>
                            </div>
                            <div class="mega-grid">
                                <?php foreach (($childrenByParent[$rootId] ?? []) as $group): ?>
                                    <?php $groupName = (string)($group['name'] ?? ''); ?>
                                    <article class="mega-card">
                                        <a class="mega-title" href="category.php?url=<?= urlencode((string)($group['url'] ?? '')) ?>"><?= shop_e($groupName) ?></a>
                                        <?php render_shop_mega_links($childrenByParent, (int)$group['id']); ?>
                                    </article>
                                <?php endforeach; ?>
                                <?php if (empty($childrenByParent[$rootId])): ?>
                                    <article class="mega-card">
                                        <a class="mega-title" href="category.php?url=<?= urlencode((string)($rootCategory['url'] ?? '')) ?>"><?= shop_e($rootCategory['name'] ?? '') ?></a>
                                        <span>Товары этой категории появятся здесь после привязки в CRM.</span>
                                    </article>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </aside>

        <section class="main-content">
            <?php if ($dbError): ?>
                <div class="notice error">Не удалось загрузить товары: <?= shop_e($dbError) ?></div>
            <?php endif; ?>

            <section class="banner-slider" id="bannerSlider">
                <div class="banner-track">
                    <?php foreach ($banners as $index => $banner): ?>
                        <?php
                        $from = preg_match('/^#[0-9a-fA-F]{6}$/', (string)($banner['bg_from'] ?? '')) ? $banner['bg_from'] : '#2459d6';
                        $to = preg_match('/^#[0-9a-fA-F]{6}$/', (string)($banner['bg_to'] ?? '')) ? $banner['bg_to'] : '#22c55e';
                        $color = preg_match('/^#[0-9a-fA-F]{6}$/', (string)($banner['text_color'] ?? '')) ? $banner['text_color'] : '#ffffff';
                        $image = shop_asset_url($banner['image'] ?? '');
                        ?>
                        <article class="hero-card banner-slide <?= $index === 0 ? 'active' : '' ?>" style="--banner-from: <?= shop_e($from) ?>; --banner-to: <?= shop_e($to) ?>; --banner-text: <?= shop_e($color) ?>;">
                            <div class="hero-copy">
                                <span class="banner-kicker"><?= shop_e($banner['kicker'] ?: 'ALLIPE') ?></span>
                                <h1><?= shop_e($banner['title']) ?></h1>
                                <p><?= shop_e($banner['subtitle']) ?></p>
                                <div class="hero-actions">
                                    <a class="btn btn-primary" href="<?= shop_e($banner['link'] ?: 'catalog.php') ?>"><?= shop_e($banner['button_text'] ?: 'Смотреть') ?></a>
                                </div>
                            </div>
                            <div class="hero-art">
                                <?php if ($image): ?>
                                    <img class="banner-image" src="<?= shop_e($image) ?>" alt="<?= shop_e($banner['title']) ?>">
                                <?php else: ?>
                                    <div class="box-stack">
                                        <span></span><span></span><span></span>
                                    </div>
                                    <div class="supply-pack">
                                        <i data-lucide="package-open"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
                <?php if (count($banners) > 1): ?>
                    <button class="banner-nav prev" type="button" data-banner-prev aria-label="Предыдущий баннер"><i data-lucide="chevron-left"></i></button>
                    <button class="banner-nav next" type="button" data-banner-next aria-label="Следующий баннер"><i data-lucide="chevron-right"></i></button>
                    <div class="banner-dots">
                        <?php foreach ($banners as $index => $_): ?>
                            <button class="<?= $index === 0 ? 'active' : '' ?>" type="button" data-banner-dot="<?= $index ?>" aria-label="Баннер <?= $index + 1 ?>"></button>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>

            <div class="quick-tags">
                <?php foreach (array_slice($featuredCategories, 0, 6) as $category): ?>
                    <?php $categoryName = (string)($category['name'] ?? ''); ?>
                    <a href="category.php?url=<?= urlencode((string)($category['url'] ?? '')) ?>"><?= shop_e($categoryName) ?></a>
                <?php endforeach; ?>
            </div>

            <section class="catalog" id="catalog">
                <div class="section-head">
                    <div>
                        <p>Каталог</p>
                        <h2>Товары из базы CRM</h2>
                    </div>
                    <select id="sortSelect">
                        <option value="new">Сначала новые</option>
                        <option value="price-asc">Цена по возрастанию</option>
                        <option value="price-desc">Цена по убыванию</option>
                        <option value="stock">Сначала в наличии</option>
                    </select>
                </div>
                <div class="product-grid" id="productGrid"></div>
            </section>

            <section class="info-grid" id="delivery">
                <article><i data-lucide="truck"></i><b>Доставка</b><span>Курьер, самовывоз и доставка для организаций.</span></article>
                <article><i data-lucide="badge-percent"></i><b>Опт</b><span>Подберем товары для офиса, школы или склада.</span></article>
                <article id="contacts"><i data-lucide="phone"></i><b>Контакты</b><span>+996 555 000 000 В· sales@allipe.kg</span></article>
            </section>
        </section>
    </main>
</div>

<aside class="cart-panel" id="cartPanel">
    <div class="cart-head">
        <div><b>Корзина</b><span id="cartMeta">Пока пусто</span></div>
        <button type="button" id="cartClose"><i data-lucide="x"></i></button>
    </div>
    <div class="cart-items" id="cartItems"></div>
    <form class="order-form" id="orderForm" method="post" action="checkout.php">
        <input type="hidden" name="csrf_token" value="<?= shop_e($_SESSION['shop_csrf_token']) ?>">
        <label>Имя<input name="name" required placeholder="Ваше имя"></label>
        <label>Телефон<input name="phone" required placeholder="+996 ..."></label>
        <label>Комментарий<textarea name="comment" placeholder="Адрес или детали заказа"></textarea></label>
        <div class="cart-total"><span>Итого</span><b id="cartTotal">0 сом</b></div>
        <button class="btn btn-primary" type="submit">Оставить заявку</button>
    </form>
</aside>
<div class="cart-backdrop" id="cartBackdrop"></div>
<div class="toast" id="toast"></div>

<script>
window.SHOP_PRODUCTS = <?= json_encode($products, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
window.SHOP_CATEGORIES = <?= json_encode($categories, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
window.SHOP_CATEGORY_DESCENDANTS = <?= json_encode($categoryDescendants, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
window.SHOP_THEME = <?= json_encode($themeKey, JSON_UNESCAPED_UNICODE) ?>;
window.SHOP_CSRF_TOKEN = <?= json_encode($_SESSION['shop_csrf_token'], JSON_UNESCAPED_UNICODE) ?>;
window.SHOP_CART_API = "api/public/cart.php";
</script>
<script src="assets/shop/app.js?v=20260429-cart"></script>
</body>
</html>
