<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Cart; use App\Core\Response;
if($_SERVER['REQUEST_METHOD']!=='POST'||!verify_csrf())Response::json(['ok'=>false,'message'=>'Invalid request.'],419);
$data=request_data(); $action=(string)($data['action']??'summary');
try{
 if($action==='add')$summary=Cart::add((int)($data['product_id']??0),max(1,(int)($data['qty']??1)),!empty($data['variant_id'])?(int)$data['variant_id']:null);
 elseif($action==='update')$summary=Cart::update((string)($data['key']??$data['product_id']??''),(int)($data['qty']??1));
 elseif($action==='remove')$summary=Cart::remove((string)($data['key']??$data['product_id']??''));
 else $summary=Cart::summary();
 Response::json(['ok'=>true,'message'=>$action==='add'?'Added to cart.':'Cart updated.','summary'=>['count'=>$summary['count'],'subtotal'=>$summary['subtotal']]]);
}catch(Throwable $e){Response::json(['ok'=>false,'message'=>$e->getMessage()],422);}
