<?php

namespace App\Models;

use CodeIgniter\Model;

class Brands extends Model
{
    /**
     * table name
     * @var string
     */
    protected $table = 'brands';
    protected $primaryKey = 'id'; // Primary key column
    protected $allowedFields = ['name', 'active'];

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

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

    /**
     * Insert new brand
     * @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 brand data
     * @param mixed $data
     * @param mixed $id
     * @return bool
     */
    public function updateBrand($data, $id)
    {
        if ($data && $id) {
            return $this->update($id, $data); // Update data by id
        }
        return false;
    }

    /**
     * Delete brand
     * @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 getName()
    {
        return $this->db->table('brands')->select('name')->where('active', 1)->get()->getResult();
    }

    public function getNameById(int $id)
    {
        return $this->select('name')->where('active', 1)
        ->where('id', $id)->first();
    }

    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;
    }
}
