<?php
/**
 * Handles the Community Login page functionality.
 *
 * @package HVAC_Community_Events
 * @version 1.0.0
 */

namespace HVAC_Community_Events\Community;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Login_Handler Class
 */
class Login_Handler {

	/**
	 * Constructor.
	 * Hooks into WordPress.
	 */
	public function __construct() {
	 // Register our shortcode only if it doesn't exist already
	 if (!shortcode_exists('hvac_community_login')) {
	   add_shortcode('hvac_community_login', array($this, 'render_login_form'));
	 }
	 
	 add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts')); // Enqueue scripts/styles

	 // Add action hooks for authentication and redirection
	 add_action('wp_authenticate', array($this, 'handle_authentication'), 30, 2);
	 
	 // Handle failed login redirect back to custom login page
	 add_action('wp_login_failed', array($this, 'handle_login_failure'));
	 
	 // Handle successful login redirect
	 add_filter('login_redirect', array($this, 'custom_login_redirect'), 10, 3);

	 // Redirect logged-in users away from the login page
	 add_action('template_redirect', array($this, 'redirect_logged_in_user'));
	}

	/**
	 * Renders the login form using the custom template.
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string HTML output of the login form.
	 */
	public function render_login_form( $atts ) {
	 // Logged-in user check and redirect moved to redirect_logged_in_user() hooked to template_redirect

	 // Start output buffering to capture the template output.
	 ob_start();

		// Check for login errors passed via query parameters
		if ( isset( $_GET['login'] ) && $_GET['login'] === 'failed' ) {
			// You might want to use a more user-friendly message or integrate with theme notices
			echo '<div class="hvac-login-error" style="color: red; border: 1px solid red; padding: 10px; margin-bottom: 15px;">' . esc_html__( 'Invalid username or password.', 'hvac-community-events' ) . '</div>';
		}

		// Define variables needed by the template (if any)
		// $caption = __( 'Please log in to access the trainer area.', 'hvac-community-events' );

		// Include the custom login form template.
		// Use a helper function to locate the template, allowing theme overrides.
		$template_path = \HVAC_PLUGIN_DIR . 'templates/community/login-form.php'; // Use HVAC_PLUGIN_DIR constant
		if ( file_exists( $template_path ) ) {
			include $template_path;
		} else {
			// Fallback or error message if template is missing
			echo '<p>Error: Login form template not found.</p>';
		}

		// Return the buffered content.
		return ob_get_clean();
	}

