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

// Ambil ID produk
$product_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

$stmt = $db->prepare("SELECT * FROM products WHERE id = ? AND is_active = 1");
$stmt->execute([$product_id]);
$product = $stmt->fetch();

if (!$product) {
    // Jika produk tidak ditemukan, arahkan kembali ke katalog
    header("Location: index.php");
    exit();
}

// Proses submit Add to Cart
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_to_cart') {
    $qty = isset($_POST['qty']) ? intval($_POST['qty']) : 1;
    
    // Validasi stok
    if ($qty > $product['stock']) {
        $error_msg = "Maaf, jumlah pesanan melebihi stok yang tersedia.";
    } elseif ($qty <= 0) {
        $error_msg = "Jumlah pesanan tidak valid.";
    } else {
        if (!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = [];
        }
        
        // Tambahkan atau update jumlah di keranjang
        if (isset($_SESSION['cart'][$product_id])) {
            $_SESSION['cart'][$product_id] += $qty;
        } else {
            $_SESSION['cart'][$product_id] = $qty;
        }
        
        // Arahkan ke halaman keranjang belanja
        header("Location: cart.php");
        exit();
    }
}

$page_title = $product['name'] . " - Toko Kue Edelys";
require_once __DIR__ . '/includes/header.php';
?>

<main style="margin-top: 2rem;">
    <div style="margin-bottom: 1.5rem;">
        <a href="index.php" style="color: var(--text-secondary); font-size: 0.95rem; font-weight: 500;">
            <i class="fa-solid fa-arrow-left-long"></i> Kembali ke Katalog
        </a>
    </div>

    <?php if (isset($error_msg)): ?>
        <div style="background-color: rgba(178, 83, 62, 0.1); color: var(--danger-color); padding: 1rem; border-radius: var(--radius-sm); border: 1px solid var(--danger-color); margin-bottom: 1.5rem;">
            <i class="fa-solid fa-triangle-exclamation"></i> <?php echo htmlspecialchars($error_msg); ?>
        </div>
    <?php endif; ?>

    <div class="product-detail-container">
        <!-- Bagian Gambar -->
        <div class="detail-gallery">
            <img src="<?php echo htmlspecialchars($product['image_url']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
        </div>

        <!-- Bagian Informasi Produk -->
        <div class="detail-info">
            <span class="product-category" style="font-size: 0.9rem; margin-bottom: 0.8rem; display: inline-block;">
                <?php echo htmlspecialchars($product['category']); ?>
            </span>
            <h1 class="detail-title"><?php echo htmlspecialchars($product['name']); ?></h1>
            <div class="detail-price">
                Rp <?php echo number_format($product['price'], 0, ',', '.'); ?>
            </div>

            <div class="detail-desc-block">
                <h3 class="detail-desc-title">Deskripsi Kue</h3>
                <p class="detail-desc-text"><?php echo nl2br(htmlspecialchars($product['description'])); ?></p>
            </div>

            <!-- Stok & Form Order -->
            <div style="margin-bottom: 1.5rem;">
                <strong>Status Ketersediaan:</strong>
                <?php if ($product['stock'] <= 0): ?>
                    <span style="color: var(--danger-color); font-weight: bold; margin-left: 0.5rem;"><i class="fa-solid fa-circle-xmark"></i> Stok Habis</span>
                <?php else: ?>
                    <span style="color: var(--success-color); font-weight: bold; margin-left: 0.5rem;"><i class="fa-solid fa-circle-check"></i> Ready (Tersedia <?php echo $product['stock']; ?> pcs)</span>
                <?php endif; ?>
            </div>

            <?php if ($product['stock'] > 0): ?>
                <form action="product.php?id=<?php echo $product['id']; ?>" method="POST" class="order-form-box">
                    <input type="hidden" name="action" value="add_to_cart">
                    
                    <div class="form-group">
                        <label for="qty">Tentukan Jumlah Pesanan</label>
                        <div class="quantity-input-group">
                            <button type="button" class="quantity-btn" onclick="decreaseQty()">-</button>
                            <input type="number" name="qty" id="qty" class="quantity-val" value="1" min="1" max="<?php echo $product['stock']; ?>" readonly>
                            <button type="button" class="quantity-btn" onclick="increaseQty()">+</button>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-full"><i class="fa-solid fa-cart-plus"></i> Masukkan Keranjang</button>
                </form>
            <?php else: ?>
                <div class="order-form-box" style="text-align: center; background-color: #ECEFF1; border-color: #CFD8DC;">
                    <p style="color: #546E7A; font-weight: 500; margin-bottom: 0.5rem;">Kue Ini Sedang Tidak Tersedia</p>
                    <button class="btn btn-full" style="background-color: #B0BEC5; color: #FFFFFF; cursor: not-allowed;" disabled>Stok Habis</button>
                </div>
            <?php endif; ?>
        </div>
    </div>
</main>

<script>
function increaseQty() {
    var qtyInput = document.getElementById('qty');
    var maxVal = parseInt(qtyInput.getAttribute('max'));
    var currentVal = parseInt(qtyInput.value);
    if (currentVal < maxVal) {
        qtyInput.value = currentVal + 1;
    }
}

function decreaseQty() {
    var qtyInput = document.getElementById('qty');
    var currentVal = parseInt(qtyInput.value);
    if (currentVal > 1) {
        qtyInput.value = currentVal - 1;
    }
}
</script>

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