<?php
session_start();
include('includes/config.php');

// Inisialisasi keranjang jika belum ada
if(!isset($_SESSION['cart'])){
    $_SESSION['cart'] = [];
}

// 1. LOGIKA TAMBAH PRODUK (DENGAN CEK STOK)
if(isset($_GET['add'])){
    $id = intval($_GET['add']);
    $size = isset($_GET['size']) ? intval($_GET['size']) : 0;
    
    if($size == 0) exit(json_encode(['status'=>'error', 'msg'=>'Ukuran belum dipilih']));

    // Ambil Stok dari tabel produk_detail
    $cek_stok = mysqli_query($conn, "SELECT stok FROM produk_detail WHERE id_produk = '$id' AND ukuran = '$size'");
    $data_stok = mysqli_fetch_assoc($cek_stok);
    $stok_db = $data_stok ? intval($data_stok['stok']) : 0;

    $key = $id . "-" . $size;
    $qty_di_keranjang = isset($_SESSION['cart'][$key]) ? $_SESSION['cart'][$key]['qty'] : 0;

    // Validasi stok
    if(($qty_di_keranjang + 1) > $stok_db){
        exit(json_encode(['status'=>'error', 'msg'=>'Maaf, stok ukuran ini tidak mencukupi.']));
    }

    if(isset($_SESSION['cart'][$key]) && is_array($_SESSION['cart'][$key])){
        $_SESSION['cart'][$key]['qty'] += 1;
    } else {
        $_SESSION['cart'][$key] = [
            'id_produk' => $id,
            'ukuran' => $size,
            'qty' => 1
        ];
    }
    exit(json_encode(['status'=>'ok']));
}

// 2. LOGIKA HAPUS
if(isset($_GET['remove'])){
    $key = $_GET['remove'];
    unset($_SESSION['cart'][$key]);
    exit(json_encode(['status'=>'ok']));
}

