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

class Users extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('auth_lib');
        $this->load->library('form_validation');
        $this->load->model('User_model');
        $this->load->helper(['url', 'form']);

        // Toutes les pages nécessitent une connexion
        $this->auth_lib->require_login();
    }

    /**
     * Liste des utilisateurs
     */
    public function index()
    {
        $this->auth_lib->require_permission('user_view');

        $filters = [
            'role_id'     => $this->input->get('role_id'),
            'status'      => $this->input->get('status'),
            'location_id' => $this->input->get('location_id'),
            'search'      => $this->input->get('search'),
        ];

        $page   = max(1, (int) $this->input->get('page'));
        $limit  = 20;
        $offset = ($page - 1) * $limit;

        $data = [
            'title'      => 'Gestion des Utilisateurs',
            'users'      => $this->User_model->get_list($filters, $limit, $offset),
            'total'      => $this->User_model->count_list($filters),
            'roles'      => $this->User_model->get_roles(),
            'locations'  => $this->User_model->get_locations(),
            'filters'    => $filters,
            'page'       => $page,
            'limit'      => $limit,
        ];

        $this->load->view('templates/header', $data);
        $this->load->view('users/index', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Créer un utilisateur
     */
    public function create()
    {
        $this->auth_lib->require_permission('user_manage');

        $data = [
            'title'     => 'Nouvel Utilisateur',
            'roles'     => $this->User_model->get_roles(),
            'locations' => $this->User_model->get_locations(),
        ];

        if ($this->input->method() === 'post') {
            $this->_set_validation_rules();

            if ($this->form_validation->run() === TRUE) {
                $user_data = [
                    'full_name'     => $this->input->post('full_name', TRUE),
                    'username'      => $this->input->post('username', TRUE),
                    'email'         => $this->input->post('email', TRUE),
                    'phone'         => $this->input->post('phone', TRUE),
                    'password_hash' => $this->auth_lib->hash_password($this->input->post('password')),
                    'role_id'       => $this->input->post('role_id'),
                    'location_id'   => $this->input->post('location_id') ?: null,
                    'status'        => 'active',
                ];

                $new_id = $this->User_model->create($user_data);

                $this->auth_lib->log_action(
                    $this->auth_lib->user_id(), 'user_created', 'users', $new_id,
                    'Création de: ' . $user_data['username']
                );

                $this->session->set_flashdata('success', 'Utilisateur créé avec succès.');
                redirect('users');
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('users/form', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Modifier un utilisateur
     */
    public function edit($id)
    {
        $this->auth_lib->require_permission('user_manage');

        $user = $this->User_model->get($id);
        if ( ! $user) {
            show_404();
        }

        $data = [
            'title'     => 'Modifier ' . $user->full_name,
            'user'      => $user,
            'roles'     => $this->User_model->get_roles(),
            'locations' => $this->User_model->get_locations(),
        ];

        if ($this->input->method() === 'post') {
            $this->_set_validation_rules($id);

            if ($this->form_validation->run() === TRUE) {
                $update_data = [
                    'full_name'   => $this->input->post('full_name', TRUE),
                    'username'    => $this->input->post('username', TRUE),
                    'email'       => $this->input->post('email', TRUE),
                    'phone'       => $this->input->post('phone', TRUE),
                    'role_id'     => $this->input->post('role_id'),
                    'location_id' => $this->input->post('location_id') ?: null,
                    'status'      => $this->input->post('status'),
                ];

                $this->User_model->update($id, $update_data);

                $this->auth_lib->log_action(
                    $this->auth_lib->user_id(), 'user_updated', 'users', $id,
                    'Modification de: ' . $update_data['username']
                );

                $this->session->set_flashdata('success', 'Utilisateur modifié avec succès.');
                redirect('users');
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('users/form', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Activer / Désactiver un utilisateur
     */
    public function toggle_status($id)
    {
        $this->auth_lib->require_permission('user_manage');

        $user = $this->User_model->get($id);
        if ( ! $user) {
            show_404();
        }

        // Empêcher la désactivation de son propre compte
        if ($user->id == $this->auth_lib->user_id()) {
            $this->session->set_flashdata('error', 'Vous ne pouvez pas désactiver votre propre compte.');
            redirect('users');
        }

        $new_status = ($user->status === 'active') ? 'inactive' : 'active';
        $this->User_model->update($id, ['status' => $new_status]);

        $this->auth_lib->log_action(
            $this->auth_lib->user_id(), 'user_status_changed', 'users', $id,
            $user->username . ' → ' . $new_status
        );

        $this->session->set_flashdata('success', 'Statut modifié : ' . $new_status);
        redirect('users');
    }

    /**
     * Réinitialiser le mot de passe (admin)
     */
    public function reset_password($id)
    {
        $this->auth_lib->require_permission('user_manage');

        $user = $this->User_model->get($id);
        if ( ! $user) {
            show_404();
        }

        $data = [
            'title' => 'Réinitialiser le mot de passe - ' . $user->full_name,
            'user'  => $user,
        ];

        if ($this->input->method() === 'post') {
            $this->form_validation->set_rules('new_password', 'Nouveau mot de passe', 'required|min_length[8]');
            $this->form_validation->set_rules('confirm_password', 'Confirmation', 'required|matches[new_password]');

            if ($this->form_validation->run() === TRUE) {
                $this->auth_lib->reset_password($id, $this->input->post('new_password'));
                $this->session->set_flashdata('success', 'Mot de passe réinitialisé pour ' . $user->full_name);
                redirect('users');
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('users/reset_password', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Consultation des logs
     */
    public function logs()
    {
        $this->auth_lib->require_permission('log_view');

        $filters = [
            'user_id'   => $this->input->get('user_id'),
            'module'    => $this->input->get('module'),
            'action'    => $this->input->get('action'),
            'date_from' => $this->input->get('date_from'),
            'date_to'   => $this->input->get('date_to'),
        ];

        $data = [
            'title'  => 'Journal des Actions',
            'logs'   => $this->User_model->get_logs($filters, 100),
            'filters'=> $filters,
        ];

        $this->load->view('templates/header', $data);
        $this->load->view('users/logs', $data);
        $this->load->view('templates/footer');
    }

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

    private function _set_validation_rules($exclude_id = null)
    {
        $this->form_validation->set_rules('full_name', 'Nom complet', 'required|trim|max_length[120]');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|max_length[150]|callback__unique_email[' . $exclude_id . ']');
        $this->form_validation->set_rules('phone', 'Téléphone', 'trim|max_length[30]');
        $this->form_validation->set_rules('role_id', 'Rôle', 'required|integer');

        $this->form_validation->set_rules('username', 'Nom d\'utilisateur', 
            'required|trim|alpha_dash|min_length[3]|max_length[60]|callback__unique_username[' . $exclude_id . ']');

        // Mot de passe requis seulement à la création
        if ( ! $exclude_id) {
            $this->form_validation->set_rules('password', 'Mot de passe', 'required|min_length[8]');
            $this->form_validation->set_rules('confirm_password', 'Confirmation', 'required|matches[password]');
        }
    }

    /**
     * Callback : vérifier unicité du username
     */
    public function _unique_username($username, $exclude_id)
    {
        $exclude_id = $exclude_id ?: null;
        if ( ! $this->User_model->is_username_unique($username, $exclude_id)) {
            $this->form_validation->set_message('_unique_username', 'Ce nom d\'utilisateur est déjà pris.');
            return FALSE;
        }
        return TRUE;
    }

    /**
     * Callback : vérifier unicité de l'email
     */
    public function _unique_email($email, $exclude_id)
    {
        $exclude_id = $exclude_id ?: null;
        if ( ! $this->User_model->is_email_unique($email, $exclude_id)) {
            $this->form_validation->set_message('_unique_email', 'Cet email est déjà utilisé.');
            return FALSE;
        }
        return TRUE;
    }
}
