<?php

namespace MovieEngine\Frontend\Users;

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

class Auth {

    public function __construct() {
        add_shortcode('movie_engine_login', [$this, 'render_login_form']);
        add_shortcode('movie_engine_register', [$this, 'render_login_form']);
        add_action('wp_ajax_nopriv_movie_engine_ajax_login', [$this, 'ajax_login']);
        add_action('wp_ajax_movie_engine_ajax_login', [$this, 'ajax_login']);
        add_action('wp_ajax_nopriv_movie_engine_ajax_register', [$this, 'ajax_register']);
        add_action('wp_ajax_movie_engine_ajax_register', [$this, 'ajax_register']);
        add_action('wp_ajax_nopriv_movie_engine_ajax_lost_password', [$this, 'ajax_lost_password']);
        add_action('wp_ajax_movie_engine_ajax_lost_password', [$this, 'ajax_lost_password']);
        add_action('init', [$this, 'redirect_wp_login_page']);
        add_action('template_redirect', [$this, 'render_virtual_login']);
        add_filter('login_url', [$this, 'filter_login_url'], 10, 3);
        add_filter('register_url', [$this, 'filter_register_url'], 10, 1);
        add_filter('retrieve_password_message', [$this, 'override_reset_email'], 10, 4);
    }

    public function filter_login_url($login_url, $redirect, $force_reauth) {
        $general_settings = get_option('movie_engine_general_settings', []);
        $enable_custom_login = isset($general_settings['enable_custom_login']) ? $general_settings['enable_custom_login'] : 1;

        if (!$enable_custom_login) {
            return $login_url;
        }

        $design_settings = get_option('movie_engine_design_settings', []);
        $login_page_id = isset($design_settings['login_page']) ? intval($design_settings['login_page']) : 0;

        if (!$login_page_id) {
            $page = get_page_by_path('movie-engine-login');
            if ($page) $login_page_id = $page->ID;
        }

        if ($login_page_id) {
            $custom_url = get_permalink($login_page_id);
            if (!empty($redirect)) {
                $custom_url = add_query_arg('redirect_to', urlencode($redirect), $custom_url);
            }
            return $custom_url;
        }
        return $login_url;
    }


    public function filter_register_url($register_url) {
        $general_settings = get_option('movie_engine_general_settings', []);
        $enable_custom_login = isset($general_settings['enable_custom_login']) ? $general_settings['enable_custom_login'] : 1;

        if (!$enable_custom_login) {
            return $register_url;
        }

        $design_settings = get_option('movie_engine_design_settings', []);
        $register_page_id = isset($design_settings['register_page']) ? intval($design_settings['register_page']) : 0;

        if (!$register_page_id) {
            $page = get_page_by_path('movie-engine-register');
            if ($page) $register_page_id = $page->ID;
        }

        if ($register_page_id) {
            return get_permalink($register_page_id);
        }
        return $register_url;
    }

    public function redirect_wp_login_page() {
        global $pagenow;
        $request_method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper(sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD']))) : '';
        if ($pagenow !== 'wp-login.php' || $request_method !== 'GET' || is_user_logged_in()) {
            return;
        }

        $general_settings = get_option('movie_engine_general_settings', []);
        $enable_custom_login = isset($general_settings['enable_custom_login']) ? $general_settings['enable_custom_login'] : 1;

        if (!$enable_custom_login) {
            return;
        }

        $allowed_actions = ['logout', 'rp', 'resetpass', 'postpass'];
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $current_action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : 'login';

        if (in_array($current_action, $allowed_actions)) {
            return;
        }

        $design_settings = get_option('movie_engine_design_settings', []);
        $login_page_id = isset($design_settings['login_page']) ? intval($design_settings['login_page']) : 0;
        $use_redirect = false;

        if ($login_page_id && get_post_status($login_page_id) === 'publish') {
            $use_redirect = true;
        } else {

            $page = get_page_by_path('movie-engine-login');
            if ($page && $page->post_status === 'publish') {
                $login_page_id = $page->ID;
                $use_redirect = true;
            }
        }

        if ($use_redirect) {
            wp_safe_redirect(get_permalink($login_page_id));
            exit();
        } else {
            $virtual_url = add_query_arg('movie_engine_cx_login', '1', home_url('/'));
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if (!empty($_GET['redirect_to'])) {
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                $virtual_url = add_query_arg('redirect_to', urlencode(sanitize_text_field(wp_unslash($_GET['redirect_to']))), $virtual_url);
            }
            wp_safe_redirect($virtual_url);
            exit();
        }
    }

    public function render_virtual_login() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (isset($_GET['movie_engine_cx_login']) && $_GET['movie_engine_cx_login'] == '1') {
            nocache_headers();
            status_header(200);
            get_header();
            echo '<div class="movie-engine-virtual-login-container me-virtual-login">';
            echo do_shortcode('[movie_engine_login]');
            echo '</div>';
            get_footer();
            exit();
        }
    }

