<?php

require_once BASE_PATH
    . '/config/database.php';


class Cart
{
    private PDO $db;


    public function __construct()
    {
        $database =
            new Database();

        $this->db =
            $database->connect();
    }


    /**
     * Tìm giỏ của Customer.
     */
    public function findByCustomerId(
        int $customerId
    ): ?array {

        $sql = "
            SELECT *
            FROM carts
            WHERE customer_id = :customer_id
            LIMIT 1
        ";

        $stmt =
            $this->db->prepare($sql);

        $stmt->execute([
            'customer_id' =>
                $customerId
        ]);

        $cart =
            $stmt->fetch();

        return $cart ?: null;
    }


    /**
     * Lấy hoặc tự tạo giỏ hàng.
     */
    public function getOrCreate(
        int $customerId
    ): int {
        $sql = "
            INSERT INTO carts (
                customer_id
            )
            VALUES (
                :customer_id
            )
            ON DUPLICATE KEY UPDATE
                id = LAST_INSERT_ID(id)
        ";

        $stmt =
            $this->db->prepare($sql);

        $stmt->execute([
            'customer_id' =>
                $customerId
        ]);


        return (int)
            $this->db->lastInsertId();
    }


    /**
     * Xóa toàn bộ sản phẩm trong giỏ.
     */
    public function clear(
        int $cartId
    ): void {

        $sql = "
            DELETE FROM cart_items
            WHERE cart_id = :cart_id
        ";

        $stmt =
            $this->db->prepare($sql);

        $stmt->execute([
            'cart_id' => $cartId
        ]);
    }
}
