<?php

class AIAutomationController extends Controller
{
    private AIAutomation $automation;
    private AIAutomationService $service;

    public function __construct(){ $this->automation=new AIAutomation(); $this->service=new AIAutomationService(); }

    private function guard(bool $adminOnly=false): void
    {
        Auth::requireLogin();
        if($adminOnly && !in_array(current_role(),['owner','admin'],true)){http_response_code(403);require app_path('Views/errors/403.php');exit;}
        if(!$adminOnly && !can('ai.use')){http_response_code(403);require app_path('Views/errors/403.php');exit;}
    }

    public function index(): void
    {
        $this->guard();
        $this->view('ai/automation',[
            'rules'=>$this->automation->rules(),
            'actions'=>$this->automation->actions('',120),
            'changes'=>$this->automation->recentChanges(80),
            'runs'=>$this->automation->recentRuns(30),
            'stats'=>$this->automation->stats(),
            'tab'=>trim((string)($_GET['tab']??'overview')),
        ]);
    }

    public function saveRule(): void
    {
        $this->guard(true);Csrf::verify();
        try{$id=$this->automation->saveRule($_POST,!empty($_POST['id'])?(int)$_POST['id']:null);log_activity('ai_automation_rule_saved','AI automation rule #'.$id.' saved.');$this->flash('success','Automation rule saved.');}
        catch(Throwable $e){$this->flash('danger',$e->getMessage());}
        $this->redirect('/ai/automation?tab=rules');
    }

    public function toggleRule(): void
    {
        $this->guard(true);Csrf::verify();$this->automation->toggleRule((int)($_POST['id']??0),!empty($_POST['enabled']));$this->flash('success','Automation rule updated.');$this->redirect('/ai/automation?tab=rules');
    }

    public function run(): void
    {
        $this->guard(true);Csrf::verify();
        try{$id=(int)($_POST['rule_id']??0);$result=$id?$this->service->runRuleById($id,'manual',(int)Auth::user()['id']):$this->service->runAll('manual',(int)Auth::user()['id']);$this->flash('success','AI automation run complete: '.($result['summary']??(($result['proposed']??0).' actions proposed; '.($result['executed']??0).' safe actions executed.')));}
        catch(Throwable $e){$this->flash('danger','Automation run failed: '.$e->getMessage());}
        $this->redirect('/ai/automation');
    }

    public function approveAction(): void
    {
        $this->guard(true);Csrf::verify();$id=(int)($_POST['id']??0);
        try{$this->automation->setActionStatus($id,'approved',(int)Auth::user()['id']);$this->service->executeAction($id,(int)Auth::user()['id']);$this->flash('success','AI action approved and completed. A change notification was recorded.');}
        catch(Throwable $e){$this->flash('danger',$e->getMessage());}
        $this->redirect('/ai/automation?tab=actions');
    }

    public function rejectAction(): void
    {
        $this->guard(true);Csrf::verify();$this->automation->setActionStatus((int)($_POST['id']??0),'rejected',(int)Auth::user()['id']);$this->flash('success','AI action rejected.');$this->redirect('/ai/automation?tab=actions');
    }
}
