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

/**
 * Admin / Login — authentication entry point.
 *
 * Extends MX_Controller directly (NOT Admin_Controller) so it does not
 * inherit the "redirect if not logged in" guard, which would loop.
 */
#[\AllowDynamicProperties]
class Login extends MX_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->library(array('session', 'auth', 'form_validation'));
		$this->load->helper(array('url', 'form', 'bloom', 'ui'));
		$this->load->model('setting_model');
		$this->settings = $this->setting_model->all();
	}

	/** Login form. Redirects to the dashboard if already signed in. */
	public function index()
	{
		if ($this->auth->logged_in())
		{
			redirect('admin/dashboard');
		}
		$this->load->view('admin/auth/login', array(
			'settings' => $this->settings,
		));
	}

	/** Process the login form. */
	public function submit()
	{
		$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
		$this->form_validation->set_rules('password', 'Password', 'required');

		if ($this->form_validation->run() === FALSE)
		{
			$this->session->set_flashdata('error', 'Please enter a valid email and password.');
			redirect('admin/login');
		}

		$result = $this->auth->attempt(
			$this->input->post('email', TRUE),
			$this->input->post('password')
		);

		if ($result === TRUE)
		{
			// Record the sign-in in the audit trail.
			$this->load->model('activity_model');
			$this->activity_model->record($this->auth->id(), 'Signed in', '');
			redirect('admin/dashboard');
		}

		// $result is an error message string
		$this->session->set_flashdata('error', $result);
		redirect('admin/login');
	}

	/** Sign out. */
	public function logout()
	{
		if ($this->auth->logged_in())
		{
			$this->load->model('activity_model');
			$this->activity_model->record($this->auth->id(), 'Signed out', '');
		}
		$this->auth->logout();
		$this->session->set_flashdata('success', 'You have been signed out.');
		redirect('admin/login');
	}
}
