<?php
require_once __DIR__ . '/../system/core/config.php';
require_once __DIR__ . '/../system/helpers/functions.php';

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

/*
|--------------------------------------------------------------------------
| ACTION
|--------------------------------------------------------------------------
*/

$action = $_POST['action'] ?? $_GET['action'] ?? '';

/*
|--------------------------------------------------------------------------
| HANDLE POST
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    verify_csrf();

    /*
    |--------------------------------------------------------------------------
    | ADD TO CART
    |--------------------------------------------------------------------------
    */

    if ($action === 'add') {

        $productId = (int)($_POST['product_id'] ?? 0);
        $variantId = (int)($_POST['variant_id'] ?? 0);
        $qty = max(1, (int)($_POST['qty'] ?? 1));

        $key = $productId . ':' . $variantId;

        if (!isset($_SESSION['cart'][$key])) {

            $_SESSION['cart'][$key] = [
                'product_id' => $productId,
                'variant_id' => $variantId,
                'qty' => 0
            ];
        }

        $_SESSION['cart'][$key]['qty'] += $qty;

        redirect('cart.php');
    }

    /*
    |--------------------------------------------------------------------------
    | UPDATE CART
    |--------------------------------------------------------------------------
    */

    if ($action === 'update') {

        foreach ($_POST['qty'] ?? [] as $key => $qty) {

            $qty = (int)$qty;

            if ($qty <= 0) {

                unset($_SESSION['cart'][$key]);

            } else {

                $_SESSION['cart'][$key]['qty'] = $qty;
            }
        }

        redirect('cart.php');
    }

    /*
    |--------------------------------------------------------------------------
    | CLEAR CART
    |--------------------------------------------------------------------------
    */

    if ($action === 'clear') {

        $_SESSION['cart'] = [];

        redirect('cart.php');
    }
}

/*
|--------------------------------------------------------------------------
| LOAD CART ITEMS
|--------------------------------------------------------------------------
*/

$items = [];
$total = 0;

