<?php
declare(strict_types=1);

namespace App\Modules\Alerts\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Alerts\Models\AlertRule;
use App\Modules\Alerts\Models\AlertLog;

class AlertController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('alert.view');

        $rules = AlertRule::query()
            ->orderBy('category', 'ASC')
            ->orderBy('name_ar', 'ASC')
            ->get();

        $categories = AlertRule::getCategories();
        $triggerTypes = AlertRule::getTriggerTypes();

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

    public function log(Request $request): Response
    {
        $this->authorize('alert.view');

        $db = App::getInstance()->db();
        $logs = $db->select(
            "SELECT al.*, ar.name_ar AS rule_name, ar.category
             FROM alert_log al
             LEFT JOIN alert_rules ar ON ar.id = al.alert_rule_id
             ORDER BY al.triggered_at DESC
             LIMIT 100"
        );

        return $this->view('Alerts.Views.log', [
            'logs'       => $logs,
            'categories' => AlertRule::getCategories(),
        ]);
    }

    public function toggle(Request $request, int $id): Response
    {
        $this->authorize('alert.manage');

        $rule = AlertRule::find($id);
        if (!$rule) {
            return $this->redirect('/alerts')->withError('القاعدة غير موجودة');
        }

        $db = App::getInstance()->db();
        $newStatus = ((int) $rule->is_active === 1) ? 0 : 1;
        $db->update('alert_rules', ['is_active' => $newStatus], 'id = ?', [$id]);

        $msg = $newStatus === 1 ? 'تم تفعيل التنبيه' : 'تم إيقاف التنبيه';
        return $this->redirect('/alerts')->withSuccess($msg);
    }

    public function acknowledge(Request $request, int $id): Response
    {
        $this->authorize('alert.view');

        $db = App::getInstance()->db();
        $log = $db->selectOne("SELECT * FROM alert_log WHERE id = ?", [$id]);
        if (!$log) {
            return $this->redirect('/alerts/log')->withError('السجل غير موجود');
        }

        $session = App::getInstance()->session();
        $db->update('alert_log', [
            'status'          => 'acknowledged',
            'acknowledged_by' => $session->get('employee_id'),
            'acknowledged_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [$id]);

        return $this->redirect('/alerts/log')->withSuccess('تم تأكيد الإطلاع على التنبيه');
    }
}
