<?php
class Admin extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Role_model');
        $this->load->model('User_model');
        $this->load->model('Permission_model');

        // Access control: Only allow role_id = 1 (superadmin)
        if ($this->session->userdata('role_id') != 1) {
            show_error('Access denied. Admins only.');
        }

        // Load helper and library
        $this->load->helper(['form', 'security']);
        $this->load->library('session');
    }

    // --- USER MANAGEMENT ---

    public function manage_users() {
        $data['users'] = $this->User_model->get_all_users();
        $this->load->view('admin/manage_users', $data);
    }

    public function create_user() {
        if ($_POST) {
            $user_data = [
                'name' => $this->input->post('name'),
                'email' => $this->input->post('email'),
                'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
                'role_id' => $this->input->post('role_id'),
                'is_active' => $this->input->post('is_active') ?? 0
            ];

            $this->User_model->create_user($user_data);
            $this->session->set_flashdata('success', 'User created successfully.');
            redirect('admin/manage_users');
        }

        $data['roles'] = $this->Role_model->get_all_roles();
        $this->load->view('admin/create_user', $data);
    }

    public function edit_user($encoded_id) {
        $user_id = base64_decode($encoded_id);
        if (!is_numeric($user_id)) show_404();

        $user = $this->User_model->get_user_by_id($user_id);
        if (!$user) show_404();

        $data['user'] = $user;
        $data['roles'] = $this->Role_model->get_all_roles();
        $this->load->view('admin/edit_user', $data);
    }

    public function update_user($encoded_id) {
        $user_id = base64_decode($encoded_id);
        if (!is_numeric($user_id)) show_404();

        $data = [
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email'),
            'role_id' => $this->input->post('role_id'),
            'is_active' => $this->input->post('is_active') ?? 0
        ];

        $password = $this->input->post('password');
        if ($password) {
            $data['password'] = password_hash($password, PASSWORD_DEFAULT);
        }

        $this->User_model->update_user($user_id, $data);
        $this->session->set_flashdata('success', 'User updated successfully.');
        redirect('admin/manage_users');
    }

    public function delete_user($encoded_id) {
        $user_id = base64_decode($encoded_id);
        if (!is_numeric($user_id)) show_404();

        $this->User_model->delete_user($user_id);
        $this->session->set_flashdata('success', 'User deleted successfully.');
        redirect('admin/manage_users');
    }

    public function activate_user($encoded_id) {
        $user_id = base64_decode($encoded_id);
        if (!is_numeric($user_id)) show_404();

        $this->User_model->update_status($user_id, 1);
        $this->session->set_flashdata('success', 'User activated.');
        redirect('admin/manage_users');
    }

    public function deactivate_user($encoded_id) {
        $user_id = base64_decode($encoded_id);
        if (!is_numeric($user_id)) show_404();

        $this->User_model->update_status($user_id, 0);
        $this->session->set_flashdata('success', 'User deactivated.');
        redirect('admin/manage_users');
    }

    // --- ROLE MANAGEMENT ---

    public function manage_roles() {
        $data['roles'] = $this->Role_model->get_all_roles();
        $this->load->view('admin/manage_roles', $data);
    }

    public function create_role() {
        if ($_POST) {
            $role_name = $this->input->post('role_name');
            if (!empty($role_name)) {
                $this->Role_model->create_role($role_name);
                $this->session->set_flashdata('success', 'Role created.');
                redirect('admin/manage_roles');
            } else {
                $data['error'] = "Role name cannot be empty.";
            }
        }
        $this->load->view('admin/create_role');
    }

    public function delete_role($role_id) {
        if ($role_id != 1) {
            $this->Role_model->delete_role($role_id);
            $this->session->set_flashdata('success', 'Role deleted.');
        }
        redirect('admin/manage_roles');
    }

    // --- PERMISSIONS MANAGEMENT ---

    public function manage_permissions() {
        if ($_POST) {
            $role_id = $this->input->post('role_id');
            $sections = $this->input->post('sections') ?? [];
            $this->Permission_model->update_permissions($role_id, $sections);
            $this->session->set_flashdata('success', 'Permissions updated.');
        }

        $data['roles'] = $this->Role_model->get_all_roles();
        $data['sections'] = ['clients', 'accounts', 'balance', 'tickets', 'users'];
        $this->load->view('admin/manage_permissions', $data);
    }
}