<?php
session_start();
include 'includes/connect.php';

header('Content-Type: application/json');

$user_id = $_SESSION['user_id'] ?? $_SESSION['distributor_id'] ?? 0;

if($user_id == 0){
    echo json_encode(["success"=>false,"message"=>"Login required"]);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true);

$id = intval($data['id']);
$action = $data['action'];

$cart = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM cart WHERE id='$id' AND user_id='$user_id'"));

if(!$cart){
    echo json_encode(["success"=>false,"message"=>"Not found"]);
    exit;
}

$newQty = $cart['quantity'];

if($action == "increase"){
    $newQty++;
} else if($action == "decrease"){
    $newQty--;
}

if($newQty <= 0){
    mysqli_query($conn,"DELETE FROM cart WHERE id='$id'");
    echo json_encode(["success"=>true,"quantity"=>0]);
    exit;
}

mysqli_query($conn,"UPDATE cart SET quantity='$newQty' WHERE id='$id'");

echo json_encode(["success"=>true,"quantity"=>$newQty]);