<?php
declare(strict_types=1);

namespace Controllers;
use Helpers\Auth; use Helpers\Request; use Helpers\Response; use Repositories\CartRepository;
final class CartController
{
    private function context(): array { $u=Auth::user(); $g=$_SERVER['HTTP_X_GUEST_SESSION'] ?? Request::input()['guest_session_id'] ?? bin2hex(random_bytes(16)); return [$u?(int)$u['id']:null, (string)$g]; }
    public function index(): never { [$uid,$g]=$this->context(); Response::success(['guest_session_id'=>$g,'items'=>(new CartRepository())->get($uid,$g)]); }
    public function add(): never { $d=Request::input(); [$uid,$g]=$this->context(); (new CartRepository())->add($uid,$g,(int)$d['product_id'], max(1,(int)($d['quantity']??1))); Response::success(['items'=>(new CartRepository())->get($uid,$g)], 'Cart updated'); }
    public function update(): never { $d=Request::input(); [$uid,$g]=$this->context(); (new CartRepository())->update($uid,$g,(int)$d['product_id'], (int)$d['quantity']); Response::success(['items'=>(new CartRepository())->get($uid,$g)], 'Cart updated'); }
    public function remove(): never { $d=Request::input(); [$uid,$g]=$this->context(); (new CartRepository())->remove($uid,$g,(int)$d['product_id']); Response::success(['items'=>(new CartRepository())->get($uid,$g)], 'Removed'); }
}