foreach ($_SESSION['cart'] as $key => $cart) {

    $stmt = $pdo->prepare("
        SELECT *
        FROM products
        WHERE id = ?
          AND is_active = 1
        LIMIT 1
    ");

    $stmt->execute([
        (int)$cart['product_id']
    ]);

    $product = $stmt->fetch();

    if (!$product) {

        unset($_SESSION['cart'][$key]);

        continue;
    }

    $variant = null;

    $price = (int)$product['price'];
    $weight = (int)$product['weight_gram'];

    /*
    |--------------------------------------------------------------------------
    | LOAD VARIANT
    |--------------------------------------------------------------------------
    */

    if (!empty($cart['variant_id'])) {

        $stmt = $pdo->prepare("
            SELECT *
            FROM product_variants
            WHERE id = ?
              AND product_id = ?
              AND is_active = 1
            LIMIT 1
        ");

        $stmt->execute([
            (int)$cart['variant_id'],
            (int)$product['id']
        ]);

        $variant = $stmt->fetch();

        if ($variant) {

            $price += (int)$variant['price_adjustment'];

            if ((int)$variant['weight_gram'] > 0) {

                $weight = (int)$variant['weight_gram'];
            }
        }
    }

    $qty = max(1, (int)$cart['qty']);

    $subtotal = $price * $qty;

    $total += $subtotal;

    $items[$key] = [
        'product' => $product,
        'variant' => $variant,
        'qty' => $qty,
        'price' => $price,
        'weight' => $weight,
        'subtotal' => $subtotal
    ];
}
?>
<!DOCTYPE html>
<html lang="id">

<head>

    <meta charset="UTF-8">

    <title>Keranjang Belanja</title>

    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">

    <script src="https://cdn.tailwindcss.com"></script>

</head>

<body class="bg-slate-100 text-slate-800">

<main class="max-w-6xl mx-auto px-4 py-6 md:py-10">

    <!-- HEADER -->

    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6">

        <div>

            <h1 class="text-3xl md:text-4xl font-black">
                Keranjang Belanja
            </h1>

            <p class="text-slate-500 mt-1">
                Review produk sebelum checkout.
            </p>

        </div>

        <a href="index.php"
           class="bg-white border border-slate-200 hover:border-green-500 px-5 py-3 rounded-2xl font-bold text-center transition">
            ← Belanja Lagi
        </a>

    </div>

    <?php if (!$items): ?>

        <div class="bg-white rounded-3xl shadow p-10 text-center">

            <h2 class="text-2xl font-black mb-3">
                Keranjang kosong
            </h2>

            <p class="text-slate-500 mb-6">
                Belum ada produk di keranjang Anda.
            </p>

            <a href="index.php"
               class="inline-block bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-2xl font-bold transition">
                Mulai Belanja
            </a>

        </div>

    <?php else: ?>

        <form method="POST"
              class="grid lg:grid-cols-3 gap-6">

            <input type="hidden"
                   name="csrf_token"
                   value="<?= csrf_token() ?>">

            <input type="hidden"
                   name="action"
                   value="update">

            <!-- CART ITEMS -->

            <section class="lg:col-span-2 bg-white rounded-3xl shadow overflow-hidden">

                <?php foreach ($items as $key => $item): ?>

                    <div class="p-4 md:p-5 border-b border-slate-100">

                        <div class="flex flex-col md:flex-row md:items-center gap-5">

                            <!-- IMAGE -->

                            <img src="../uploads/products/<?= e($item['product']['image']) ?>"
                                 class="w-full md:w-28 h-40 md:h-28 object-cover rounded-2xl bg-slate-100"
                                 alt="<?= e($item['product']['name']) ?>">

                            <!-- CONTENT -->

                            <div class="flex-1">

                                <h3 class="text-lg font-black">
                                    <?= e($item['product']['name']) ?>
                                </h3>

                                <?php if ($item['variant']): ?>

                                    <p class="text-sm text-slate-500 mt-1">
                                        Varian:
                                        <?= e($item['variant']['variant_name']) ?>
                                    </p>

                                <?php endif; ?>

                                <p class="text-green-700 font-black mt-2">
                                    <?= rupiah($item['price']) ?>
                                </p>

                                <p class="text-xs text-slate-400 mt-1">
                                    Berat:
                                    <?= number_format($item['weight']) ?> gram
                                </p>

                            </div>

                            <!-- QTY -->

                            <div class="flex flex-row md:flex-col items-center gap-3">

                                <label class="text-sm font-bold text-slate-500">
                                    Qty
                                </label>

                                <input type="number"
                                       name="qty[<?= e($key) ?>]"
                                       value="<?= $item['qty'] ?>"
                                       min="0"
                                       class="w-24 border border-slate-300 rounded-xl px-3 py-2 text-center font-bold">

                            </div>

                            <!-- SUBTOTAL -->

                            <div class="text-right">

                                <p class="text-xs text-slate-400 uppercase font-bold">
                                    Subtotal
                                </p>

                                <strong class="text-lg text-orange-600">
                                    <?= rupiah($item['subtotal']) ?>
                                </strong>

                                <p class="text-xs text-red-500 mt-2">
                                    Isi 0 untuk hapus
                                </p>

                            </div>

                        </div>

                    </div>

                <?php endforeach; ?>

            </section>

            <!-- SUMMARY -->

            <aside class="bg-white rounded-3xl shadow p-6 h-fit sticky top-5">

                <h2 class="text-2xl font-black mb-5">
                    Ringkasan Belanja
                </h2>

                <div class="flex justify-between py-3 border-b">

                    <span class="text-slate-500">
                        Total Produk
                    </span>

                    <strong>
                        <?= count($items) ?>
                    </strong>

                </div>

                <div class="flex justify-between py-4 text-xl font-black">

                    <span>Total</span>

                    <span class="text-green-700">
                        <?= rupiah($total) ?>
                    </span>

                </div>

                <div class="space-y-3 mt-6">

                    <button type="submit"
                            class="w-full bg-slate-900 hover:bg-slate-800 text-white py-4 rounded-2xl font-bold transition">
                        Update Cart
                    </button>

                    <a href="checkout.php"
                       class="block text-center bg-green-600 hover:bg-green-700 text-white py-4 rounded-2xl font-bold transition">
                        Checkout
                    </a>

                </div>

            </aside>

        </form>

    <?php endif; ?>

</main>

</body>
</html>