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

include_once APPPATH . 'core/Admin_Controller.php';

class Users extends Admin_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_m');
        $this->load->model('rbac_m');
        $this->load->database();
        if (!$this->rbac_m->tables_ready()) {
            redirect(base_url('index.php/install/rbac'));
            return;
        }
        $this->require_permission('manage_users', 'view');
    }

    public function index()
    {
        $this->data['page_title'] = 'Users';
        $this->data['users'] = $this->user_m->get_all();
        $this->data['flash_success'] = $this->session->flashdata('success');
        $this->data['flash_error'] = $this->session->flashdata('error');
        $this->render_report('admin/users/index', $this->data);
    }

    public function create()
    {
        $this->data['page_title'] = 'Add User';
        $this->data['user'] = null;
        $this->data['roles'] = $this->rbac_m->get_roles(true);
        $this->data['form_action'] = base_url('index.php/users/store');
        $this->render_report('admin/users/form', $this->data);
    }

    public function store()
    {
        $payload = $this->collect_payload(true);
        if ($payload === false) {
            redirect(base_url('index.php/users/create'));
            return;
        }

        if ($this->user_m->get_by_username($payload['username'])) {
            $this->session->set_flashdata('error', 'Username already exists.');
            redirect(base_url('index.php/users/create'));
            return;
        }

        $this->user_m->create($payload);
        $this->session->set_flashdata('success', 'User created successfully.');
        redirect(base_url('index.php/users'));
    }

    public function edit($id = null)
    {
        $user = $this->user_m->get($id);
        if (!$user) {
            show_404();
            return;
        }
        $this->data['page_title'] = 'Edit User';
        $this->data['user'] = $user;
        $this->data['roles'] = $this->rbac_m->get_roles(true);
        $this->data['form_action'] = base_url('index.php/users/update/' . (int) $id);
        $this->render_report('admin/users/form', $this->data);
    }

    public function update($id = null)
    {
        $user = $this->user_m->get($id);
        if (!$user) {
            show_404();
            return;
        }

        $payload = $this->collect_payload(false);
        if ($payload === false) {
            redirect(base_url('index.php/users/edit/' . (int) $id));
            return;
        }

        if ($this->user_m->get_by_username($payload['username'], $id)) {
            $this->session->set_flashdata('error', 'Username already exists.');
            redirect(base_url('index.php/users/edit/' . (int) $id));
            return;
        }

        // Do not overwrite password if left blank
        if ($payload['password'] === '' || $payload['password'] === null) {
            unset($payload['password']);
        }

        $this->user_m->update($id, $payload);
        $this->session->set_flashdata('success', 'User updated successfully.');
        redirect(base_url('index.php/users'));
    }

    public function delete($id = null)
    {
        $user = $this->user_m->get($id);
        if (!$user) {
            show_404();
            return;
        }
        if ((int) $user->id === (int) $this->session->userdata('userid')) {
            $this->session->set_flashdata('error', 'You cannot delete your own account.');
            redirect(base_url('index.php/users'));
            return;
        }
        $this->user_m->delete($id);
        $this->session->set_flashdata('success', 'User deleted.');
        redirect(base_url('index.php/users'));
    }

    public function toggle_status($id = null)
    {
        $user = $this->user_m->get($id);
        if (!$user) {
            show_404();
            return;
        }
        if ((int) $user->id === (int) $this->session->userdata('userid')) {
            $this->session->set_flashdata('error', 'You cannot disable your own account.');
            redirect(base_url('index.php/users'));
            return;
        }
        $status = isset($user->status) ? (int) $user->status : 1;
        $this->user_m->update($id, array('status' => $status ? 0 : 1));
        $this->session->set_flashdata('success', 'User status updated.');
        redirect(base_url('index.php/users'));
    }

    protected function collect_payload($require_password)
    {
        $name = trim((string) $this->input->post('name'));
        $username = trim((string) $this->input->post('username'));
        $password = (string) $this->input->post('password');
        $email = trim((string) $this->input->post('email'));
        $role_id = (int) $this->input->post('role_id');
        $status = (int) $this->input->post('status') ? 1 : 0;
        $university_name = trim((string) $this->input->post('university_name'));

        if ($name === '' || $username === '' || !$role_id) {
            $this->session->set_flashdata('error', 'Name, username and role are required.');
            return false;
        }
        if ($require_password && $password === '') {
            $this->session->set_flashdata('error', 'Password is required for new users.');
            return false;
        }

        $role = $this->rbac_m->get_role($role_id);
        if (!$role || !(int) $role->status) {
            $this->session->set_flashdata('error', 'Invalid role selected.');
            return false;
        }

        // Keep usertype in sync for legacy checks / Super Admin
        $usertype = !empty($role->is_superadmin) ? 'Admin' : 'User';

        $data = array(
            'name' => $name,
            'username' => $username,
            'password' => $password,
            'email' => $email !== '' ? $email : null,
            'role_id' => $role_id,
            'status' => $status,
            'usertype' => $usertype,
            'university_name' => $university_name !== '' ? $university_name : $name,
        );

        return $data;
    }
}
