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

/**
 * Extended Security class: when CSRF fails on login-related requests,
 * redirect back to the login page with a "session expired" message instead of 403.
 */
class MY_Security extends CI_Security {

	/**
	 * Show CSRF Error - redirect to login with friendly message when session/token expired on login forms
	 *
	 * @return	void
	 */
	public function csrf_show_error()
	{
		if (!function_exists('get_instance')) {
			show_error('The action you have requested is not allowed.', 403);
			return;
		}
		$CI =& get_instance();
		$uri = '';
		if (isset($CI->uri) && is_object($CI->uri)) {
			$uri = $CI->uri->uri_string();
		} elseif (isset($CI->router) && is_object($CI->router)) {
			$class = $CI->router->fetch_class();
			$method = $CI->router->fetch_method();
			$uri = $class . '/' . $method;
		}

		// Match login-related URIs (check more specific paths first)
		if ($uri === 'login/verify_otp' || strpos($uri, 'login/verify_otp/') === 0) {
			if (isset($CI->session) && is_object($CI->session)) {
				$CI->session->set_flashdata('failed', 'Your session has expired. Please try again.');
			}
			redirect('login/otp');
			return;
		}
		if ($uri === 'login/send_otp' || strpos($uri, 'login/send_otp/') === 0) {
			if (isset($CI->session) && is_object($CI->session)) {
				$CI->session->set_flashdata('failed', 'Your session has expired. Please try again.');
			}
			redirect('login/forgot_password');
			return;
		}
		if ($uri === 'login/verify' || strpos($uri, 'login/verify/') === 0) {
			if (isset($CI->session) && is_object($CI->session)) {
				$CI->session->set_flashdata('failed', 'Your session has expired. Please sign in again.');
			}
			redirect('login');
			return;
		}

		show_error('The action you have requested is not allowed.', 403);
	}
}
