<?php

namespace App\Repositories;

use App\Config\Database;

class CategoryRepository extends BaseRepository
{

    /**
     * Get all allowed fields
     * 
     * @return array
     */
    protected function getAllowedFields(): array
    {
        return [
            'id_category'               => 'id_category',
            'name_category'             => 'name_category',
            'level_category'            => 'level_category',
            'reference_father_category' => 'reference_father_category',
            'reference_category'        => 'reference_category',
            'is_active'                 => 'is_active',
            'created_at'                => 'created_at',
            'updated_at'                => 'updated_at'
        ];
    }

    /**
     * Get all categories by params
     * 
     * @throws Exception
     * 
     * @return array
     * 
     * @param array $params
     */
    public function getAllCategories(array $params): array
    {
        return $this->getAllFromTable('categories', $params);
    }

    /**
     * Get category by id
     * 
     * @throws Exception
     * 
     * @return array|null
     */
    public function getById(int $id): ?array
    {
        $sql = "
            SELECT 
                id_category,
                name_category,
                level_category,
                reference_father_category,
                reference_category,
                is_active
            FROM categories
            WHERE id_category = ?
            LIMIT 1
        ";

        $conn = Database::connection();

        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $id);
        $stmt->execute();

        $result = $stmt->get_result()->fetch_assoc();

        return $result ?: null;
    }
}
