<?php
declare(strict_types=1);

namespace App\Modules\Pricing\Models;

use App\Core\Model;

class RegulatoryDiscount extends Model
{
    protected string $table = 'regulatory_discounts';
    protected array $fillable = [
        'article_number', 'name_ar', 'name_en', 'description',
        'discount_percentage', 'max_discount_percentage',
        'eligibility_type', 'source_branch_id', 'target_branch_id',
        'min_service_years', 'allows_installment', 'installment_max_years',
        'installment_interest_rate', 'applies_to', 'is_active',
        'effective_from', 'effective_to', 'board_decision_number',
        'board_decision_date', 'notes', 'created_by', 'updated_by',
    ];

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $query = static::query();
        if (!empty($filters['search'])) {
            $query->where('name_ar', 'LIKE', '%' . $filters['search'] . '%');
        }
        if ($filters['is_active'] !== '') {
            $query->where('is_active', '=', (int) $filters['is_active']);
        }
        if (!empty($filters['eligibility_type'])) {
            $query->where('eligibility_type', '=', $filters['eligibility_type']);
        }
        return $query->orderBy('article_number', 'ASC')->paginate($perPage, $page);
    }

    public static function getActiveByType(string $eligibilityType, ?int $targetBranchId = null): array
    {
        $db = \App\Core\App::getInstance()->db();
        $sql = "SELECT * FROM regulatory_discounts WHERE eligibility_type = ? AND is_active = 1 AND (effective_from IS NULL OR effective_from <= CURDATE()) AND (effective_to IS NULL OR effective_to >= CURDATE())";
        $params = [$eligibilityType];

        if ($targetBranchId !== null) {
            $sql .= " AND (target_branch_id = ? OR target_branch_id IS NULL)";
            $params[] = $targetBranchId;
        }

        return $db->select($sql, $params);
    }
}
