<?php
ob_start(); // Start output buffering to prevent header errors
session_start();
require 'config/db.php';

// Initialize cart
if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = []; }

// --- HELPER FUNCTION: FORCE REDIRECT ---
function safe_redirect($url) {
    if (!headers_sent()) {
        header("Location: " . $url);
    }
    // JavaScript Fallback (Guarantees redirect happens)
    echo "<script type='text/javascript'>window.location.href='$url';</script>";
    echo "<noscript><meta http-equiv='refresh' content='0;url=$url'/></noscript>";
    exit();
}

// ---------------------------------------------------------
// 1. HANDLE COUPON (From Cart Page)
// ---------------------------------------------------------
if (isset($_POST['apply_coupon'])) {
    $code = strtoupper(trim($_POST['code']));
    $stmt = $pdo->prepare("SELECT * FROM coupons WHERE code = ? AND status = 1");
    $stmt->execute([$code]);
    $coupon = $stmt->fetch();

    if ($coupon) {
        $_SESSION['coupon'] = ['code' => $coupon['code'], 'type' => $coupon['type'], 'value' => $coupon['value']];
        safe_redirect("/cart.php?msg=coupon_applied");
    } else {
        safe_redirect("/cart.php?error=invalid_coupon");
    }
}

// ---------------------------------------------------------
// 2. HANDLE REMOVE COUPON
// ---------------------------------------------------------
if (isset($_GET['remove_coupon'])) {
    unset($_SESSION['coupon']);
    safe_redirect("/cart.php");
}

// ---------------------------------------------------------
// 3. HANDLE ADD TO CART / BUY NOW
// ---------------------------------------------------------
$action = $_POST['action'] ?? '';
$variant_id = $_POST['variant_id'] ?? 0;

if ($action == 'add_to_cart' || $action == 'buy_now') {
    
    // A. Apply Coupon if entered on Product Page
    if (!empty($_POST['coupon_code'])) {
        $code = strtoupper(trim($_POST['coupon_code']));
        $stmtC = $pdo->prepare("SELECT * FROM coupons WHERE code = ? AND status = 1");
        $stmtC->execute([$code]);
        $coupon = $stmtC->fetch();
        if ($coupon) {
            $_SESSION['coupon'] = ['code' => $coupon['code'], 'type' => $coupon['type'], 'value' => $coupon['value']];
        }
    }

    // B. Add Product
    $stmt = $pdo->prepare("SELECT id FROM product_variants WHERE id = ?");
    $stmt->execute([$variant_id]);
    $variant = $stmt->fetch();

    if ($variant) {
        if (isset($_SESSION['cart'][$variant_id])) {
            $_SESSION['cart'][$variant_id]++;
        } else {
            $_SESSION['cart'][$variant_id] = 1;
        }
    }

    // C. Redirect
    if ($action == 'buy_now') {
        safe_redirect("/checkout.php");
    } else {
        safe_redirect("/cart.php?msg=added");
    }
}

// ---------------------------------------------------------
// 4. HANDLE REMOVE ITEM
// ---------------------------------------------------------
if (isset($_GET['remove'])) {
    $id = $_GET['remove'];
    unset($_SESSION['cart'][$id]);
    if(empty($_SESSION['cart'])) unset($_SESSION['coupon']);
    safe_redirect("/cart.php");
}

// ---------------------------------------------------------
// 5. HANDLE UPDATE QTY
// ---------------------------------------------------------
if (isset($_POST['update_qty'])) {
    if(isset($_POST['qty']) && is_array($_POST['qty'])) {
        foreach ($_POST['qty'] as $vid => $q) {
            $q = (int)$q;
            if ($q <= 0) unset($_SESSION['cart'][$vid]);
            else $_SESSION['cart'][$vid] = $q;
        }
    }
    safe_redirect("/cart.php");
}

// Default Fallback
safe_redirect("/index.php");

// --- ABANDONED CART TRACKER ---
if (isset($_SESSION['user_id']) && !empty($_SESSION['cart'])) {
    $uid = $_SESSION['user_id'];
    $cart_json = json_encode($_SESSION['cart']);
    
    // Check if entry exists for today
    $check = $pdo->prepare("SELECT id FROM abandoned_carts WHERE user_id = ? AND status = 'pending'");
    $check->execute([$uid]);
    $exist = $check->fetch();
    
    if ($exist) {
        // Update existing
        $pdo->prepare("UPDATE abandoned_carts SET cart_data = ?, created_at = NOW() WHERE id = ?")->execute([$cart_json, $exist['id']]);
    } else {
        // Create new
        // Fetch email
        $uEmail = $pdo->query("SELECT email FROM users WHERE id = $uid")->fetchColumn();
        $pdo->prepare("INSERT INTO abandoned_carts (user_id, email, cart_data) VALUES (?, ?, ?)")->execute([$uid, $uEmail, $cart_json]);
    }
}
?>


