<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

$user = null;
$isMinor = false;
if (isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0) {
    $user = getConnectedUser($pdo);
    if ($user) {
        $isMinor = (bool)($user['is_minor'] ?? false);
        if (!$isMinor && !empty($user['birthdate'])) {
            $age = (new DateTime())->diff(new DateTime($user['birthdate']))->y;
            $isMinor = $age < 18;
        }
    }
}

// Infos boutique
$settings = $pdo->query("SELECT * FROM store_settings WHERE id=1")->fetch();
$storeName = $settings['store_name'] ?? 'La Boutique';
$logoPath  = $settings['logo_path']  ?? null;

// Filtres
$search   = trim($_GET['q']    ?? '');
$typeFilter = $_GET['type']    ?? '';
$where    = "WHERE 1=1";
$params   = [];
if ($search) { $where .= " AND (s.name LIKE ? OR s.description LIKE ?)"; $params = array_merge($params,["%$search%","%$search%"]); }
if ($typeFilter) { $where .= " AND s.item_type = ?"; $params[] = $typeFilter; }

// Ajouter colonne price_jetons si absente
try { $pdo->exec("ALTER TABLE store_items ADD COLUMN IF NOT EXISTS price_jetons INT DEFAULT 0"); } catch(Exception $e) {}

$stmt = $pdo->prepare("SELECT * FROM store_items s $where ORDER BY s.is_on_sale DESC, s.id DESC");
$stmt->execute($params);
$items = $stmt->fetchAll();

// Types disponibles
$types = $pdo->query("SELECT DISTINCT item_type FROM store_items WHERE item_type IS NOT NULL ORDER BY item_type")->fetchAll(PDO::FETCH_COLUMN);

// Taxes
$taxCA = (float)($settings['tax_canada'] ?? 5.00);
$taxQC = (float)($settings['tax_quebec'] ?? 9.975);

include 'header.php';
?>

