<?php



class UtilisateursController {



    public function showLoginForm() {
      require '/home/dykqnvjf/public_html/bewise/app/views/LoginView.php';
    }


    public function authenticate() {
      @session_start();
      $email = $_POST['email'];
      $mdp = $_POST['password'];

      require_once '/home/dykqnvjf/public_html/bewise/app/models/UtilisateursModel.php';
      require_once '/home/dykqnvjf/public_html/bewise/app/models/SessionsModel.php';

      $userModel = new UtilisateursModel();
      $sessionModel = new SessionsModel();

      $user = $userModel->verifyCredentials($email, $mdp);

      if ($user && $user['statut'] === 'actif') {
        $_SESSION['user'] = $user;
        $userModel->updateConnexionStats($user['id_utilisateur']);

        $ip = $_SERVER['REMOTE_ADDR'];
        $navigateur = $_SERVER['HTTP_USER_AGENT'];
        $localisation = 'Douala, Cameroun';
        $type_appareil = 'Desktop/Tablette/Mobile';

        $_SESSION['id_session'] = $sessionModel->create($user['id_utilisateur'], $ip, $navigateur, $localisation, $type_appareil);
        header('Location: ../index.php/dashboard');
      } else {
        $_SESSION['error'] = "Identifiants incorrects ou compte inactif.";
        header('Location: ../index.php/login');
      }
    }


    public function showRegisterForm() {
      require '/home/dykqnvjf/public_html/bewise/app/views/RegisterView.php';
    }


    public function storeUser() {
        require_once '/home/dykqnvjf/public_html/bewise/app/models/UtilisateursModel.php';
        $model = new UtilisateursModel();
        
        // Vérification si l'email existe déjà
        $email = $_POST['email'] ?? '';
        if ($model->emailExists($email)) {
            // Gérer l'erreur (redirection avec message ou affichage dans la vue)
            $_SESSION['error'] = "Ce numéro de téléphone est déjà utilisé. Veuillez en choisir un autre.";
            header('Location: ../index.php/register');
            exit();
        }
    
        // Validation supplémentaire des données
        $requiredFields = ['nom', 'prenom', 'email', 'password'];
        foreach ($requiredFields as $field) {
            if (empty($_POST[$field])) {
                $_SESSION['error'] = "Le champ $field est obligatoire.";
                header('Location: ../index.php/register');
                exit();
            }
        }
    
        // Hashage du mot de passe
        $_POST['password'] = password_hash($_POST['password'], PASSWORD_BCRYPT);
    
        // Insertion sécurisée
        try {
            $model->insert($_POST);
            $_SESSION['success'] = "Inscription réussie ! Vous pouvez maintenant vous connecter.";
            header('Location: ../index.php/login');
            exit();
        } catch (Exception $e) {
            error_log("Erreur d'inscription: " . $e->getMessage());
            $_SESSION['error'] = "Une erreur s'est produite lors de l'inscription.";
            header('Location: ../index.php/register');
            exit();
        }
    }



      public function logout() {
      @session_start();
      require_once '/home/dykqnvjf/public_html/bewise/app/models/SessionsModel.php';
      $sessionModel = new SessionsModel();

      if (isset($_SESSION['id_session'])) {
        $sessionModel->close($_SESSION['id_session']);
      }

      session_destroy();
      header('Location: ../index.php/login');
    }


    public function showUpdateProfil() {
      @session_start();
      if (!isset($_SESSION['user'])) {
        header('Location: ../index.php/login');
        exit;
      }

      $user = $_SESSION['user'];
      require_once '/home/dykqnvjf/public_html/bewise/app/views/Update_profilView.php';
    }


    public function showProfil() {
      @session_start();
      if (!isset($_SESSION['user'])) {
        header('Location: ../index.php/login');
        exit;
      }

      $user = $_SESSION['user'];
      require '/home/dykqnvjf/public_html/bewise/app/views/ProfilView.php';
    }


    public function updateProfil($id) {
      if (session_status() === PHP_SESSION_NONE) session_start();
      if (!isset($_SESSION['user']) || $_SESSION['user']['id_utilisateur'] != $id) {
        header('Location: ../index.php/login');
        exit;
      }

      if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        require_once '/home/dykqnvjf/public_html/bewise/app/models/UtilisateursModel.php';
        $model = new UtilisateursModel();

        $data = [
          'id_utilisateur' => $id,
          'nom' => $_POST['nom'],
          'prenom' => $_POST['prenom'],
          'email' => $_POST['email'],
          'genre' => $_POST['genre'],
          'date_naissance' => $_POST['date_naissance'],
          'niveau_education' => $_POST['niveau_education'],
          'profession' => $_POST['profession'],
          'type_utilisateur' => $_POST['type_utilisateur'],
          'motivation_financiere' => $_POST['motivation_financiere'],
          'profil_risque' => $_POST['profil_risque']
        ];

        $model->updateProfil($data);

        // Mettre à jour la session
        $_SESSION['user'] = array_merge($_SESSION['user'], $data);

        // Redirection
        header('Location: ../profil');
      } else {
        require_once '/home/dykqnvjf/public_html/bewise/app/views/Update_profilView.php';
      }
    }


    public function showDashboard() {
      @session_start();
      if (!isset($_SESSION['user'])) {
        header('Location: ../index.php/login');
        exit;
      }

      require '/home/dykqnvjf/public_html/bewise/app/views/DashboardView.php';
    } 

}


?>