<?php
/**
 * Controller Auth - Authentification
 * mySupport - Plateforme de Service Client Intelligent
 */

namespace App\Controllers;

use Core\Controller;
use App\Models\User;

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

class AuthController extends Controller
{
    private User $userModel;

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

    public function loginForm(): void
    {
        if (isset($_SESSION['user_id']) && isset($_SESSION['user_role'])) {
            $role = $_SESSION['user_role'];
            if ($role === ROLE_SUPER_ADMIN || $role === ROLE_ADMIN_ENTREPRISE || $role === ROLE_AGENT) {
                $this->redirectByRole();
                return;
            }
        }
        
        $this->view('auth/login', [
            'csrf_token' => $this->generateCsrf(),
            'error' => $_SESSION['login_error'] ?? null
        ]);
        unset($_SESSION['login_error']);
    }

    public function login(): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/auth/login');
            return;
        }

        $email = $this->sanitize($this->input('email', ''));
        $password = $this->input('password', '');

        if (empty($email) || empty($password)) {
            $_SESSION['login_error'] = 'Veuillez remplir tous les champs.';
            $this->redirect('/auth/login');
            return;
        }

        $user = $this->userModel->authenticate($email, $password);

        if (!$user) {
            $_SESSION['login_error'] = 'Email ou mot de passe incorrect.';
            $this->redirect('/auth/login');
            return;
        }

        if (!$user['is_active']) {
            $_SESSION['login_error'] = 'Votre compte est désactivé.';
            $this->redirect('/auth/login');
            return;
        }

        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_email'] = $user['email'];
        $_SESSION['user_name'] = $user['prenom'] . ' ' . $user['nom'];
        $_SESSION['user_role'] = $user['role'];
        $_SESSION['entreprise_id'] = $user['entreprise_id'];

        $this->logActivity('login', 'Connexion réussie');
        $this->redirectByRole();
    }

    public function logout(): void
    {
        if (isset($_SESSION['user_id'])) {
            $this->userModel->setOffline($_SESSION['user_id']);
            $this->logActivity('logout', 'Déconnexion');
        }

        session_destroy();
        $this->redirect('/auth/login');
    }

    public function unauthorized(): void
    {
        $this->view('auth/unauthorized');
    }

    public function registerForm(): void
    {
        if (isset($_SESSION['user_id'])) {
            $this->redirectByRole();
            return;
        }
        
        $this->view('auth/register', [
            'csrf_token' => $this->generateCsrf(),
            'error' => $_SESSION['register_error'] ?? null,
            'success' => $_SESSION['register_success'] ?? null
        ]);
        unset($_SESSION['register_error'], $_SESSION['register_success']);
    }

    public function register(): void
    {
        if (!$this->isPost() || !$this->validateCsrf()) {
            $this->redirect('/auth/register');
            return;
        }

        $entreprise = $this->sanitize($this->input('entreprise', ''));
        $prenom = $this->sanitize($this->input('prenom', ''));
        $nom = $this->sanitize($this->input('nom', ''));
        $email = $this->sanitize($this->input('email', ''));
        $telephone = $this->sanitize($this->input('telephone', ''));
        $password = $this->input('password', '');
        $passwordConfirm = $this->input('password_confirm', '');

        // Validation
        if (empty($entreprise) || empty($prenom) || empty($nom) || empty($email) || empty($password)) {
            $_SESSION['register_error'] = 'Veuillez remplir tous les champs obligatoires.';
            $this->redirect('/auth/register');
            return;
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $_SESSION['register_error'] = 'Adresse email invalide.';
            $this->redirect('/auth/register');
            return;
        }

        if (strlen($password) < 8) {
            $_SESSION['register_error'] = 'Le mot de passe doit contenir au moins 8 caractères.';
            $this->redirect('/auth/register');
            return;
        }

        if ($password !== $passwordConfirm) {
            $_SESSION['register_error'] = 'Les mots de passe ne correspondent pas.';
            $this->redirect('/auth/register');
            return;
        }

        // Vérifier si l'email existe déjà
        $existingUser = $this->userModel->findByEmail($email);
        if ($existingUser) {
            $_SESSION['register_error'] = 'Cette adresse email est déjà utilisée.';
            $this->redirect('/auth/register');
            return;
        }

        // Créer l'entreprise
        require_once APP_PATH . '/Models/Entreprise.php';
        $entrepriseModel = new \App\Models\Entreprise();
        
        $entrepriseId = $entrepriseModel->create([
            'nom' => $entreprise,
            'slug' => $entrepriseModel->generateSlug($entreprise),
            'email' => $email,
            'telephone' => $telephone,
            'type_abonnement' => SUBSCRIPTION_BASIC,
            'is_active' => 1,
            'widget_token' => $entrepriseModel->generateToken(),
            'created_at' => date('Y-m-d H:i:s')
        ]);

        // Créer l'utilisateur admin de l'entreprise
        $userId = $this->userModel->create([
            'entreprise_id' => $entrepriseId,
            'email' => $email,
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'prenom' => $prenom,
            'nom' => $nom,
            'role' => ROLE_ADMIN_ENTREPRISE,
            'is_active' => 1,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        $_SESSION['register_success'] = 'Compte créé avec succès! Vous pouvez maintenant vous connecter.';
        $this->redirect('/auth/login');
    }

    private function redirectByRole(): void
    {
        $role = $_SESSION['user_role'] ?? null;
        
        switch ($role) {
            case ROLE_SUPER_ADMIN:
                $this->redirect('/super-admin');
                break;
            case ROLE_ADMIN_ENTREPRISE:
                $this->redirect('/admin');
                break;
            case ROLE_AGENT:
                $this->redirect('/agent');
                break;
            default:
                // Ne pas rediriger vers login pour éviter la boucle
                $this->redirect('/');
                break;
        }
    }

    private function logActivity(string $action, string $description): void
    {
        $this->db->insert('logs_activite', [
            'entreprise_id' => $_SESSION['entreprise_id'] ?? null,
            'user_id' => $_SESSION['user_id'] ?? null,
            'action' => $action,
            'description' => $description,
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null,
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
            'created_at' => date('Y-m-d H:i:s')
        ]);
    }
}
