<?php
/**
 * Controller Super Admin
 * mySupport - Plateforme de Service Client Intelligent
 */

namespace App\Controllers;

use Core\Controller;
use App\Models\Entreprise;
use App\Models\User;
use App\Models\Conversation;
use App\Models\Alerte;

require_once APP_PATH . '/Models/Entreprise.php';
require_once APP_PATH . '/Models/User.php';
require_once APP_PATH . '/Models/Conversation.php';
require_once APP_PATH . '/Models/Alerte.php';

class SuperAdminController extends Controller
{
    private Entreprise $entrepriseModel;
    private User $userModel;
    private Conversation $conversationModel;
    private Alerte $alerteModel;

    public function __construct()
    {
        parent::__construct();
        $this->requireRole(ROLE_SUPER_ADMIN);
        
        $this->entrepriseModel = new Entreprise();
        $this->userModel = new User();
        $this->conversationModel = new Conversation();
        $this->alerteModel = new Alerte();
    }

    public function dashboard(): void
    {
        $entreprises = $this->entrepriseModel->all();
        $statsEntreprises = $this->entrepriseModel->getStatistiques();
        $alertes = $this->alerteModel->getAllForSuperAdmin();
        
        $totalConversations = 0;
        $totalAgents = 0;
        
        foreach ($entreprises as $e) {
            $stats = $this->conversationModel->getStatistiques($e['id']);
            $totalConversations += $stats['total'] ?? 0;
            $totalAgents += $this->userModel->countAgents($e['id']);
        }
        
        $this->view('super-admin/dashboard', [
            'entreprises' => $entreprises,
            'stats' => $statsEntreprises,
            'totalConversations' => $totalConversations,
            'totalAgents' => $totalAgents,
            'alertes' => array_slice($alertes, 0, 10),
            'user' => $this->currentUser()
        ]);
    }

    public function entreprises(): void
    {
        $entreprises = $this->entrepriseModel->all('nom', 'ASC');
        
        foreach ($entreprises as &$e) {
            $e['nb_agents'] = $this->userModel->countAgents($e['id']);
            $stats = $this->conversationModel->getStatistiques($e['id']);
            $e['nb_conversations'] = $stats['total'] ?? 0;
        }
        
        $this->view('super-admin/entreprises/index', [
            'entreprises' => $entreprises,
            'user' => $this->currentUser()
        ]);
    }

    public function createEntreprise(): void
    {
        $this->view('super-admin/entreprises/create', [
            'csrf_token' => $this->generateCsrf(),
            'langues' => LANGUAGES,
            'canaux' => ['web' => 'Web Chat', 'whatsapp' => 'WhatsApp', 'voice' => 'Voix'],
            'abonnements' => ['basic' => 'Basic', 'pro' => 'Pro', 'enterprise' => 'Enterprise'],
            'user' => $this->currentUser()
        ]);
    }

