<?php
session_start();
header('Content-Type: application/json');

$response = ['cart_count' => 0];

if(!isset($_SESSION['user_id'])){
    echo json_encode($response);
    exit;
}

if(isset($_POST['product_id'])){
    $product_id = $_POST['product_id'];
    $name = $_POST['name'];
    $price = $_POST['price'];
    $image = $_POST['image'];

    $cart_item = [
        'id' => $product_id,
        'name' => $name,
        'price' => $price,
        'image' => $image,
        'quantity' => 1
    ];

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

    $found = false;
    foreach($_SESSION['cart'] as &$item){
        if($item['id'] == $product_id){
            $item['quantity']++;
            $found = true;
            break;
        }
    }
    unset($item);

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

    $response['cart_count'] = count($_SESSION['cart']);
}

echo json_encode($response);


