<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/cart.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/abandoned-cart.php';

$pageTitle = 'Cart | LOVE-U Essentials';
$pageDescription = 'Review your LOVE-U Essentials cart before checkout.';

$currentCustomer = function_exists('customer') ? customer() : null;

if (isset($_GET['recover'])) {
    $recoveryToken = trim($_GET['recover']);

    if ($recoveryToken !== '') {
        $stmt = $pdo->prepare("
            SELECT *
            FROM abandoned_carts
            WHERE recovery_token = ?
              AND status = 'pending'
            LIMIT 1
        ");
        $stmt->execute([$recoveryToken]);
        $recoveryCart = $stmt->fetch();

        if ($recoveryCart) {
            $stmt = $pdo->prepare("
                SELECT *
                FROM abandoned_cart_items
                WHERE abandoned_cart_id = ?
            ");
            $stmt->execute([$recoveryCart['id']]);
            $recoveryItems = $stmt->fetchAll();

            clear_cart();

            foreach ($recoveryItems as $recoveryItem) {
                add_to_cart(
                    (int) $recoveryItem['product_id'],
                    (int) $recoveryItem['quantity'],
                    !empty($recoveryItem['variation_id']) ? (int) $recoveryItem['variation_id'] : null
                );
            }

            $_SESSION['abandoned_cart_session_id'] = $recoveryCart['session_id'];

            redirect(BASE_URL . '/public/cart.php?recovered_cart=1');
        }
    }

    redirect(BASE_URL . '/public/cart.php?recovery_failed=1');
}

if (is_post()) {
    $action = $_POST['action'] ?? 'add';

    if ($action === 'add') {
        $productId = (int) ($_POST['product_id'] ?? 0);
        $variationId = !empty($_POST['variation_id']) ? (int) $_POST['variation_id'] : null;
        $quantity = max(1, (int) ($_POST['quantity'] ?? 1));

        if ($productId > 0) {
            $stmtProduct = $pdo->prepare("SELECT slug, stock_quantity, stock_status FROM products WHERE id = ? LIMIT 1");
            $stmtProduct->execute([$productId]);
            $cartProduct = $stmtProduct->fetch();

            if (!$cartProduct) {
                redirect(BASE_URL . '/public/cart.php?error=invalid_product');
            }

            if ($variationId) {
                $stmt = $pdo->prepare("
                SELECT *
                FROM product_variations
                WHERE id = ?
                  AND product_id = ?
                  AND status = 'active'
                LIMIT 1
            ");
                $stmt->execute([$variationId, $productId]);
                $variation = $stmt->fetch();

                if (!$variation) {
                    redirect(BASE_URL . '/public/product.php?slug=' . urlencode($cartProduct['slug']) . '&variation=invalid');
                }

                if ((int) $variation['stock_quantity'] <= 0) {
                    redirect(BASE_URL . '/public/product.php?slug=' . urlencode($cartProduct['slug']) . '&variation=out_of_stock');
                }

                if ($quantity > (int) $variation['stock_quantity']) {
                    $quantity = (int) $variation['stock_quantity'];
                }
            } else {
                if ($cartProduct['stock_status'] === 'out_of_stock' || (int) $cartProduct['stock_quantity'] <= 0) {
                    redirect(BASE_URL . '/public/product.php?slug=' . urlencode($cartProduct['slug']) . '&stock=out');
                }

                if ($quantity > (int) $cartProduct['stock_quantity']) {
                    $quantity = (int) $cartProduct['stock_quantity'];
                }
            }

            add_to_cart($productId, $quantity, $variationId);
        }

        redirect(BASE_URL . '/public/cart.php');
    }

    if ($action === 'update') {
        foreach ($_POST['quantities'] ?? [] as $cartKey => $quantity) {
            update_cart_item($cartKey, (int) $quantity);
        }

        redirect(BASE_URL . '/public/cart.php?updated=1');
    }
}

if (isset($_GET['remove'])) {
    remove_cart_item((string) $_GET['remove']);
    redirect(BASE_URL . '/public/cart.php?removed=1');
}

$cart = get_cart();
$productIds = [];

foreach ($cart as $cartKey => $cartItem) {
    if (!empty($cartItem['product_id'])) {
        $productIds[] = (int) $cartItem['product_id'];
    }
}

$productIds = array_values(array_unique($productIds));

$cartItems = [];
$subtotal = 0;

if ($productIds) {
    $placeholders = implode(',', array_fill(0, count($productIds), '?'));

    $stmt = $pdo->prepare("
        SELECT p.*,
            (
                SELECT image_path
                FROM product_images
                WHERE product_id = p.id
                ORDER BY is_primary DESC, sort_order ASC, id ASC
                LIMIT 1
            ) AS primary_image
        FROM products p
        WHERE p.id IN ($placeholders)
          AND p.status = 'active'
    ");

    $stmt->execute($productIds);
    $products = $stmt->fetchAll();

    foreach ($cart as $cartKey => $cartItem) {
        $productId = (int) ($cartItem['product_id'] ?? 0);
        $variationId = !empty($cartItem['variation_id']) ? (int) $cartItem['variation_id'] : null;

        $product = null;

        foreach ($products as $productRow) {
            if ((int) $productRow['id'] === $productId) {
                $product = $productRow;
                break;
            }
        }

        if (!$product) {
            continue;
        }

        $variation = null;

        if ($variationId) {
            $stmtVariation = $pdo->prepare("
            SELECT *
            FROM product_variations
            WHERE id = ?
              AND product_id = ?
              AND status = 'active'
            LIMIT 1
        ");
            $stmtVariation->execute([$variationId, $productId]);
            $variation = $stmtVariation->fetch();
        }

        $quantity = (int) ($cartItem['quantity'] ?? 1);
        $basePrice = !empty($product['sale_price']) ? (float) $product['sale_price'] : (float) $product['regular_price'];
        $unitPrice = $basePrice + (float) ($variation['price_adjustment'] ?? 0);
        $lineTotal = $unitPrice * $quantity;

$displayImage = $product['primary_image'] ?? '';

if (!empty($variation['image_path'])) {
    $displayImage = $variation['image_path'];
}

$subtotal += $lineTotal;

$cartItems[] = [
    'cart_key' => $cartKey,
    'product' => $product,
    'variation' => $variation,
    'display_image' => $displayImage,
    'quantity' => $quantity,
    'unit_price' => $unitPrice,
    'line_total' => $lineTotal,
];
    }
}
if ($cartItems && $subtotal > 0) {
    $abandonedCartItems = [];

    foreach ($cartItems as $item) {
        $variation = $item['variation'] ?? null;

        $abandonedCartItems[] = [
            'product_id' => $item['product']['id'],
            'variation_id' => $variation['id'] ?? null,
            'product_name' => $item['product']['product_name'],
            'variation_name' => $variation
                ? $variation['variation_name'] . ': ' . $variation['variation_value']
                : null,
            'quantity' => $item['quantity'],
            'unit_price' => $item['unit_price'],
        ];
    }

    upsert_abandoned_cart(
        $currentCustomer['id'] ?? null,
        $currentCustomer['email'] ?? '',
        $subtotal,
        $abandonedCartItems
    );
}

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

<section class="lue-cart-page">
    <div class="lue-cart-orb lue-cart-orb-one"></div>
    <div class="lue-cart-orb lue-cart-orb-two"></div>

    <div class="container">
        <div class="lue-cart-hero">
            <div>
                <div class="eyebrow">Your Bag</div>
                <h1>Shopping Cart</h1>
                <p>Review your selected LOVE-U Essentials before moving to secure checkout.</p>
            </div>

            <a href="<?= e(BASE_URL); ?>/public/shop.php" class="lue-cart-continue">Continue Shopping</a>
        </div>

        <?php if (isset($_GET['recovered_cart'])): ?>
            <div class="lue-cart-alert lue-cart-alert-success">
                Your cart has been restored. You can now continue checkout.
            </div>
        <?php endif; ?>

        <?php if (isset($_GET['recovery_failed'])): ?>
            <div class="lue-cart-alert lue-cart-alert-error">
                This recovery link is invalid or expired.
            </div>
        <?php endif; ?>

        <?php if (isset($_GET['updated'])): ?>
            <div class="lue-cart-alert lue-cart-alert-success">
                Your cart has been updated.
            </div>
        <?php endif; ?>

        <?php if (isset($_GET['removed'])): ?>
            <div class="lue-cart-alert">
                Item removed from your cart.
            </div>
        <?php endif; ?>

        <?php if (!$cartItems): ?>
            <div class="lue-cart-empty">
                <span>Empty Bag</span>
                <h2>Your cart is empty</h2>
                <p>Explore LOVE-U Essentials and add your favourite self-care products to your cart.</p>
                <a href="<?= e(BASE_URL); ?>/public/shop.php" class="btn">Start Shopping</a>
            </div>
        <?php else: ?>
            <form method="POST" class="lue-cart-form">
                <input type="hidden" name="action" value="update">

                <div class="lue-cart-layout">
                    <div class="lue-cart-items-panel">
                        <div class="lue-cart-panel-head">
                            <div>
                                <span>Selected Essentials</span>
                                <h2><?= e(count($cartItems)); ?> item<?= count($cartItems) === 1 ? '' : 's'; ?> in your bag</h2>
                            </div>

                            <button type="submit" class="lue-cart-update-top">Update Cart</button>
                        </div>

                        <div class="lue-cart-items">
                            <?php foreach ($cartItems as $item): ?>
                                <?php
                                $product = $item['product'];
                                $maxQty = max(1, (int) $product['stock_quantity']);

                                if (!empty($item['variation']) && isset($item['variation']['stock_quantity'])) {
                                    $maxQty = max(1, (int) $item['variation']['stock_quantity']);
                                }
                                ?>

                                <div class="lue-cart-item">
                                    <a href="<?= e(BASE_URL); ?>/public/product.php?slug=<?= e($product['slug']); ?>" class="lue-cart-item-image">
                                        <?php if (!empty($item['display_image'])): ?>
                                            <img src="<?= e(BASE_URL . '/' . $item['display_image']); ?>" alt="<?= e($product['product_name']); ?>">
                                        <?php else: ?>
                                            <div class="product-placeholder"><?= e($product['product_name']); ?></div>
                                        <?php endif; ?>
                                    </a>

                                    <div class="lue-cart-item-info">
                                        <div class="lue-cart-item-top">
                                            <div>
                                                <h3>
                                                    <a href="<?= e(BASE_URL); ?>/public/product.php?slug=<?= e($product['slug']); ?>">
                                                        <?= e($product['product_name']); ?>
                                                    </a>
                                                </h3>

                                                <?php if (!empty($item['variation'])): ?>
                                                    <p class="lue-cart-variation">
                                                        <?= e($item['variation']['variation_name']); ?>:
                                                        <strong><?= e($item['variation']['variation_value']); ?></strong>
                                                    </p>
                                                <?php endif; ?>

                                                <p class="lue-cart-unit-price">
                                                    <?= e(format_price($item['unit_price'], $product['currency_code'])); ?> each
                                                </p>
                                            </div>

                                            <a
                                                href="<?= e(BASE_URL); ?>/public/cart.php?remove=<?= e(urlencode($item['cart_key'])); ?>"
                                                class="lue-cart-remove"
                                            >
                                                Remove
                                            </a>
                                        </div>

                                        <div class="lue-cart-item-bottom">
                                            <div class="lue-qty-control" data-max="<?= e($maxQty); ?>">
                                                <button type="button" class="lue-qty-btn" data-qty-action="decrease">−</button>

                                                <input
                                                    type="number"
                                                    name="quantities[<?= e($item['cart_key']); ?>]"
                                                    value="<?= e($item['quantity']); ?>"
                                                    min="1"
                                                    max="<?= e($maxQty); ?>"
                                                    class="lue-qty-input"
                                                >

                                                <button type="button" class="lue-qty-btn" data-qty-action="increase">+</button>
                                            </div>

                                            <div class="lue-cart-line-total">
                                                <span>Line Total</span>
                                                <strong><?= e(format_price($item['line_total'], $product['currency_code'])); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <aside class="lue-cart-summary">
                        <div class="lue-cart-summary-card">
                            <div class="lue-summary-head">
                                <span>Checkout</span>
                                <h2>Order Summary</h2>
                            </div>

                            <div class="lue-summary-lines">
                                <div class="lue-summary-row">
                                    <span>Subtotal</span>
                                    <strong><?= e(format_price($subtotal)); ?></strong>
                                </div>

                                <div class="lue-summary-row">
                                    <span>Shipping</span>
                                    <strong>Calculated at checkout</strong>
                                </div>

                                <div class="lue-summary-row">
                                    <span>Discounts</span>
                                    <strong>Apply at checkout</strong>
                                </div>
                            </div>

                            <div class="lue-summary-total">
                                <span>Estimated Total</span>
                                <strong><?= e(format_price($subtotal)); ?></strong>
                            </div>

                            <div class="lue-cart-summary-actions">
                                <button type="submit" class="btn btn-light">Update Cart</button>
                                <a href="<?= e(BASE_URL); ?>/public/checkout.php" class="btn">Proceed to Checkout</a>
                            </div>

                            <div class="lue-cart-trust">
                                <span>Secure checkout</span>
                                <span>Gift-ready orders</span>
                                <span>Delivery calculated at checkout</span>
                            </div>
                        </div>
                    </aside>
                </div>
            </form>
        <?php endif; ?>
    </div>
</section>

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