    public function storeEntreprise(): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/super-admin/entreprises');
            return;
        }

        $data = [
            'nom' => $this->sanitize($this->input('nom')),
            'secteur' => $this->sanitize($this->input('secteur')),
            'pays' => $this->sanitize($this->input('pays', 'Mali')),
            'region' => $this->sanitize($this->input('region')),
            'email' => $this->sanitize($this->input('email')),
            'telephone' => $this->sanitize($this->input('telephone')),
            'adresse' => $this->sanitize($this->input('adresse')),
            'type_abonnement' => $this->input('type_abonnement', 'basic'),
            'max_agents' => (int) $this->input('max_agents', 5),
            'langues_actives' => json_encode($this->input('langues', ['fr'])),
            'canaux_actifs' => json_encode($this->input('canaux', ['web']))
        ];

        $entrepriseId = $this->entrepriseModel->createEntreprise($data);

        if ($entrepriseId && $this->input('admin_email')) {
            $this->userModel->createUser([
                'entreprise_id' => $entrepriseId,
                'email' => $this->sanitize($this->input('admin_email')),
                'password' => $this->input('admin_password', 'changeme123'),
                'nom' => $this->sanitize($this->input('admin_nom', 'Admin')),
                'prenom' => $this->sanitize($this->input('admin_prenom', '')),
                'role' => ROLE_ADMIN_ENTREPRISE
            ]);
        }

        $_SESSION['flash_success'] = 'Entreprise créée avec succès.';
        $this->redirect('/super-admin/entreprises');
    }

    public function editEntreprise(string $id): void
    {
        $entreprise = $this->entrepriseModel->find((int) $id);
        
        if (!$entreprise) {
            $this->redirect('/super-admin/entreprises');
            return;
        }

        $admins = $this->userModel->getByEntreprise((int) $id, ROLE_ADMIN_ENTREPRISE);
        
        $this->view('super-admin/entreprises/edit', [
            'entreprise' => $entreprise,
            'admins' => $admins,
            'csrf_token' => $this->generateCsrf(),
            'langues' => LANGUAGES,
            'canaux' => ['web' => 'Web Chat', 'whatsapp' => 'WhatsApp', 'voice' => 'Voix'],
            'abonnements' => ['basic' => 'Basic', 'pro' => 'Pro', 'enterprise' => 'Enterprise'],
            'user' => $this->currentUser()
        ]);
    }

    public function updateEntreprise(string $id): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/super-admin/entreprises/' . $id);
            return;
        }

        $data = [
            'nom' => $this->sanitize($this->input('nom')),
            'secteur' => $this->sanitize($this->input('secteur')),
            'pays' => $this->sanitize($this->input('pays')),
            'region' => $this->sanitize($this->input('region')),
            'email' => $this->sanitize($this->input('email')),
            'telephone' => $this->sanitize($this->input('telephone')),
            'adresse' => $this->sanitize($this->input('adresse')),
            'type_abonnement' => $this->input('type_abonnement'),
            'max_agents' => (int) $this->input('max_agents'),
            'langues_actives' => json_encode($this->input('langues', ['fr'])),
            'canaux_actifs' => json_encode($this->input('canaux', ['web']))
        ];

        $this->entrepriseModel->update((int) $id, $data);
        
        $_SESSION['flash_success'] = 'Entreprise mise à jour avec succès.';
        $this->redirect('/super-admin/entreprises/' . $id);
    }

    public function toggleEntreprise(string $id): void
    {
        if (!$this->isPost()) {
            $this->redirect('/super-admin/entreprises');
            return;
        }

        $this->entrepriseModel->toggleActive((int) $id);
        
        if ($this->isAjax()) {
            $this->json(['success' => true]);
        } else {
            $this->redirect('/super-admin/entreprises');
        }
    }

    public function statistiques(): void
    {
        $entreprises = $this->entrepriseModel->all();
        $stats = [];
        
        foreach ($entreprises as $e) {
            $convStats = $this->conversationModel->getStatistiques($e['id']);
            $stats[] = [
                'entreprise' => $e,
                'conversations' => $convStats
            ];
        }
        
        $this->view('super-admin/statistiques', [
            'stats' => $stats,
            'user' => $this->currentUser()
        ]);
    }

    public function langues(): void
    {
        $sql = "SELECT * FROM langues ORDER BY nom ASC";
        $langues = $this->db->fetchAll($sql);
        
        $this->view('super-admin/langues', [
            'langues' => $langues,
            'user' => $this->currentUser()
        ]);
    }

    public function abonnements(): void
    {
        $sql = "SELECT a.*, e.nom as entreprise_nom 
                FROM abonnements a 
                LEFT JOIN entreprises e ON a.entreprise_id = e.id 
                ORDER BY a.created_at DESC";
        $abonnements = $this->db->fetchAll($sql);
        
        $this->view('super-admin/abonnements', [
            'abonnements' => $abonnements,
            'user' => $this->currentUser()
        ]);
    }
}
