<?php
declare(strict_types=1);

namespace App\Modules\Sales\Models;

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

class Package extends Model
{
    protected static string $table = 'packages';
    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',
        'description_ar',
        'package_price_member',
        'package_price_nonmember',
        'items_total_price',
        'active_from',
        'active_to',
        'is_active',
        'notes',
    ];

    public static function allActive(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM `packages`
             WHERE `is_active` = 1
               AND (`active_from` IS NULL OR `active_from` <= CURDATE())
               AND (`active_to` IS NULL OR `active_to` >= CURDATE())
             ORDER BY `name_ar` ASC"
        );
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $query = static::query();

        if (!empty($filters['q'])) {
            $search = '%' . $filters['q'] . '%';
            $query = $query->whereRaw('(`name_ar` LIKE ? OR `code` LIKE ?)', [$search, $search]);
        }

        if (isset($filters['is_active']) && $filters['is_active'] !== '') {
            $query = $query->where('is_active', '=', (int) $filters['is_active']);
        }

        $query = $query->orderBy('name_ar', 'ASC');

        return $query->paginate($perPage, $page);
    }
}
