<?php

namespace App\Models;

use CodeIgniter\Model;

class Category extends Model
{
    /**
     * table name
     * @var string
     */
    protected $table = 'categories';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'active'];

    /**
     * Get active categories information
     * @return array
     */
    public function getActiveCategory()
    {
        return $this->where('active', 1)->findAll(); // Get active categories
    }

    /**
     * Get category data by id or all
     * @param mixed $id
     * @return array|object|null
     */
    public function getCategoryData($id = null)
    {
        if ($id) {
            return $this->find($id); // Find by id
        }
        return $this->findAll(); // Get all
    }

    /**
     * Insert new category
     * @param mixed $data
     * @return bool|int|string
     */
    public function create($data)
    {
        if ($data) {
            return $this->insert($data); // Insert data and return true/false based on success
        }
        return false;
    }

     /**
      * Update category data
      * @param mixed $data
      * @param mixed $id
      * @return bool
      */
    public function updateCategory($data, $id)
    {
        if ($data && $id) {
            return $this->update($id, $data); // Update data by id
        }
        return false;
    }
    

    /**
     * Delete category
     * @param mixed $id
     * @return bool|\CodeIgniter\Database\BaseResult
     */
    public function remove($id)
    {
        if ($id) {
            return $this->delete($id); // Delete by id
        }
        return false;
    }

    public function getOrCreateIdByName(string $name): int
    {
        $normalized = trim($name);

        $brand = $this
            ->where('name', $normalized)
            ->first();

        if ($brand) {
            return (int) $brand[$this->primaryKey];
        }

        $newData = [
            'name'   => $normalized,
            'active' => 1,
        ];

        $insertedId = $this->insert($newData);

        if (! $insertedId) {
            throw new \RuntimeException('Impossible de créer le brand « ' . $normalized . ' »');
        }

        return (int) $insertedId;
    }
public function getNameById(string $id)
{
    $result = $this->select('name')
        ->where('id', $id)
        ->first();

    return $result ? $result['name'] : '';
}

}