<?php
require_once 'includes/bootstrap.php';
header('Content-Type: application/json; charset=utf-8');
$pid = 0;
if(isset($_POST['product_id'])) $pid=(int)$_POST['product_id'];
elseif(isset($_POST['id'])) $pid=(int)$_POST['id'];
elseif(isset($_GET['product_id'])) $pid=(int)$_GET['product_id'];
if($pid<=0){ echo json_encode(array('status'=>'error','message'=>'no_product')); exit; }
$q=mysqli_query($conn,"SELECT id FROM products WHERE id=$pid AND status=1 LIMIT 1");
if(!$q || mysqli_num_rows($q)==0){ echo json_encode(array('status'=>'error','message'=>'not_found')); exit; }
if(!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) $_SESSION['cart']=array();
$key=(string)$pid;
if(!isset($_SESSION['cart'][$key])) $_SESSION['cart'][$key]=0;
$_SESSION['cart'][$key]++;
$count=cart_count();
session_write_close();
echo json_encode(array('status'=>'ok','count'=>$count,'cart'=>$_SESSION['cart']));
?>