	/**
		* Enqueues scripts and styles for the login page.
		*/
	public function enqueue_scripts() {
		global $post;

		// Only enqueue if the shortcode is present on the current page.
		if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'hvac_community_login' ) ) {
			// Enqueue common HVAC styles
			wp_enqueue_style(
				'hvac-common-style',
				\HVAC_PLUGIN_URL . 'assets/css/hvac-common.css',
				array(), 
				\HVAC_PLUGIN_VERSION
			);
			
			// Enqueue harmonized framework
			wp_enqueue_style(
				'hvac-harmonized-framework',
				\HVAC_PLUGIN_URL . 'assets/css/hvac-harmonized.css',
				array('hvac-common-style'), 
				\HVAC_PLUGIN_VERSION
			);
			
			// Enqueue base login CSS
			wp_enqueue_style(
				'hvac-community-login',
				\HVAC_PLUGIN_URL . 'assets/css/community-login.css',
				array('hvac-harmonized-framework'), 
				\HVAC_PLUGIN_VERSION
			);
			
			// Enqueue enhanced CSS
			wp_enqueue_style(
				'hvac-community-login-enhanced',
				\HVAC_PLUGIN_URL . 'assets/css/community-login-enhanced.css',
				array('hvac-community-login'), 
				\HVAC_PLUGIN_VERSION
			);

			// Enqueue jQuery (dependency for our JavaScript)
			wp_enqueue_script('jquery');
			
			// Enqueue login JavaScript
			wp_enqueue_script(
				'hvac-community-login-js',
				\HVAC_PLUGIN_URL . 'assets/js/community-login.js',
				array('jquery'),
				\HVAC_PLUGIN_VERSION,
				true
			);

			// Localize script with translatable strings
			wp_localize_script('hvac-community-login-js', 'hvacLogin', array(
				'showPassword' => __('Show password', 'hvac-community-events'),
				'hidePassword' => __('Hide password', 'hvac-community-events'),
				'usernameRequired' => __('Username or email is required.', 'hvac-community-events'),
				'passwordRequired' => __('Password is required.', 'hvac-community-events'),
				'loggingIn' => __('Logging in...', 'hvac-community-events'),
				'logIn' => __('Log In', 'hvac-community-events'),
				'ajaxUrl' => admin_url('admin-ajax.php'),
				'nonce' => wp_create_nonce('hvac_login_nonce')
			));
		}
	}

	/**
	 * Handles custom authentication logic (if needed).
	 * Placeholder for Task 2.2.
	 *
	 * @param string $username Username or email address.
	 * @param string $password Password.
	 */
	public function handle_authentication( &$username, &$password ) {
	 // Custom validation or checks can go here.
	 // For now, rely on default WordPress authentication.
	}

	/**
	 * Handles redirecting the user back to the custom login page on authentication failure.
	 *
	 * Hooked to 'wp_login_failed'.
	 */
	public function handle_login_failure($username) {
	 // Check if the request originated from our custom login page
	 // We check both the referrer and the hidden field
	 $referrer = wp_get_referer();
	 $is_custom_login = isset($_POST['hvac_custom_login']) && $_POST['hvac_custom_login'] === '1';
	 $login_page_slug = 'training-login';

	 if ($is_custom_login || ($referrer && strpos($referrer, $login_page_slug) !== false)) {
	 	$login_page_url = home_url('/' . $login_page_slug . '/');
	 	
	 	// Preserve redirect_to parameter if it exists
	 	$redirect_to = isset($_POST['redirect_to']) ? $_POST['redirect_to'] : '';
	 	$args = array('login' => 'failed');
	 	if (!empty($redirect_to)) {
	 		$args['redirect_to'] = $redirect_to;
	 	}
	 	
	 	// Redirect back to the custom login page with a failure flag
	 	wp_safe_redirect(add_query_arg($args, $login_page_url));
	 	exit;
	 }
	 // If not from our custom login page, let WordPress handle normally
	}

	// REMOVED: Unnecessary redirect_on_login_failure method.
	// WordPress handles redirecting back to the referring page (our custom login page)
	// on authentication failure automatically when using wp_login_form().
	// The 'login_redirect' filter handles the success case.

	/**
	 * Custom redirect logic after successful login.
	 * Placeholder for Task 2.5.
	 * Filters the login redirect URL based on user role.
	 *
	 * @param string   $redirect_to           The redirect destination URL.
	 * @param string   $requested_redirect_to The requested redirect destination URL (if provided).
	 * @param WP_User|WP_Error $user          WP_User object if login successful, WP_Error object otherwise.
	 * @return string Redirect URL.
	 */
	public function custom_login_redirect( $redirect_to, $requested_redirect_to, $user ) {
	 // Check if login was successful and user is not an error object
	 if ( $user && ! is_wp_error( $user ) ) {
	 	// Check if the user has Master Trainer capabilities - redirect to Master Dashboard first
	 	if ( user_can( $user, 'view_master_dashboard' ) || user_can( $user, 'view_all_trainer_data' ) ) {
	 		// Redirect Master Trainers to the Master Dashboard
	 		$master_dashboard_url = home_url( '/master-trainer/dashboard/' );
	 		return $master_dashboard_url;
	 	}
	 	// Check if the user has the 'hvac_trainer' role
	 	elseif ( in_array( 'hvac_trainer', (array) $user->roles ) ) {
	 		// Redirect regular HVAC trainers to their dashboard
	 		// Updated to new hierarchical URL structure
	 		$dashboard_url = home_url( '/trainer/dashboard/' );
	 		return $dashboard_url;
	 	} else {
	 		// For other roles (like admin), redirect to the standard WP admin dashboard.
	 		// If $requested_redirect_to is set (e.g., trying to access a specific admin page), respect it.
	 		return $requested_redirect_to ? $requested_redirect_to : admin_url();
	 	}
	 }

	 // If login failed ($user is WP_Error), return the default $redirect_to.
	 // Our redirect_on_login_failure should ideally catch this first, but this is a fallback.
	 return $redirect_to;
	}

	/**
	 * Redirects logged-in users away from the custom login page.
	 * Hooked to 'template_redirect'.
	 */
	public function redirect_logged_in_user() {
	 // Check if we are on the custom login page (adjust slug if needed)
	 if ( is_page( 'training-login' ) && is_user_logged_in() ) {
	 	// Get current user
	 	$user = wp_get_current_user();
	 	
	 	// Redirect based on user role/capabilities - prioritize Master Trainers
	 	if ( current_user_can( 'view_master_dashboard' ) || current_user_can( 'view_all_trainer_data' ) ) {
	 		// Master Trainers go to the Master Dashboard
	 		$master_dashboard_url = home_url( '/master-trainer/dashboard/' );
	 		wp_safe_redirect( $master_dashboard_url );
	 		exit;
	 	} elseif ( in_array( 'hvac_trainer', (array) $user->roles ) || current_user_can( 'view_hvac_dashboard' ) ) {
	 		// Regular HVAC trainers go to their dashboard
	 		$dashboard_url = home_url( '/trainer/dashboard/' );
	 		wp_safe_redirect( $dashboard_url );
	 		exit;
	 	} elseif ( current_user_can( 'manage_options' ) ) {
	 		// Administrators can choose - redirect to WP admin or allow access to dashboard
	 		// For now, let them stay on the login page with a message, or redirect to admin
	 		$admin_url = admin_url();
	 		wp_safe_redirect( $admin_url );
	 		exit;
	 	} else {
	 		// Other logged-in users get redirected to home page
	 		wp_safe_redirect( home_url() );
	 		exit;
	 	}
	 }
	}

}