<?php

declare(strict_types=1);
require_once __DIR__ . '/../app/config/bootstrap.php';
require_once __DIR__ . '/../app/controllers/ShopController.php';
require_once __DIR__ . '/../app/core/DijikalaLayout.php';
require_once __DIR__ . '/../app/models/Product.php';

$slug = trim((string)($_GET['slug'] ?? ''));
$id = (int)($_GET['id'] ?? 0);
$productModel = new Product();
if ($slug !== '') {
    $product = $productModel->findBySlug($slug);
} elseif ($id > 0) {
    $product = (new ShopController())->product($id);
} else {
    $product = null;
}

$seo = [];
if ($product) {
    $desc = strip_tags((string)($product['short_description'] ?: $product['long_description'] ?: ''));
    $desc = mb_substr($desc, 0, 300);
    $canonical = rtrim(APP_URL, '/') . appPath('/public/product.php');
    $canonical .= !empty($product['slug']) ? ('?slug=' . rawurlencode((string)$product['slug'])) : ('?id=' . (int)$product['id']);
    $seo = [
        'description' => $desc,
        'canonical' => $canonical,
        'json_ld' => [
            '@context' => 'https://schema.org',
            '@type' => 'Product',
            'name' => $product['title'],
            'sku' => $product['sku'],
            'description' => $desc,
            'offers' => [
                '@type' => 'Offer',
                'priceCurrency' => 'IRR',
                'price' => (float)$product['price'],
                'availability' => ((int)$product['stock'] > 0) ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock',
            ],
        ],
    ];
}

renderDijikalaShellStart($product ? (string)$product['title'] : 'محصول', $seo, '');
?>

<article class="container" style="padding:1.5rem 0 2.5rem;">
    <?php if (!$product): ?>
        <p>محصول یافت نشد.</p>
    <?php else: ?>
        <div style="display:flex;flex-wrap:wrap;gap:24px;">
            <div style="flex:1;min-width:280px;">
                <?php if (!empty($product['image_url'])): ?>
                    <img src="<?= htmlspecialchars(appPath('/' . ltrim((string)$product['image_url'], '/'))) ?>"
                         alt="<?= htmlspecialchars((string)$product['title']) ?>"
                         style="max-width:100%;border-radius:8px;"
                         loading="eager">
                <?php else: ?>
                    <img src="<?= dijikalaAsset('img/sman.png') ?>" alt="" style="max-width:100%;">
                <?php endif; ?>
                <?php if (!empty($product['video_path'])): ?>
                    <video style="margin-top:12px;width:100%;border-radius:8px;" controls preload="metadata">
                        <source src="<?= htmlspecialchars(appPath('/' . ltrim((string)$product['video_path'], '/'))) ?>">
                    </video>
                <?php endif; ?>
            </div>
            <div style="flex:1.5;min-width:280px;">
                <h1 style="margin-top:0;"><?= htmlspecialchars((string)$product['title']) ?></h1>
                <p style="font-size:0.9rem;color:#475569;">
                    شناسه پیگیری: <code><?= htmlspecialchars((string)($product['tracking_code'] ?? '-')) ?></code>
                    — SKU: <code><?= htmlspecialchars((string)$product['sku']) ?></code>
                </p>
                <?php
                    $d = max(0, min(99, (int)($product['discount_percent'] ?? 0)));
                    $price = (float)$product['price'];
                    $listApprox = ($d > 0) ? (int)round($price / (1 - $d / 100)) : (int)$price;
                ?>
                <div class="c-price__value c-price__value--plp" style="margin:16px 0;">
                    <?php if ($d > 0): ?>
                        <del><?= number_format((float)$listApprox) ?></del>
                        <span class="c-price__discount-oval"><span><?= (int)$d ?>٪</span></span>
                    <?php endif; ?>
                    <div class="c-price__value-wrapper" style="font-size:1.25rem;">
                        <?= number_format($price) ?> <span class="c-price__currency">تومان</span>
                    </div>
                </div>
                <p>موجودی: <?= (int)$product['stock'] ?></p>
                <p><?= nl2br(htmlspecialchars((string)($product['short_description'] ?? ''))) ?></p>
                <?php if (!empty($product['long_description'])): ?>
                    <div class="long-desc" style="margin-top:12px;line-height:1.7;">
                        <?= strip_tags((string)$product['long_description'], '<p><br><strong><b><ul><ol><li><em><span>') ?>
                    </div>
                <?php endif; ?>
                <div style="margin-top:20px;display:flex;flex-wrap:wrap;gap:10px;">
                    <a class="btn-login" style="text-decoration:none;display:inline-block;padding:12px 20px;"
                       href="<?= htmlspecialchars(appPath('/public/cart.php')) ?>?add=<?= (int)$product['id'] ?>">افزودن به سبد</a>
                    <a class="btn-link-spoiler"
                       href="<?= htmlspecialchars(appPath('/public/compare.php')) ?>?add=<?= (int)$product['id'] ?>">افزودن به مقایسه</a>
                </div>
            </div>
        </div>
    <?php endif; ?>
</article>

<?php
renderDijikalaShellEnd('product', 'minimal');
Performance::finish('public.product');
