<?php

namespace App\Controllers;

use App\Models\AiAlertModel;

/**
 * Manager-facing list over ai_alerts (see App\Commands\FlagAnomalies) —
 * flags only, read-only aside from dismiss(), which just acknowledges a
 * flag (never touches a booking/rate/anything else it flagged).
 */
class AiAlertController extends BaseController
{
    public function index()
    {
        $model = new AiAlertModel();

        $tab = $this->request->getGet('tab') ?: 'open';

        $alerts = $tab === 'dismissed'
            ? $model->where('dismissed_at IS NOT NULL', null, false)->orderBy('dismissed_at', 'desc')->findAll()
            : $model->where('dismissed_at', null)->orderBy('created_at', 'desc')->findAll();

        return view('ai_alerts/index', [
            'pageTitle' => 'AI Alerts',
            'alerts'    => $alerts,
            'tab'       => $tab,
            'openCount' => (new AiAlertModel())->countOpen(),
        ]);
    }

    public function dismiss(int $id)
    {
        $model = new AiAlertModel();
        $alert = $model->find($id);

        if ($alert === null) {
            return redirect()->to('ai/alerts')->with('error', 'Alert not found.');
        }

        $model->dismiss($id, $this->currentUserId());
        $this->logActivity('reports', 'Dismissed AI alert "' . $alert->title . '".');

        return redirect()->to('ai/alerts')->with('success', 'Alert dismissed.');
    }
}
