<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Auth; use App\Core\Database; use App\Core\Response;
Auth::requireLogin('public/login.php');
if($_SERVER['REQUEST_METHOD']!=='POST' || !verify_csrf()) Response::json(['ok'=>false,'message'=>'Invalid request.'],419);
$data=request_data(); $pid=(int)($data['product_id']??0); $action=(string)($data['action']??'toggle');
if($pid<1 || !Database::safeFetchOne('SELECT id FROM products WHERE id=? AND status="published" LIMIT 1',[$pid])) Response::json(['ok'=>false,'message'=>'Product not found.'],404);
$existing=Database::safeFetchOne('SELECT id FROM compares WHERE user_id=? AND product_id=? LIMIT 1',[Auth::id(),$pid]);
if($action==='remove' || ($action==='toggle' && $existing)){ Database::safeExecute('DELETE FROM compares WHERE user_id=? AND product_id=?',[Auth::id(),$pid]); $added=false; }
else { if(!$existing){ if(db_count('compares','user_id=?',[Auth::id()])>=4) Response::json(['ok'=>false,'message'=>'You can compare up to 4 products.'],422); Database::safeExecute('INSERT INTO compares (user_id,product_id,created_at) VALUES (?,?,NOW())',[Auth::id(),$pid]); } $added=true; }
$count=db_count('compares','user_id=?',[Auth::id()]); Response::json(['ok'=>true,'added'=>$added,'count'=>$count,'message'=>$added?'Added to compare.':'Removed from compare.']);
