<?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 (Task 2.2 & 2.5)
	 add_action('wp_authenticate', array($this, 'handle_authentication'), 30, 2); // Allow custom auth checks
	 // REMOVED: add_action('login_form_login', array($this, 'redirect_on_login_failure')); // This was causing premature redirects

	 // Temporarily disabled for testing
	 // add_action('wp_login_failed', array($this, 'handle_login_failure')); // Handle failed login redirect
	 add_filter('login_redirect', array($this, 'custom_login_redirect'), 10, 3); // Handle success redirect

	 // 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_CE_PLUGIN_DIR . 'templates/community/login-form.php'; // Correct constant name
		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' ) ) {
			wp_enqueue_style(
				'hvac-community-login-style',
				HVAC_CE_PLUGIN_URL . 'assets/css/community-login.css',
				array(), // Add dependencies like theme stylesheet if needed
				HVAC_CE_VERSION
			);
		}
	}

	/**
	 * 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() {
	 // Check if the request originated from our custom login page.
	 // This prevents interference with the standard wp-login.php flow if accessed directly.
	 $referrer = wp_get_referer();
	 $login_page_slug = 'community-login'; // The slug of your custom login page

	 if ( $referrer && strpos( $referrer, $login_page_slug ) !== false ) {
	 	$login_page_url = home_url( '/' . $login_page_slug . '/' );
	 	// Redirect back to the custom login page with a failure flag.
	 	wp_safe_redirect( add_query_arg( 'login', 'failed', $login_page_url ) );
	 	exit;
	 }
	 // If not referred from our custom login page, let WordPress handle the failure (usually redisplays wp-login.php).
	}

	// 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 the 'hvac_trainer' role
	 	if ( in_array( 'hvac_trainer', (array) $user->roles ) ) {
	 		// Redirect HVAC trainers to their dashboard
	 		// Assumes dashboard page slug is 'hvac-dashboard'. Adjust if needed.
	 		$dashboard_url = home_url( '/hvac-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( 'community-login' ) && is_user_logged_in() ) {
	 	// Get current user
	 	$user = wp_get_current_user();
	 	
	 	// Redirect based on user role/capabilities
	 	if ( in_array( 'hvac_trainer', (array) $user->roles ) || current_user_can( 'view_hvac_dashboard' ) ) {
	 		// HVAC trainers go to their dashboard
	 		$dashboard_url = home_url( '/hvac-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;
	 	}
	 }
	}

}