<?php
/**
 * Controller Widget - Widget chat intégrable
 * mySupport - Plateforme de Service Client Intelligent
 */

namespace App\Controllers;

use Core\Controller;
use App\Models\Entreprise;

require_once APP_PATH . '/Models/Entreprise.php';

class WidgetController extends Controller
{
    private Entreprise $entrepriseModel;

    public function __construct()
    {
        parent::__construct();
        $this->entrepriseModel = new Entreprise();
    }

    public function index(string $token): void
    {
        $entreprise = $this->entrepriseModel->findByToken($token);
        
        if (!$entreprise || !$entreprise['is_active']) {
            echo "Widget non disponible";
            return;
        }

        $config = json_decode($entreprise['widget_config'] ?? '{}', true);
        $langues = json_decode($entreprise['langues_actives'] ?? '["fr"]', true);
        
        $this->view('widget/chat', [
            'entreprise' => $entreprise,
            'config' => $config,
            'langues' => $langues,
            'token' => $token
        ]);
    }
    
    public function embedScript(): void
    {
        header('Content-Type: application/javascript');
        header('Access-Control-Allow-Origin: *');
        header('Cache-Control: public, max-age=3600');
        readfile(ROOT_PATH . '/public/widget/embed.js');
        exit;
    }
    
    public function chatByApiKey(): void
    {
        $apiKey = $_GET['api_key'] ?? '';
        
        if (empty($apiKey)) {
            echo "Widget non disponible - Clé API manquante";
            return;
        }
        
        $entreprise = $this->entrepriseModel->findByApiKey($apiKey);
        
        if (!$entreprise || !$entreprise['is_active']) {
            echo "Widget non disponible - Clé API invalide";
            return;
        }

        $config = json_decode($entreprise['widget_config'] ?? '{}', true);
        $langues = json_decode($entreprise['langues_actives'] ?? '["fr"]', true);
        
        $this->view('widget/chat', [
            'entreprise' => $entreprise,
            'config' => $config,
            'langues' => $langues,
            'token' => $entreprise['widget_token']
        ]);
    }
}
