<?php
namespace App\Controllers;

use App\Services\AIService;
use App\Services\LeadService;

class AIController {
    private $aiService;
    private $leadService;
    
    public function __construct() {
        global $pdo;
        $this->aiService = new AIService();
        $this->leadService = new LeadService($pdo);
    }
    
    public function index() {
        $leads = $this->leadService->getLeads();
        
        ob_start();
        include APP_ROOT . '/resources/views/pages/ai-tools.php';
        $content = ob_get_clean();
        
        $currentPage = 'ai-tools';
        $pageTitle = 'AI Tools';
        include APP_ROOT . '/resources/views/layouts/main.php';
    }
    
    public function analyze() {
        header('Content-Type: application/json');
        
        $leadId = $_POST['lead_id'] ?? null;
        $leads = $this->leadService->getLeads();
        
        $lead = current(array_filter($leads, function($l) use ($leadId) {
            return $l->id == $leadId;
        }));
        
        if ($lead) {
            $analysis = $this->aiService->analyzeLead($lead);
            echo json_encode($analysis);
        } else {
            echo json_encode(['error' => 'Lead not found']);
        }
    }
    
    public function generateResponse() {
        header('Content-Type: application/json');
        
        $leadId = $_POST['lead_id'] ?? null;
        $tone = $_POST['tone'] ?? 'professional';
        $leads = $this->leadService->getLeads();
        
        $lead = current(array_filter($leads, function($l) use ($leadId) {
            return $l->id == $leadId;
        }));
        
        if ($lead) {
            $response = $this->aiService->generateEmailResponse($lead, $tone);
            echo json_encode(['response' => $response]);
        } else {
            echo json_encode(['error' => 'Lead not found']);
        }
    }
}