// 3. LOGIKA UPDATE JUMLAH (DENGAN CEK STOK)
if(isset($_GET['update'], $_GET['op'])){
    $key = $_GET['update'];
    if(!isset($_SESSION['cart'][$key])) exit(json_encode(['status'=>'error']));
    
    $id_p = $_SESSION['cart'][$key]['id_produk'];
    $uk = $_SESSION['cart'][$key]['ukuran'];
    $qty_sekarang = $_SESSION['cart'][$key]['qty'];

    if($_GET['op']=='plus'){
        // Cek stok lagi sebelum tambah
        $cek_stok = mysqli_query($conn, "SELECT stok FROM produk_detail WHERE id_produk = '$id_p' AND ukuran = '$uk'");
        $data_stok = mysqli_fetch_assoc($cek_stok);
        $stok_db = intval($data_stok['stok']);

        if(($qty_sekarang + 1) > $stok_db){
            exit(json_encode(['status'=>'error', 'msg'=>'Maksimum stok tersedia: ' . $stok_db]));
        }
        $_SESSION['cart'][$key]['qty']++;
    } elseif($_GET['op']=='minus'){
        if($_SESSION['cart'][$key]['qty'] > 1){
            $_SESSION['cart'][$key]['qty']--;
        } else {
            exit(json_encode(['status'=>'min','qty'=>1]));
        }
    }
    exit(json_encode(['status'=>'ok','qty'=>$_SESSION['cart'][$key]['qty']]));
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Keranjang Belanja - Alfateeh Sepatuku</title>
    <style>
        body { font-family: 'Poppins', sans-serif; background:#f5f5f5; margin:0; padding:0; }
        .cart-container { max-width:900px; margin:40px auto; background:#fff; padding:25px; border-radius:12px; box-shadow:0 5px 20px rgba(0,0,0,0.1); }
        .cart-item { display:flex; align-items:center; border-bottom:1px solid #eee; padding:20px 0; }
        .cart-item img { width:90px; height:90px; border-radius:10px; object-fit:cover; }
        .item-info { flex:1; margin-left:20px; }
        .item-info strong { font-size: 1.1rem; color: #333; }
        .badge-size { display: inline-block; background: #e3f2fd; color: #1e88e5; padding: 2px 8px; border-radius: 5px; font-size: 0.85rem; margin: 5px 0; font-weight: bold; }
        .qty-control { display:flex; align-items:center; gap:12px; margin: 0 20px; }
        .qty-btn { background:#1e88e5; color:#fff; border:none; width:30px; height:30px; border-radius:5px; cursor:pointer; font-size: 1.2rem; }
        .subtotal { width:160px; text-align:right; font-weight:700; color: #1e88e5; }
        .total { text-align:right; font-size:1.4rem; font-weight:bold; margin-top:30px; padding-top: 20px; border-top: 2px solid #eee; }
        .checkout-btn { display:block; text-align:center; margin-top:25px; background:#00b4d8; color:#fff; padding:15px; border-radius:10px; text-decoration:none; font-weight:bold; font-size: 1.1rem; }
        .remove-btn { background:none; border:none; color:#e63946; cursor:pointer; font-weight:600; margin-left:15px; }
    </style>
</head>
<body>

<div class="cart-container">
    <h1>🛒 Keranjang Belanja</h1>

    <?php if(count($_SESSION['cart']) > 0): ?>
    <form method="get" action="checkout.php">
        <?php
        $discount = 0.2; 
        foreach($_SESSION['cart'] as $key => $item):
            if(!is_array($item)) { unset($_SESSION['cart'][$key]); continue; }

            $id = $item['id_produk'];
            $uk = $item['ukuran'];
            $qty = $item['qty'];

            $sql = mysqli_query($conn, "SELECT * FROM produk WHERE id='$id'");
            $product = mysqli_fetch_assoc($sql);
            if(!$product) continue;

            $price = $product['harga'];
            $subtotal = ($qty >= 2) ? ($price + ($price*(1-$discount)) + ($qty-2)*$price) : ($price * $qty);
        ?>
        <div class="cart-item" data-key="<?= $key ?>" data-price="<?= $price ?>">
            <input type="checkbox" name="checkout_items[]" value="<?= $key ?>" checked class="cb-item">
            <img src="assets/img/<?= htmlspecialchars($product['gambar']) ?>">
            <div class="item-info">
                <strong><?= htmlspecialchars($product['nama']) ?></strong><br>
                <span class="badge-size">Ukuran: <?= $uk ?></span><br>
                <span style="color: #888;">Rp <?= number_format($price,0,",",".") ?></span>
            </div>
            <div class="qty-control">
                <button type="button" class="qty-btn minus">–</button>
                <span class="qty"><?= $qty ?></span>
                <button type="button" class="qty-btn plus">+</button>
            </div>
            <div class="subtotal">Rp <?= number_format($subtotal,0,",",".") ?></div>
            <button type="button" class="remove-btn">Hapus</button>
        </div>
        <?php endforeach; ?>

        <div class="total">Total: Rp <span id="grand-total">0</span></div>
        <button type="submit" class="checkout-btn">Lanjutkan Checkout</button>
    </form>
    <?php else: ?>
        <div style="text-align:center; padding: 40px;">
            <p>Keranjang kamu masih kosong nih.</p>
            <a href="product.php" class="checkout-btn" style="display:inline-block; padding: 10px 30px;">Mulai Belanja</a>
        </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const discount = 0.2;

    function updateTotal() {
        let total = 0;
        document.querySelectorAll('.cart-item').forEach(function(item){
            const cb = item.querySelector('.cb-item');
            const price = parseInt(item.dataset.price) || 0;
            const qty = parseInt(item.querySelector('.qty').innerText) || 0;
            let subtotal = (qty >= 2) ? (price + (price * (1 - discount)) + (qty - 2) * price) : (price * qty);

            item.querySelector('.subtotal').innerText = 'Rp ' + subtotal.toLocaleString('id-ID');
            if(cb && cb.checked) { total += subtotal; }
        });
        document.getElementById('grand-total').innerText = total.toLocaleString('id-ID');
    }

    document.querySelectorAll('.cart-item').forEach(item => {
        const key = item.dataset.key;

        item.querySelector('.plus').addEventListener('click', () => {
            fetch('keranjang.php?update=' + key + '&op=plus')
                .then(res => res.json())
                .then(data => {
                    if(data.status === 'error') {
                        alert(data.msg); 
                    } else {
                        item.querySelector('.qty').innerText = data.qty;
                        updateTotal();
                    }
                });
        });

        item.querySelector('.minus').addEventListener('click', () => {
            fetch('keranjang.php?update=' + key + '&op=minus')
                .then(res => res.json())
                .then(data => {
                    if(data.status == 'min') return;
                    item.querySelector('.qty').innerText = data.qty;
                    updateTotal();
                });
        });

        item.querySelector('.remove-btn').addEventListener('click', () => {
            if(confirm('Hapus item ini?')){
                fetch('keranjang.php?remove=' + key)
                    .then(() => {
                        item.remove();
                        updateTotal();
                    });
            }
        });

        item.querySelector('.cb-item').addEventListener('change', updateTotal);
    });

    updateTotal();
});
</script>
</body>
</html>