<style>
.item-card { transition:transform 0.15s, border-color 0.15s; }
.item-card:hover { transform:translateY(-2px); border-color:#0d6efd !important; }
.price-old { text-decoration:line-through; color:#666; font-size:0.8rem; }
.price-sale { color:#dc3545; font-weight:bold; font-size:1.1rem; }
.price-normal { color:#28a745; font-weight:bold; font-size:1.1rem; }
</style>

<div class="container-fluid mt-3 px-4">

    <a href="index.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Dashboard</a>
    <!-- En-tête boutique -->
    <div class="d-flex align-items-center gap-3 mb-4">
        <?php if ($logoPath && file_exists(__DIR__.'/'.$logoPath)): ?>
            <img src="<?= htmlspecialchars($logoPath) ?>" style="height:50px;object-fit:contain;">
        <?php endif; ?>
        <div>
            <h4 class="oracle-text text-success mb-0"><?= htmlspecialchars($storeName) ?></h4>
            <small class="text-muted">Articles disponibles · Taxes applicables (<?= $taxCA ?>% + <?= $taxQC ?>%)</small>
        </div>
        <?php if ($user && (int)($user['is_admin_store'] ?? 0)): ?>
            <a href="store_manage.php" class="btn btn-outline-warning btn-sm ms-auto">⚙️ Gérer ma boutique</a>
        <?php endif; ?>
        <?php if ($user && isAdmin($user)): ?>
            <a href="admin_store.php" class="btn btn-outline-danger btn-sm <?= !$user['is_admin_store']?'ms-auto':'' ?>">️ Admin boutique</a>
        <?php endif; ?>
    </div>

    <!-- Disclaimer boutique -->
    <div class="alert alert-secondary small py-2 mb-3">
        <i class="fa-solid fa-triangle-exclamation fa-xs me-1"></i>
        JeTeGageQue n'est pas responsable de cette boutique et n'en assure pas la gestion.
        Les transactions se font directement entre l'acheteur et le vendeur.
    </div>

    <!-- Filtres -->
    <form method="GET" class="row g-2 mb-4">
        <div class="col-md-5">
            <input type="text" name="q" class="form-control form-control-sm" placeholder=" Rechercher un article…" value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-3">
            <select name="type" class="form-select form-select-sm">
                <option value="">Tous les types</option>
                <?php foreach ($types as $t): ?>
                    <option value="<?= htmlspecialchars($t) ?>" <?= $typeFilter===$t?'selected':'' ?>><?= htmlspecialchars($t) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-success btn-sm w-100">Filtrer</button>
        </div>
        <div class="col-md-2">
            <a href="store.php" class="btn btn-outline-secondary btn-sm w-100">Réinitialiser</a>
        </div>
    </form>

    <?php if (empty($items)): ?>
        <div class="text-center text-muted py-5">
            <i class="fa-solid fa-store fa-3x mb-3 text-secondary"></i>
            <p>Aucun article disponible pour l'instant.</p>
        </div>
    <?php else: ?>

    <!-- Grille articles -->
    <div class="row g-3">
    <?php foreach ($items as $item):
        $price     = (float)$item['price'];
        $salePrice = (float)($item['sale_price'] ?? 0);
        $onSale    = (int)$item['is_on_sale'] && $salePrice > 0;
        $displayPrice = $onSale ? $salePrice : $price;

        // Calcul taxes
        $subtotal = $displayPrice;
        $gst = round($subtotal * ($taxCA / 100), 2);
        $qst = round(($subtotal + $gst) * ($taxQC / 100), 2);
        $total = round($subtotal + $gst + $qst, 2);
    ?>
    <div class="col-sm-6 col-md-4 col-lg-3">
        <div class="card bg-dark border-secondary h-100 item-card shadow-sm">
            <!-- Image -->
            <?php if (!empty($item['photo_path']) && file_exists(__DIR__.'/'.$item['photo_path'])): ?>
                <img src="<?= htmlspecialchars($item['photo_path']) ?>"
                     class="card-img-top" style="height:160px;object-fit:cover;">
            <?php else: ?>
                <div class="d-flex align-items-center justify-content-center bg-secondary"
                     style="height:160px;color:#888;font-size:2.5rem;"></div>
            <?php endif; ?>

            <div class="card-body p-3">
                <!-- Badge type + vente -->
                <div class="d-flex justify-content-between align-items-start mb-1">
                    <?php if (!empty($item['item_type'])): ?>
                        <span class="badge bg-dark border border-secondary text-muted" style="font-size:0.55rem;"><?= htmlspecialchars($item['item_type']) ?></span>
                    <?php endif; ?>
                    <?php if ($onSale): ?>
                        <span class="badge bg-danger" style="font-size:0.55rem;">EN VENTE</span>
                    <?php endif; ?>
                </div>

                <h6 class="text-white fw-bold mb-1" style="font-size:0.85rem;"><?= htmlspecialchars($item['name']) ?></h6>
                <p class="text-muted small mb-2" style="font-size:0.72rem; line-height:1.4;"><?= htmlspecialchars(mb_substr($item['description'],0,80)) ?><?= strlen($item['description'])>80?'…':'' ?></p>

                <?php if (!empty($item['sku'])): ?>
                    <small class="text-muted" style="font-size:0.6rem;">#<?= htmlspecialchars($item['sku']) ?></small>
                <?php endif; ?>

                <!-- Prix -->
                <div class="mt-2">
                    <?php if ($onSale): ?>
                        <span class="price-old"><?= number_format($price, 2) ?>$</span><br>
                        <span class="price-sale"><?= number_format($salePrice, 2) ?>$</span>
                    <?php else: ?>
                        <span class="price-normal"><?= number_format($price, 2) ?>$</span>
                    <?php endif; ?>
                    <small class="text-muted d-block" style="font-size:0.6rem;">+ taxes = <?= number_format($total, 2) ?>$ total</small>
                    <?php if (!empty($item['price_jetons']) && (int)$item['price_jetons'] > 0 && !$isMinor): ?>
                    <div style="margin-top:4px;">
                        <span style="color:#ffc107;font-size:0.75rem;font-weight:700;">&#9670; <?= (int)$item['price_jetons'] ?> jetons</span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Footer -->
            <div class="card-footer bg-transparent border-secondary p-2">
                <button class="btn btn-success btn-sm w-100 fw-bold"
                        onclick="addToCart(<?= $item['id'] ?>, '<?= htmlspecialchars(addslashes($item['name'])) ?>', <?= number_format($displayPrice, 2, '.', '') ?>)">
                     AJOUTER AU PANIER
                </button>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- Modal panier simplifié -->
<div class="modal fade" id="cartModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-success text-white">
            <div class="modal-header border-secondary py-2">
                <h6 class="modal-title text-success fw-bold"> MON PANIER</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-3" id="cartBody">
                <p class="text-muted small text-center">Panier vide</p>
            </div>
            <div class="modal-footer border-secondary py-2 d-flex justify-content-between align-items-center">
                <span class="text-white fw-bold">Total : <span id="cartTotal">0.00$</span></span>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-secondary btn-sm" onclick="clearCart()">Vider</button>
                    <button class="btn btn-success btn-sm fw-bold" onclick="checkout()">PAYER (PayPal)</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Bouton panier flottant -->
<button class="btn btn-success shadow" id="cartFloatBtn"
        style="position:fixed;bottom:20px;right:20px;border-radius:50%;width:52px;height:52px;font-size:1.2rem;z-index:999;display:none;"
        onclick="openCart()">
    <span id="cartCount" class="badge bg-danger" style="font-size:0.55rem;position:absolute;top:2px;right:2px;">0</span>
</button>

<script>
// Panier en mémoire (session JS)
let cart = [];
const taxCA = <?= $taxCA ?> / 100;
const taxQC = <?= $taxQC ?> / 100;
const paypalEmail = '<?= htmlspecialchars($settings['paypal_email'] ?? '') ?>';

function addToCart(id, name, price) {
    const existing = cart.find(i => i.id === id);
    if (existing) { existing.qty++; }
    else { cart.push({ id, name, price: parseFloat(price), qty: 1 }); }
    updateCartBadge();
    document.getElementById('cartFloatBtn').style.display = 'flex';
}

function updateCartBadge() {
    const total = cart.reduce((s, i) => s + i.qty, 0);
    document.getElementById('cartCount').innerText = total;
}

function clearCart() { cart = []; updateCartBadge(); document.getElementById('cartBody').innerHTML='<p class="text-muted small text-center">Panier vide</p>'; document.getElementById('cartTotal').innerText='0.00$'; }

function openCart() {
    const body = document.getElementById('cartBody');
    if (cart.length === 0) { body.innerHTML = '<p class="text-muted small text-center">Panier vide</p>'; }
    else {
        let html = '<table class="table table-dark table-sm small mb-2"><thead><tr><th>Article</th><th class="text-center">Qté</th><th class="text-end">Prix</th></tr></thead><tbody>';
        let subtotal = 0;
        cart.forEach(i => {
            const lineTotal = i.price * i.qty;
            subtotal += lineTotal;
            html += `<tr><td>${i.name}</td><td class="text-center">${i.qty}</td><td class="text-end">${lineTotal.toFixed(2)}$</td></tr>`;
        });
        const gst   = subtotal * taxCA;
        const qst   = (subtotal + gst) * taxQC;
        const total = subtotal + gst + qst;
        html += `</tbody></table>`;
        html += `<div class="small text-muted"><div class="d-flex justify-content-between"><span>Sous-total</span><span>${subtotal.toFixed(2)}$</span></div>`;
        html += `<div class="d-flex justify-content-between"><span>TPS (${(taxCA*100).toFixed(2)}%)</span><span>${gst.toFixed(2)}$</span></div>`;
        html += `<div class="d-flex justify-content-between"><span>TVQ (${(taxQC*100).toFixed(3)}%)</span><span>${qst.toFixed(2)}$</span></div></div>`;
        body.innerHTML = html;
        document.getElementById('cartTotal').innerText = total.toFixed(2) + '$';
    }
    new bootstrap.Modal(document.getElementById('cartModal')).show();
}

function checkout() {
    if (cart.length === 0) { alert('Panier vide.'); return; }

    // Calcul total
    const subtotal = cart.reduce((s,i) => s + i.price * i.qty, 0);
    const gst      = subtotal * taxCA;
    const qst      = (subtotal + gst) * taxQC;
    const total    = subtotal + gst + qst;

    if (!confirm('Confirmer la commande de ' + total.toFixed(2) + '$ ? (Simulation — aucun vrai paiement)')) return;

    // Envoyer commande au serveur
    const fd = new FormData();
    fd.append('checkout', '1');
    fd.append('cart', JSON.stringify(cart));
    fd.append('total', total.toFixed(2));

    fetch('store_checkout.php', { method:'POST', body:fd })
        .then(r => r.json())
        .then(d => {
            if (d.success) {
                alert('Commande confirmee ! Merci pour ton achat. (Simulation)');
                cart = [];
                updateCartBadge();
                bootstrap.Modal.getInstance(document.getElementById('cartModal')).hide();
            } else {
                alert('Erreur : ' + (d.error || 'Inconnue'));
            }
        })
        .catch(() => alert('Erreur de connexion.'));
}
</script>

<?php include 'footer.php'; ?>