    public function render_login_form($atts, $content = null, $tag = '') {
        if (is_user_logged_in()) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $redirect_to = isset($_GET['redirect_to']) ? sanitize_text_field(wp_unslash($_GET['redirect_to'])) : '';
            $redirect_url = UserAccess::get_login_redirect_url(null, $redirect_to);
            $current_url = home_url(add_query_arg([], $GLOBALS['wp']->request));
            if (strpos($redirect_url, $current_url) !== false || $redirect_url == get_permalink()) {
                return '';
            }

            if (!headers_sent()) {
                wp_safe_redirect($redirect_url);
                exit;
            }
            return '<div class="movie-engine-force-redirect" data-url="' . esc_attr($redirect_url) . '"></div>';
        }

        $atts = shortcode_atts([
            'action' => 'login'
        ], $atts);

        if ($tag === 'movie_engine_register') {
            $atts['action'] = 'register';
        }

        ob_start();
        \MovieEngine\Utils\TemplateLoader::get_template_part('auth/form', 'login', [
            'action' => $atts['action']
        ]);
        return ob_get_clean();
    }

    public function ajax_login() {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'movie_engine_nonce')) {
            wp_send_json_error(['message' => esc_html__('Security check failed. Please refresh the page.', 'cine-movie-engine')]);
        }

        $creds = [
            'user_login'    => isset($_POST['username']) ? sanitize_text_field(wp_unslash($_POST['username'])) : '',
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            'user_password' => isset($_POST['password']) ? wp_unslash($_POST['password']) : '',
            'remember'      => true
        ];

        $user = wp_signon($creds, is_ssl());

        if (is_wp_error($user)) {
            wp_send_json_error(['message' => $user->get_error_message()]);
        }

        $redirect_to = isset($_POST['redirect_to']) ? sanitize_text_field(wp_unslash($_POST['redirect_to'])) : '';
        wp_send_json_success([
            'redirect' => UserAccess::get_login_redirect_url($user, $redirect_to)
        ]);
    }

    public function ajax_register() {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'movie_engine_nonce')) {
            wp_send_json_error(['message' => esc_html__('Security check failed. Please refresh the page.', 'cine-movie-engine')]);
        }

        if (!get_option('users_can_register')) {
            wp_send_json_error(['message' => esc_html__('Registration is currently disabled.', 'cine-movie-engine')]);
        }

        $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
        $username = isset($_POST['username']) ? sanitize_text_field(wp_unslash($_POST['username'])) : '';
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $password = isset($_POST['password']) ? wp_unslash($_POST['password']) : '';

        if (username_exists($username) || email_exists($email)) {
            wp_send_json_error(['message' => esc_html__('User already exists.', 'cine-movie-engine')]);
        }

        $user_id = wp_create_user($username, $password, $email);

        if (is_wp_error($user_id)) {
            wp_send_json_error(['message' => $user_id->get_error_message()]);
        }

        $user = wp_signon([
            'user_login'    => $username,
            'user_password' => $password,
            'remember'      => true
        ], is_ssl());

        $redirect_to = isset($_POST['redirect_to']) ? sanitize_text_field(wp_unslash($_POST['redirect_to'])) : '';
        wp_send_json_success([
            'message' => esc_html__('Registration successful! Redirecting...', 'cine-movie-engine'),
            'redirect' => UserAccess::get_login_redirect_url($user, $redirect_to)
        ]);
    }

    /**
     * AJAX Lost Password
     */
    public function ajax_lost_password() {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'movie_engine_nonce')) {
            wp_send_json_error(['message' => esc_html__('Security check failed. Please refresh the page.', 'cine-movie-engine')]);
        }

        $user_input = isset($_POST['user_login']) ? sanitize_text_field(wp_unslash($_POST['user_login'])) : '';
        if (empty($user_input)) {
            wp_send_json_error(['message' => esc_html__('Enter a username or email.', 'cine-movie-engine')]);
        }

        $user_data = get_user_by('login', $user_input);
        if (!$user_data) {
            $user_data = get_user_by('email', $user_input);
        }

        if (!$user_data) {
            wp_send_json_error(['message' => esc_html__('User not found.', 'cine-movie-engine')]);
        }

        $errors = retrieve_password($user_data->user_login);

        if (is_wp_error($errors)) {
            wp_send_json_error(['message' => $errors->get_error_message()]);
        }

        wp_send_json_success(['message' => esc_html__('Check your email for the reset link.', 'cine-movie-engine')]);
    }

    public function override_reset_email($message, $key, $user_login, $user_data) {
        if (user_can($user_data, 'manage_options')) {
            return $message;
        }
        $reset_url = add_query_arg(['action' => 'rp', 'key' => $key, 'login' => rawurlencode($user_login)], wp_login_url());
        $email = new \MovieEngine\Emails\Types\ForgotPasswordEmail();
        $email->trigger($user_data, $reset_url);

        return false;
    }
}
