<?php
session_start();
$conn = new mysqli("localhost","kkfxoaad","Bitok@2025","kkfxoaad_bella");
header('Content-Type: application/json');

if($conn->connect_error){
    echo json_encode(['success'=>false, 'error'=>'DB connection failed']);
    exit;
}

$user_id = $_SESSION['user_id'] ?? null;
$session_token = session_id();

// Get cart id
if($user_id){
    $stmt = $conn->prepare("SELECT id FROM carts WHERE user_id=?");
    $stmt->bind_param("i",$user_id);
}else{
    $stmt = $conn->prepare("SELECT id FROM carts WHERE session_token=?");
    $stmt->bind_param("s",$session_token);
}
$stmt->execute();
$res = $stmt->get_result();
$cart = $res->fetch_assoc();
$stmt->close();

if(!$cart){ 
    echo json_encode(['success'=>false]); 
    exit; 
}

$cart_id = $cart['id'];

// Update quantity
if(isset($_POST['update_quantity'])){
    $id = intval($_POST['id']);
    $qty = intval($_POST['quantity']);
    $stmt = $conn->prepare("UPDATE cart_items SET qty=? WHERE id=? AND cart_id=?");
    $stmt->bind_param("iii",$qty,$id,$cart_id);
    $stmt->execute();
}

// Remove item
if(isset($_POST['remove_item'])){
    $id = intval($_POST['id']);
    $stmt = $conn->prepare("DELETE FROM cart_items WHERE id=? AND cart_id=?");
    $stmt->bind_param("ii",$id,$cart_id);
    $stmt->execute();
}

// Recalculate totals and subtotal
$stmt = $conn->prepare("
    SELECT ci.id, ci.qty, ci.price 
    FROM cart_items ci 
    WHERE ci.cart_id=?
");
$stmt->bind_param("i",$cart_id);
$stmt->execute();
$items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$total_price = 0;
$total_items = 0;
$subtotal = 0;

foreach($items as $item){
    $total_price += $item['price'] * $item['qty'];
    $total_items += $item['qty'];
    if(isset($id) && $id == $item['id']){
        $subtotal = $item['price'] * $item['qty'];
    }
}

// In case of remove, $subtotal = 0
if(isset($_POST['remove_item'])){
    $subtotal = 0;
}

echo json_encode([
    'success'=>true,
    'subtotal'=>$subtotal,
    'total_items'=>$total_items,
    'total_price'=>$total_price
]);
