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

/**
 * Admin / Users — manage admin accounts. Super-admin only.
 */
#[\AllowDynamicProperties]
class Users extends Admin_Controller {

	public function __construct()
	{
		parent::__construct();
		// Restrict the whole controller to super admins.
		$this->required_role = 'super_admin';
		if ( ! $this->auth->is_super())
		{
			show_error('Only super administrators can manage admin users.', 403, 'Access Denied');
		}
		$this->load->model('user_model');
	}

	public function index()
	{
		$this->render('users/index', array(
			'page_title' => 'Admin Users',
			'users'      => $this->user_model->get_all(),
		));
	}

	public function create()
	{
		$this->render('users/form', array(
			'page_title' => 'Add Admin User',
			'u'          => $this->_blank(),
			'mode'       => 'create',
		));
	}

	public function edit($id)
	{
		$u = $this->user_model->get($id);
		if ( ! $u) show_404();
		$this->render('users/form', array(
			'page_title' => 'Edit Admin User',
			'u'          => $u,
			'mode'       => 'edit',
		));
	}

	public function save()
	{
		$id = (int) $this->input->post('id');

		$this->load->library('form_validation');
		$this->form_validation->set_rules('name', 'Name', 'required|trim');
		$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
		$this->form_validation->set_rules('role', 'Role', 'required');
		if ( ! $id)
		{
			$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');
		}

		if ($this->form_validation->run() === FALSE)
		{
			$this->session->set_flashdata('error', strip_tags(validation_errors()));
			redirect($id ? 'admin/users/edit/'.$id : 'admin/users/create');
		}

		$email = $this->input->post('email', TRUE);
		if ($this->user_model->email_exists($email, $id ?: NULL))
		{
			$this->session->set_flashdata('error', 'That email address is already in use.');
			redirect($id ? 'admin/users/edit/'.$id : 'admin/users/create');
		}

		$role = $this->input->post('role', TRUE);
		$role = in_array($role, array('editor', 'super_admin'), TRUE) ? $role : 'editor';

		$data = array(
			'name'      => $this->input->post('name', TRUE),
			'email'     => $email,
			'role'      => $role,
			'is_active' => $this->input->post('is_active') ? 1 : 0,
		);

		if ($id)
		{
			$this->user_model->update($id, $data);
			// Optional password change
			if ($pw = $this->input->post('password'))
			{
				if (strlen($pw) >= 8)
				{
					$this->user_model->set_password($id, $pw);
				}
			}
			$this->log('Updated admin user', $data['name']);
			$msg = 'Admin user updated.';
		}
		else
		{
			$data['password']   = password_hash($this->input->post('password'), PASSWORD_BCRYPT);
			$data['created_at'] = date('Y-m-d H:i:s');
			$this->user_model->insert($data);
			$this->log('Created admin user', $data['name']);
			$msg = 'Admin user created.';
		}

		$this->session->set_flashdata('success', $msg);
		redirect('admin/users');
	}

	public function delete($id)
	{
		// Never let an admin delete their own account.
		if ((int) $id === (int) $this->user['id'])
		{
			$this->session->set_flashdata('error', 'You cannot delete your own account.');
			redirect('admin/users');
		}

		$u = $this->user_model->get($id);
		if ($u)
		{
			$this->user_model->delete($id);
			$this->log('Deleted admin user', $u['name']);
			$this->session->set_flashdata('success', 'Admin user deleted.');
		}
		redirect('admin/users');
	}

	public function toggle($id)
	{
		if ((int) $id === (int) $this->user['id'])
		{
			$this->session->set_flashdata('error', 'You cannot deactivate your own account.');
			redirect('admin/users');
		}
		$u = $this->user_model->get($id);
		if ($u) $this->user_model->update($id, array('is_active' => $u['is_active'] ? 0 : 1));
		redirect('admin/users');
	}

	private function _blank()
	{
		return array(
			'id' => 0, 'name' => '', 'email' => '', 'role' => 'editor',
			'avatar' => '', 'is_active' => 1, 'last_login' => NULL,
		);
	}
}
