<?php
declare(strict_types=1);

namespace App\Modules\Rules\Models;

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

class RuleOverride extends Model
{
    protected static string $table = 'rule_overrides';
    protected static bool $softDelete = false;
    protected static bool $timestamps = false;
    protected static array $fillable = [
        'rule_id', 'entity_type', 'entity_id', 'override_value_json',
        'reason', 'approved_by', 'effective_from', 'effective_to', 'is_active',
    ];

    public static function getForEntity(string $entityType, int $entityId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT ro.*, br.rule_code, br.name_ar FROM rule_overrides ro JOIN business_rules br ON br.id = ro.rule_id WHERE ro.entity_type = ? AND ro.entity_id = ? AND ro.is_active = 1 AND (ro.effective_to IS NULL OR ro.effective_to >= CURDATE()) ORDER BY ro.created_at DESC",
            [$entityType, $entityId]
        );
    }

    public static function findOverride(int $ruleId, string $entityType, int $entityId): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM rule_overrides WHERE rule_id = ? AND entity_type = ? AND entity_id = ? AND is_active = 1 AND effective_from <= CURDATE() AND (effective_to IS NULL OR effective_to >= CURDATE())",
            [$ruleId, $entityType, $entityId]
        );
    }
}