<?php
declare(strict_types=1);

namespace App\Modules\Rules\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Rules\Models\BusinessRule;
use App\Modules\Rules\Models\RuleVersion;
use App\Modules\Rules\Services\RuleEngine;

class RuleController extends Controller
{
    public function index(Request $request): Response
    {
        $category = $request->get('category', '');
        $categories = BusinessRule::getCategories();

        $db = App::getInstance()->db();
        $where = 'is_active = 1';
        $params = [];
        if ($category !== '') {
            $where .= ' AND category = ?';
            $params[] = $category;
        }
        $rules = $db->select("SELECT * FROM business_rules WHERE {$where} ORDER BY category, rule_code", $params);

        return $this->view('Rules.Views.index', [
            'rules'      => $rules,
            'categories' => $categories,
            'category'   => $category,
        ]);
    }

    public function edit(Request $request, string $id): Response
    {
        $rule = BusinessRule::find((int) $id);
        if (!$rule) {
            return $this->redirect('/rules')->withError('القاعدة غير موجودة');
        }
        return $this->view('Rules.Views.edit', ['rule' => $rule]);
    }

    public function update(Request $request, string $id): Response
    {
        $rule = BusinessRule::find((int) $id);
        if (!$rule) {
            return $this->redirect('/rules')->withError('القاعدة غير موجودة');
        }

        $newValueJson = trim((string) $request->post('current_value_json', ''));
        $reason = trim((string) $request->post('change_reason', ''));

        if ($newValueJson === '' || $reason === '') {
            return $this->redirect("/rules/{$id}/edit")->withError('يرجى ملء جميع الحقول المطلوبة');
        }

        $decoded = json_decode($newValueJson, true);
        if ($decoded === null && $newValueJson !== 'null') {
            return $this->redirect("/rules/{$id}/edit")->withError('قيمة JSON غير صالحة');
        }

        try {
            RuleEngine::update($rule->rule_code, $newValueJson, $reason, $rule->branch_id ? (int) $rule->branch_id : null);
            return $this->redirect('/rules')->withSuccess('تم تحديث القاعدة بنجاح');
        } catch (\Throwable $e) {
            return $this->redirect("/rules/{$id}/edit")->withError('فشل تحديث القاعدة: ' . $e->getMessage());
        }
    }

    public function history(Request $request, string $id): Response
    {
        $rule = BusinessRule::find((int) $id);
        if (!$rule) {
            return $this->redirect('/rules')->withError('القاعدة غير موجودة');
        }
        $versions = RuleVersion::getForRule((int) $id);
        return $this->view('Rules.Views.history', ['rule' => $rule, 'versions' => $versions]);
    }

    public function simulate(Request $request, string $id): Response
    {
        $rule = BusinessRule::find((int) $id);
        if (!$rule) {
            return $this->redirect('/rules')->withError('القاعدة غير موجودة');
        }
        return $this->view('Rules.Views.simulate', ['rule' => $rule]);
    }
}