<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Models;

use App\Core\Model;
use App\Core\App;
use App\Core\Pagination;

class Supplier extends Model
{
    protected static string $table = 'suppliers';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'code',
        'name_ar',
        'name_en',
        'contact_person',
        'phone',
        'email',
        'address_ar',
        'tax_number',
        'payment_terms',
        'rating',
        'is_active',
        'notes',
    ];

    /**
     * Get all active suppliers ordered by name_ar.
     */
    public static function allActive(): array
    {
        return static::query()
            ->where('is_active', '=', 1)
            ->orderBy('name_ar', 'ASC')
            ->get();
    }

    /**
     * Search suppliers with filters and pagination.
     */
    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = '1=1';
        $params = [];

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $where .= ' AND (`name_ar` LIKE ? OR `code` LIKE ?)';
            $params[] = $search;
            $params[] = $search;
        }

        if (isset($filters['is_active']) && $filters['is_active'] !== '') {
            $where .= ' AND `is_active` = ?';
            $params[] = (int) $filters['is_active'];
        }

        $where .= ' AND `deleted_at` IS NULL';

        $countRow = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM `suppliers` WHERE {$where}",
            $params
        );
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT * FROM `suppliers` WHERE {$where} ORDER BY `name_ar` ASC LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        return ['data' => $rows, 'pagination' => Pagination::paginate($total, $perPage, $page)];
    }
}
