<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Auth_lib - Bibliothèque d'authentification FerryOps
 * 
 * Gère la connexion, les sessions, les permissions et la journalisation.
 */
class Auth_lib
{
    protected $CI;

    public function __construct()
    {
        $this->CI =& get_instance();
        $this->CI->load->model('User_model');
        $this->CI->load->library('session');
    }

    // -------------------------------------------------------
    // AUTHENTIFICATION
    // -------------------------------------------------------

    /**
     * Tenter une connexion
     * @param string $identity  username ou email
     * @param string $password  mot de passe en clair
     * @return array ['success' => bool, 'message' => string, 'user' => object|null]
     */
    public function login($identity, $password)
    {
        $user = $this->CI->User_model->find_by_identity($identity);

        if ( ! $user) {
            return ['success' => false, 'message' => 'Identifiants incorrects.', 'user' => null];
        }

        if ($user->status !== 'active') {
            return ['success' => false, 'message' => 'Ce compte est ' . $user->status . '.', 'user' => null];
        }

        if ( ! password_verify($password, $user->password_hash)) {
            $this->log_action($user->id ?? 0, 'login_failed', 'auth', null, 'Tentative échouée pour: ' . $identity);
            return ['success' => false, 'message' => 'Identifiants incorrects.', 'user' => null];
        }

        // Connexion réussie
        $this->_set_session($user);
        $this->CI->User_model->update_last_login($user->id, $this->CI->input->ip_address());
        $this->log_action($user->id, 'login', 'auth');

        return ['success' => true, 'message' => 'Connexion réussie.', 'user' => $user];
    }

    /**
     * Déconnecter l'utilisateur
     */
    public function logout()
    {
        $user_id = $this->user_id();
        if ($user_id) {
            $this->log_action($user_id, 'logout', 'auth');
        }
        $this->CI->session->sess_destroy();
    }

    /**
     * L'utilisateur est-il connecté ?
     */
    public function is_logged_in()
    {
        return (bool) $this->CI->session->userdata('user_id');
    }

    // -------------------------------------------------------
    // SESSION
    // -------------------------------------------------------

    public function user_id()
    {
        return $this->CI->session->userdata('user_id');
    }

    public function username()
    {
        return $this->CI->session->userdata('username');
    }

    public function full_name()
    {
        return $this->CI->session->userdata('full_name');
    }

    public function role_code()
    {
        return $this->CI->session->userdata('role_code');
    }

    public function location_id()
    {
        return $this->CI->session->userdata('location_id');
    }

    /**
     * Récupérer toutes les données de session utilisateur
     */
    public function user_data()
    {
        return [
            'user_id'     => $this->user_id(),
            'username'    => $this->username(),
            'full_name'   => $this->full_name(),
            'role_code'   => $this->role_code(),
            'location_id' => $this->location_id(),
        ];
    }

    // -------------------------------------------------------
    // PERMISSIONS
    // -------------------------------------------------------

    /**
     * Vérifier si l'utilisateur a une permission spécifique
     * @param string $permission_code
     * @return bool
     */
    public function has_permission($permission_code)
    {
        $permissions = $this->CI->session->userdata('permissions');
        if ( ! is_array($permissions)) {
            return false;
        }
        return in_array($permission_code, $permissions);
    }

    /**
     * Vérifier une permission et rediriger si refusée
     */
    public function require_permission($permission_code)
    {
        if ( ! $this->has_permission($permission_code)) {
            $this->CI->session->set_flashdata('error', 'Accès refusé : vous n\'avez pas la permission requise.');
            redirect('dashboard');
        }
    }

    /**
     * Exiger la connexion (sinon redirection vers login)
     */
    public function require_login()
    {
        if ( ! $this->is_logged_in()) {
            $this->CI->session->set_flashdata('error', 'Veuillez vous connecter.');
            redirect('auth/login');
        }
    }

    /**
     * Vérifier si l'utilisateur est admin
     */
    public function is_admin()
    {
        return $this->role_code() === 'admin';
    }

    /**
     * Vérifier si l'utilisateur est Operation Manager ou Admin
     */
    public function is_manager_or_admin()
    {
        return in_array($this->role_code(), ['admin', 'op_manager']);
    }

    // -------------------------------------------------------
    // MOTS DE PASSE
    // -------------------------------------------------------

    /**
     * Hasher un mot de passe
     */
    public function hash_password($password)
    {
        return password_hash($password, PASSWORD_BCRYPT);
    }

    /**
     * Changer le mot de passe d'un utilisateur
     */
    public function change_password($user_id, $current_password, $new_password)
    {
        $user = $this->CI->User_model->get($user_id);
        if ( ! $user) {
            return ['success' => false, 'message' => 'Utilisateur introuvable.'];
        }

        if ( ! password_verify($current_password, $user->password_hash)) {
            return ['success' => false, 'message' => 'Mot de passe actuel incorrect.'];
        }

        $hash = $this->hash_password($new_password);
        $this->CI->User_model->update($user_id, ['password_hash' => $hash]);
        $this->log_action($user_id, 'password_changed', 'users', $user_id);

        return ['success' => true, 'message' => 'Mot de passe modifié avec succès.'];
    }

    /**
     * Réinitialisation admin du mot de passe
     */
    public function reset_password($user_id, $new_password)
    {
        $hash = $this->hash_password($new_password);
        $this->CI->User_model->update($user_id, ['password_hash' => $hash]);
        $this->log_action($this->user_id(), 'password_reset', 'users', $user_id, 
            'Réinitialisation par admin');
        return true;
    }

    // -------------------------------------------------------
    // JOURNALISATION
    // -------------------------------------------------------

    /**
     * Enregistrer une action dans les logs
     */
    public function log_action($user_id, $action, $module, $record_id = null, $details = null)
    {
        $this->CI->db->insert('user_logs', [
            'user_id'    => $user_id,
            'action'     => $action,
            'module'     => $module,
            'record_id'  => $record_id,
            'details'    => $details,
            'ip_address' => $this->CI->input->ip_address(),
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }

    // -------------------------------------------------------
    // FILTRAGE PAR LOCALISATION
    // -------------------------------------------------------

    /**
     * Vérifier si l'utilisateur peut accéder aux données d'une localisation
     */
    public function can_access_location($location_id)
    {
        // Admin et Op Manager voient tout
        if ($this->is_manager_or_admin()) {
            return true;
        }

        // Sinon, uniquement sa localisation
        return $this->location_id() == $location_id;
    }

    // -------------------------------------------------------
    // PRIVATE
    // -------------------------------------------------------

    private function _set_session($user)
    {
        // Charger les permissions du rôle
        $permissions = $this->CI->User_model->get_permissions($user->role_id);

        $this->CI->session->set_userdata([
            'user_id'     => $user->id,
            'username'    => $user->username,
            'full_name'   => $user->full_name,
            'email'       => $user->email,
            'role_id'     => $user->role_id,
            'role_code'   => $user->role_code,
            'location_id' => $user->location_id,
            'permissions' => $permissions,
            'logged_in'   => true,
        ]);
    }
}
