<?php

namespace App\Models;

use CodeIgniter\Model;

class ProductModel extends Model
{
    protected $table         = 'products';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'name', 'sku', 'barcode', 'category_id', 'brand_id', 'unit_id',
        'description', 'cost_price', 'sale_price', 'reorder_level',
        'status', 'notes', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'name'   => 'required|min_length[2]|max_length[200]',
        'sku'    => 'required|max_length[50]',
        'status' => 'permit_empty|in_list[active,inactive]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $categoryId = null, ?int $brandId = null): self
    {
        $this->select('products.*, product_categories.name AS category_name, product_brands.name AS brand_name, units_of_measure.code AS unit_code')
            ->join('product_categories', 'product_categories.id = products.category_id', 'left')
            ->join('product_brands', 'product_brands.id = products.brand_id', 'left')
            ->join('units_of_measure', 'units_of_measure.id = products.unit_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('products.name', $search)
                ->orLike('products.sku', $search)
                ->orLike('products.barcode', $search)
                ->groupEnd();
        }

        if ($status) {
            $this->where('products.status', $status);
        }

        if ($categoryId) {
            $this->where('products.category_id', $categoryId);
        }

        if ($brandId) {
            $this->where('products.brand_id', $brandId);
        }

        return $this;
    }

    public function getActive(): array
    {
        return $this->where('status', 'active')->orderBy('name', 'ASC')->findAll();
    }

    public function isSkuTaken(string $sku, ?int $excludeId = null): bool
    {
        $builder = $this->where('sku', strtoupper($sku));
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

        return $builder->countAllResults() > 0;
    }

    public function findWithRelations(int $id): ?array
    {
        return $this->select('products.*, product_categories.name AS category_name, product_brands.name AS brand_name, units_of_measure.name AS unit_name, units_of_measure.code AS unit_code')
            ->join('product_categories', 'product_categories.id = products.category_id', 'left')
            ->join('product_brands', 'product_brands.id = products.brand_id', 'left')
            ->join('units_of_measure', 'units_of_measure.id = products.unit_id', 'left')
            ->where('products.id', $id)
            ->first();
    }
}
