<?php
declare(strict_types=1);
namespace Repositories;

final class CartRepository extends BaseRepository
{
    private function ownerWhere(?int $userId, string $guest): array
    {
        return $userId ? ['sql'=>'user_id=:user_id', 'params'=>['user_id'=>$userId]] : ['sql'=>'guest_session_id=:guest_session_id', 'params'=>['guest_session_id'=>$guest]];
    }
    public function get(?int $userId, string $guest): array
    {
        $w = $this->ownerWhere($userId, $guest);
        return $this->fetchAll('SELECT ci.*, p.name, p.slug, p.price, p.mrp, p.stock_quantity, (SELECT image_url FROM product_images WHERE product_id=p.id ORDER BY sort_order,id LIMIT 1) AS primary_image FROM cart_items ci JOIN products p ON p.id=ci.product_id WHERE '.$w['sql'].' ORDER BY ci.updated_at DESC', $w['params']);
    }
    public function add(?int $userId, string $guest, int $productId, int $qty): void
    {
        $w = $this->ownerWhere($userId, $guest);
        $existing = $this->fetchOne('SELECT * FROM cart_items WHERE product_id=:pid AND '.$w['sql'].' LIMIT 1', ['pid'=>$productId]+$w['params']);
        if ($existing) $this->execute('UPDATE cart_items SET quantity=LEAST(quantity+:qty, 99), updated_at=NOW() WHERE id=:id', ['qty'=>$qty,'id'=>$existing['id']]);
        else $this->execute('INSERT INTO cart_items(user_id,guest_session_id,product_id,quantity) VALUES(:uid,:guest,:pid,:qty)', ['uid'=>$userId,'guest'=>$userId?null:$guest,'pid'=>$productId,'qty'=>$qty]);
    }
    public function update(?int $userId, string $guest, int $productId, int $qty): void
    {
        $w = $this->ownerWhere($userId, $guest);
        if ($qty <= 0) { $this->remove($userId, $guest, $productId); return; }
        $this->execute('UPDATE cart_items SET quantity=:qty, updated_at=NOW() WHERE product_id=:pid AND '.$w['sql'], ['qty'=>$qty,'pid'=>$productId]+$w['params']);
    }
    public function remove(?int $userId, string $guest, int $productId): void
    {
        $w = $this->ownerWhere($userId, $guest);
        $this->execute('DELETE FROM cart_items WHERE product_id=:pid AND '.$w['sql'], ['pid'=>$productId]+$w['params']);
    }
    public function clearUser(int $userId): void { $this->execute('DELETE FROM cart_items WHERE user_id=:id', ['id'=>$userId]); }
    public function mergeGuestToUser(string $guest, int $userId): void
    {
        $items = $this->fetchAll('SELECT product_id, quantity FROM cart_items WHERE guest_session_id=:g', ['g'=>$guest]);
        foreach ($items as $item) $this->add($userId, '', (int)$item['product_id'], (int)$item['quantity']);
        $this->execute('DELETE FROM cart_items WHERE guest_session_id=:g', ['g'=>$guest]);
    }
}
