<?php
require_once __DIR__ . '/../includes/header_customer.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/cart.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$stmt = $pdo->prepare('SELECT p.*, c.name AS category_name FROM products p LEFT JOIN categories c ON c.id = p.category_id WHERE p.id = ? LIMIT 1');
$stmt->execute([$id]);
$product = $stmt->fetch();

if (!$product) {
    // Header already included
    echo '<div class="alert error">Produk tidak ditemukan.</div>';
    require_once __DIR__ . '/../includes/footer_customer.php';
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!is_logged_in()) {
        flash_message('error', 'Silakan login terlebih dahulu untuk menambahkan ke keranjang.');
        redirect(base_url('pages/login.php'));
    }

    if ((current_user()['role'] ?? '') !== 'customer') {
        flash_message('error', 'Hanya customer yang dapat berbelanja.');
        redirect(base_url('public/index.php?page=product_detail&id=' . (int) $product['id']));
    }

    $qty = max(1, (int) ($_POST['qty'] ?? 1));
    $qty = min($qty, (int) $product['stock']);

    if ($qty < 1) {
        flash_message('error', 'Stok tidak mencukupi.');
        redirect(base_url('public/index.php?page=product_detail&id=' . (int) $product['id']));
    }

    $cartId = get_or_create_cart($pdo, (int) current_user()['id']);
    add_cart_item($pdo, $cartId, (int) $product['id'], $qty, (float) $product['price']);
    flash_message('success', 'Produk ditambahkan ke keranjang.');
    redirect(base_url('public/index.php?page=cart'));
}

require_once __DIR__ . '/../includes/header_customer.php';
?>

<div class="row g-4 justify-content-center">
    <!-- Product Image Section -->
    <div class="col-lg-7">
        <div class="detail-card p-2 p-md-3">
            <div class="detail-image-wrapper">
                <?php if (!empty($product['photo'])): ?>
                    <img class="img-fluid rounded-4 shadow-sm w-100" src="<?= base_url('uploads/' . sanitize($product['photo'])); ?>" alt="<?= sanitize($product['name']); ?>">
                <?php else: ?>
                    <div class="product-thumb fs-2">Al-Qanuni</div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Product Info Section (Sticky) -->
    <div class="col-lg-5">
        <div class="sticky-top" style="top: 100px; z-index: 10;">
            <div class="detail-card p-4 p-lg-5">
                <span class="category-chip mb-3"><?= sanitize($product['category_name'] ?? 'Umum'); ?></span>
                <h1 class="fw-bold display-6 mb-3"><?= sanitize($product['name']); ?></h1>
                
                <div class="price-section mb-4">
                    <h2 class="price-tag display-6 mb-0"><?= format_currency($product['price']); ?></h2>
                    <span class="text-muted d-block mt-1">Stok tersedia: <strong class="<?= (int)$product['stock'] > 0 ? 'text-success' : 'text-danger'; ?>"><?= (int) $product['stock']; ?> unit</strong></span>
                </div>

                <div class="description-section mb-4">
                    <h6 class="fw-bold text-muted text-uppercase small ls-1">Deskripsi Produk</h6>
                    <p class="lead fs-6 text-secondary"><?= nl2br(sanitize($product['description'])); ?></p>
                </div>

                <hr class="my-4 border-secondary opacity-10">

                <form method="post" class="add-to-cart-form">
                    <div class="row g-3 align-items-end">
                        <div class="col-4">
                            <label class="fw-bold small mb-2 text-muted">Jumlah</label>
                            <input type="number" class="form-control form-control-lg text-center fw-bold bg-light border-0" name="qty" value="1" min="1" max="<?= (int) $product['stock']; ?>">
                        </div>
                        <div class="col-8">
                            <button class="btn btn-lg w-100 py-3 d-flex align-items-center justify-content-center gap-2" type="submit" <?= (int) $product['stock'] === 0 ? 'disabled' : ''; ?>>
                                <i class="bi bi-bag-plus-fill"></i>
                                <?= (int) $product['stock'] === 0 ? 'Stok Habis' : 'Beli Sekarang'; ?>
                            </button>
                        </div>
                    </div>
                </form>
                
                <div class="mt-4 pt-3 text-center border-top">
                    <div class="row text-muted small">
                        <div class="col-4 border-end">
                            <div class="d-flex flex-column align-items-center">
                                <i class="bi bi-shield-check fs-4 mb-1 text-success"></i>
                                <span>Original</span>
                            </div>
                        </div>
                        <div class="col-4 border-end">
                            <div class="d-flex flex-column align-items-center">
                                <i class="bi bi-truck fs-4 mb-1 text-primary"></i>
                                <span>Fast Ship</span>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="d-flex flex-column align-items-center">
                                <i class="bi bi-chat-heart fs-4 mb-1 text-danger"></i>
                                <span>Support</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_customer.php'; ?>
