<?php
declare(strict_types=1);

namespace App\Modules\Rules\Models;

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

class BusinessRule extends Model
{
    protected static string $table = 'business_rules';
    protected static bool $softDelete = false;
    protected static bool $timestamps = true;
    protected static array $fillable = [
        'rule_code', 'category', 'name_ar', 'name_en', 'description_ar', 'description_en',
        'parameters_json', 'current_value_json', 'data_type', 'branch_id',
        'effective_from', 'effective_to', 'is_active', 'version',
    ];

    public function getValue(): array
    {
        return json_decode($this->current_value_json ?? '{}', true) ?? [];
    }

    public function getParameters(): array
    {
        return json_decode($this->parameters_json ?? '{}', true) ?? [];
    }

    public static function allByCategory(string $category, ?int $branchId = null): array
    {
        $db = App::getInstance()->db();
        if ($branchId) {
            return $db->select(
                "SELECT * FROM business_rules WHERE category = ? AND (branch_id IS NULL OR branch_id = ?) AND is_active = 1 ORDER BY rule_code",
                [$category, $branchId]
            );
        }
        return $db->select(
            "SELECT * FROM business_rules WHERE category = ? AND is_active = 1 ORDER BY rule_code",
            [$category]
        );
    }

    public static function getCategories(): array
    {
        $db = App::getInstance()->db();
        $rows = $db->select("SELECT DISTINCT category FROM business_rules WHERE is_active = 1 ORDER BY category");
        return array_column($rows, 'category');
    }
}