<?php
class AIController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $cid = Auth::user()['company_id'];
        $agents = $this->db->fetchAll("SELECT * FROM ai_agents WHERE company_id=? AND deleted_at IS NULL ORDER BY name", [$cid]);
        $conversations = $this->db->fetchAll("SELECT ac.*, aa.name as agent_name FROM ai_conversations ac LEFT JOIN ai_agents aa ON ac.agent_id=aa.id WHERE ac.company_id=? ORDER BY ac.created_at DESC LIMIT 20", [$cid]);
        require 'app/views/ai/index.php';
    }

    public function configure($id) {
        $cid = Auth::user()['company_id'];
        $agent = $this->db->fetch("SELECT * FROM ai_agents WHERE id=? AND company_id=?", [$id, $cid]);
        if (!$agent) { flash('error', 'Agent not found.'); redirect('?page=ai'); }
        $conversations = $this->db->fetchAll("SELECT * FROM ai_conversations WHERE agent_id=? AND company_id=? ORDER BY created_at DESC LIMIT 50", [$id, $cid]);
        require 'app/views/ai/configure.php';
    }

    public function update($id) {
        CSRF::verify(); $cid = Auth::user()['company_id'];
        $this->db->update('ai_agents', [
            'status' => $_POST['status'] ?? 'inactive',
            'instructions' => $_POST['instructions'] ?? null,
            'escalation_rules' => $_POST['escalation_rules'] ?? null,
        ], 'id = ? AND company_id = ?', [$id, $cid]);
        flash('success', 'Agent configuration updated.'); redirect('?page=ai&action=configure&id='.$id);
    }
}
