<?php

namespace Core\App\Models;

use PDO;

class ProductCategoryModel
{
    protected PDO $db;

    public function __construct()
    {
        $this->db = \db();
    }

    /* =========================================
     * Get category IDs by product
     * ========================================= */
    public function getCategoryIdsByProduct(int $productId): array
    {
        $stmt = $this->db->prepare("
            SELECT category_id
            FROM product_categories
            WHERE product_id = ?
        ");
        $stmt->execute([$productId]);

        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }

    /* =========================================
     * Sync product categories
     * ========================================= */
    public function sync(int $productId, array $categoryIds): void
    {
        $this->db->prepare("
            DELETE FROM product_categories
            WHERE product_id = ?
        ")->execute([$productId]);

        if (empty($categoryIds)) {
            return;
        }

        $stmt = $this->db->prepare("
            INSERT INTO product_categories (product_id, category_id)
            VALUES (?, ?)
        ");

        foreach ($categoryIds as $categoryId) {
            $stmt->execute([$productId, (int)$categoryId]);
        }
    }
}
