<?php
/**
 * Custom Login & Registration System for WordPress
 * Version: 2.0
 * Description: Complete login/registration system with AJAX support and custom redirects
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class RM_Custom_Auth_System {
    
    private $text_domain = 'wp_custom_auth';
    
    public function __construct() {
        add_action('init', [$this, 'init']);
        add_action('plugins_loaded', [$this, 'load_textdomain']);
        
        // AJAX hooks
        add_action('wp_ajax_nopriv_custom_login', [$this, 'ajax_login']);
        add_action('wp_ajax_nopriv_custom_register', [$this, 'ajax_register']);
        
        // Redirect hooks
        add_action('init', [$this, 'redirect_login_page']);
        add_action('wp_logout', [$this, 'custom_logout_redirect']);
        
        // Shortcodes
        add_shortcode('custom_login_form', [$this, 'login_form_shortcode']);
        add_shortcode('custom_register_form', [$this, 'register_form_shortcode']);
        
        // Enqueue scripts
        add_action('wp_head', [$this, 'enqueue_scripts']);
    }
    
    public function init() {
        // Any initialization code
    }
    
    public function load_textdomain() {
        load_plugin_textdomain($this->text_domain, false, dirname(plugin_basename(__FILE__)) . '/lang/');
    }
    
    /**
     * Redirect default WordPress login to custom login page
     */
    public function redirect_login_page() {
        global $pagenow;
        
        
        // Check if we're on wp-login.php
        if ($pagenow === 'wp-login.php') {
            // Allow logout action
            if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'logout') {
                return;
            }
            
            // Allow password reset actions
            if (isset($_REQUEST['action']) && in_array($_REQUEST['action'], ['lostpassword', 'rp', 'resetpass'])) {
                return;
            }
            
            $login_page = $this->get_login_page_url();
            if ($login_page) {
                $redirect_to = isset($_GET['redirect_to']) ? '?redirect_to=' . urlencode($_GET['redirect_to']) : '';
                wp_redirect($login_page . $redirect_to);
                exit;
            }
        }
    }
    
    /**
     * Custom logout redirect
     */
    public function custom_logout_redirect() {
        $login_page = $this->get_login_page_url();
        if ($login_page) {
            $redirect_url = $login_page . '?login_status=logout';
            wp_redirect($redirect_url);
            exit;
        }
    }
    
    /**
     * Get login page URL
     */
    private function get_login_page_url() {
        $login_page = get_page_by_path('login');
        if ($login_page) {
            return get_permalink($login_page);
        }
        return false;
    }
    
    /**
     * Enqueue necessary scripts and styles
     */
    public function enqueue_scripts() {
		$info = [
			'messages' => [
                'loading' => __('Loading...', $this->text_domain),
                'fill_fields' => __('Please fill in all required fields', $this->text_domain),
                'success' => __('Success! Redirecting...', $this->text_domain),
			]
		];
		echo '<script>var customAuth =' . json_encode($info) . '</script>';
    }
    
    /**
     * AJAX Login Handler
     */
    public function ajax_login() {
        try {
            // Verify nonce
            if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ds1-nonce-v')) {
                wp_send_json_error([
                    'message' => __('Security check failed. Please refresh the page and try again.', $this->text_domain)
                ]);
                return;
            }
            
            // Sanitize input
            $username = sanitize_text_field($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $remember = isset($_POST['remember']) && $_POST['remember'] === 'true';
            
            // Validate input
            if (empty($username) || empty($password)) {
                wp_send_json_error([
                    'message' => __('Username and password are required.', $this->text_domain)
                ]);
                return;
            }
            
            // Attempt login
            $creds = [
                'user_login' => $username,
                'user_password' => $password,
                'remember' => $remember
            ];
            
            $user = wp_signon($creds, false);
            
            if (is_wp_error($user)) {
                wp_send_json_error([
                    'message' => $user->get_error_message()
                ]);
                return;
            }
            
            // Set auth cookie
            wp_set_auth_cookie($user->ID, $remember);
            wp_set_current_user($user->ID);
            
            // Determine redirect URL
            $redirect_url = $this->get_redirect_url($user);
            
            wp_send_json_success([
                'message' => __('Login successful! Redirecting...', $this->text_domain),
                'redirect' => $redirect_url
            ]);
            
        } catch (Exception $e) {
            wp_send_json_error([
                'message' => __('An unexpected error occurred. Please try again.', $this->text_domain)
            ]);
        }
        
        wp_die();
    }
    
    /**
     * AJAX Registration Handler
     */
    public function ajax_register() {
        // Check if registration is enabled
        if (!get_option('users_can_register')) {
            wp_send_json_error([
                'message' => __('Registration is currently disabled.', $this->text_domain)
            ]);
        }
        
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ds1-nonce-v')) {
            wp_send_json_error([
                'message' => __('Security check failed. Please refresh the page and try again.', $this->text_domain)
            ]);
        }
        
        // Sanitize input
        $username = sanitize_user($_POST['username'] ?? '');
        $email = sanitize_email($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        
        // Validate input
        if (empty($username) || empty($email) || empty($password)) {
            wp_send_json_error([
                'message' => __('All fields are required.', $this->text_domain)
            ]);
        }
        
        if ($password !== $confirm_password) {
            wp_send_json_error([
                'message' => __('Passwords do not match.', $this->text_domain)
            ]);
        }
        
        if (!is_email($email)) {
            wp_send_json_error([
                'message' => __('Please enter a valid email address.', $this->text_domain)
            ]);
        }
        
        if (username_exists($username)) {
            wp_send_json_error([
                'message' => __('Username already exists.', $this->text_domain)
            ]);
        }
        
        if (email_exists($email)) {
            wp_send_json_error([
                'message' => __('Email address already exists.', $this->text_domain)
            ]);
        }
        
        // Create user
        $user_id = wp_create_user($username, $password, $email);
        
        if (is_wp_error($user_id)) {
            wp_send_json_error([
                'message' => $user_id->get_error_message()
            ]);
        }
        
        // Auto login after registration (optional)
        $auto_login = apply_filters('custom_auth_auto_login_after_register', true);
        
        if ($auto_login) {
            wp_set_auth_cookie($user_id);
            wp_set_current_user($user_id);
            
            $user = get_user_by('id', $user_id);
            $redirect_url = $this->get_redirect_url($user);
            
            wp_send_json_success([
                'message' => __('Registration successful! Logging you in...', $this->text_domain),
                'redirect' => $redirect_url
            ]);
        } else {
            wp_send_json_success([
                'message' => __('Registration successful! Please login.', $this->text_domain),
                'redirect' => $this->get_login_page_url()
            ]);
        }
    }
    
    /**
     * Get redirect URL after login
     */
    private function get_redirect_url($user) {
        // Check for redirect_to parameter
        if (isset($_POST['redirect_to']) && !empty($_POST['redirect_to'])) {
            return esc_url_raw($_POST['redirect_to']);
        }
        
        if (isset($_GET['redirect_to']) && !empty($_GET['redirect_to'])) {
            return esc_url_raw($_GET['redirect_to']);
        }
        
        // Custom redirect function hook
        $custom_redirect = apply_filters('custom_auth_login_redirect', '', $user);
        if (!empty($custom_redirect)) {
            return $custom_redirect;
        }
        
        // Default redirects based on user role
        if (user_can($user, 'manage_options')) {
            return admin_url();
        } elseif (user_can($user, 'edit_posts')) {
            return admin_url();
        } else {
            return home_url();
        }
    }
    
    /**
     * Login Form Shortcode
     */
    public function login_form_shortcode($atts) {
        $atts = shortcode_atts([
            'redirect' => '',
            'show_register_link' => 'true'
        ], $atts);
        
        ob_start();
        
        if (is_user_logged_in()) {
            $this->render_logged_in_message($atts);
        } else {
            $this->render_login_form($atts);
        }
        
        return ob_get_clean();
    }
    
    /**
     * Register Form Shortcode
     */
    public function register_form_shortcode($atts) {
        $atts = shortcode_atts([
            'redirect' => '',
            'show_login_link' => 'true'
        ], $atts);
        
        ob_start();
        
        if (!get_option('users_can_register')) {
            echo '<p class="auth-message error">' . __('Registration is currently disabled.', $this->text_domain) . '</p>';
            return ob_get_clean();
        }
        
        if (is_user_logged_in()) {
            $this->render_logged_in_message($atts);
        } else {
            $this->render_register_form($atts);
        }
        
        return ob_get_clean();
    }
    
    /**
     * Render logged in message
     */
    private function render_logged_in_message($atts) {
        $current_user = wp_get_current_user();
        $logout_url = wp_logout_url();
        
        if (!empty($atts['redirect'])) {
            echo '<script>setTimeout(function(){ window.location.href = "' . esc_url($atts['redirect']) . '"; }, 3000);</script>';
        }
        ?>
        <div class="auth-logged-in-message">
            <h3><?php printf(__('Welcome back, %s!', $this->text_domain), $current_user->display_name); ?></h3>
            <p><?php _e('You are already logged in.', $this->text_domain); ?></p>
            <a href="<?php echo esc_url($logout_url); ?>" class="logout-link">
                <?php _e('Logout', $this->text_domain); ?>
            </a>
            <?php if (!empty($atts['redirect'])): ?>
                <p><small><?php _e('Redirecting in 3 seconds...', $this->text_domain); ?></small></p>
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Render login form
     */
    private function render_login_form($atts) {
        // Show status messages
        $this->show_status_messages();
        ?>
        <div class="custom-auth-container">
            <form id="custom-login-form" class="custom-auth-form" method="post">
                <div class="auth-field">
                    <label for="login-username"><?php _e('Username or Email', $this->text_domain); ?></label>
                    <input type="text" id="login-username" name="username" required>
                </div>
                
                <div class="auth-field">
                    <label for="login-password"><?php _e('Password', $this->text_domain); ?></label>
                    <input type="password" id="login-password" name="password" required>
                </div>
                
                <div class="auth-field checkbox">
                    <label>
                        <input type="checkbox" name="remember" value="true">
                        <?php _e('Remember me', $this->text_domain); ?>
                    </label>
                </div>
                
                <?php if (!empty($atts['redirect'])): ?>
                    <input type="hidden" name="redirect_to" value="<?php echo esc_attr($atts['redirect']); ?>">
                <?php endif; ?>
                
                <div class="auth-field">
                    <button type="submit" class="auth-submit">
                        <?php _e('Login', $this->text_domain); ?>
                    </button>
                </div>
                
                <?php wp_nonce_field('ds1-nonce-v', 'nonce'); ?>
            </form>
            
            <div class="auth-message-container"></div>
            
            <?php if ($atts['show_register_link'] === 'true' && get_option('users_can_register')): ?>
                <p class="auth-links">
                    <?php _e("Don't have an account?", $this->text_domain); ?>
                    <a href="#register"><?php _e('Register here', $this->text_domain); ?></a>
                </p>
            <?php endif; ?>
        </div>
        <?php
        $this->render_auth_styles();
        $this->render_auth_scripts();
    }
    
    /**
     * Render register form
     */
    private function render_register_form($atts) {
        ?>
        <div class="custom-auth-container">
            <form id="custom-register-form" class="custom-auth-form" method="post">
                <div class="auth-field">
                    <label for="register-username"><?php _e('Username', $this->text_domain); ?></label>
                    <input type="text" id="register-username" name="username" required>
                </div>
                
                <div class="auth-field">
                    <label for="register-email"><?php _e('Email', $this->text_domain); ?></label>
                    <input type="email" id="register-email" name="email" required>
                </div>
                
                <div class="auth-field">
                    <label for="register-password"><?php _e('Password', $this->text_domain); ?></label>
                    <input type="password" id="register-password" name="password" required>
                </div>
                
                <div class="auth-field">
                    <label for="register-confirm-password"><?php _e('Confirm Password', $this->text_domain); ?></label>
                    <input type="password" id="register-confirm-password" name="confirm_password" required>
                </div>
                
                <?php if (!empty($atts['redirect'])): ?>
                    <input type="hidden" name="redirect_to" value="<?php echo esc_attr($atts['redirect']); ?>">
                <?php endif; ?>
                
                <div class="auth-field">
                    <button type="submit" class="auth-submit">
                        <?php _e('Register', $this->text_domain); ?>
                    </button>
                </div>
                
                <?php wp_nonce_field('ds1-nonce-v', 'nonce'); ?>
            </form>
            
            <div class="auth-message-container"></div>
            
            <?php if ($atts['show_login_link'] === 'true'): ?>
                <p class="auth-links">
                    <?php _e('Already have an account?', $this->text_domain); ?>
                    <a href="#login"><?php _e('Login here', $this->text_domain); ?></a>
                </p>
            <?php endif; ?>
        </div>
        <?php
        $this->render_auth_styles();
        $this->render_register_scripts();
    }
    
    /**
     * Show status messages
     */
    private function show_status_messages() {
        $login_status = $_GET['login_status'] ?? '';
        
        switch ($login_status) {
            case 'logout':
                echo '<div class="auth-message success">' . __('You have been logged out successfully.', $this->text_domain) . '</div>';
                break;
            case 'failed':
                echo '<div class="auth-message error">' . __('Login failed. Please check your credentials.', $this->text_domain) . '</div>';
                break;
        }
    }
    
    /**
     * Render CSS styles
     */
    private function render_auth_styles() {
        static $styles_rendered = false;
        if ($styles_rendered) return;
        $styles_rendered = true;
        ?>
        <style>
        .custom-auth-container {
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .custom-auth-form .auth-field {
            margin-bottom: 20px;
        }
        
        .custom-auth-form label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .custom-auth-form input[type="text"],
        .custom-auth-form input[type="email"],
        .custom-auth-form input[type="password"] {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .custom-auth-form .checkbox label {
            font-weight: normal;
            display: flex;
            align-items: center;
        }
        
        .custom-auth-form .checkbox input {
            width: auto;
            margin-right: 8px;
        }
        
        .auth-submit {
            width: 100%;
            padding: 12px;
            background: #0073aa;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        
        .auth-submit:hover {
            background: #005a87;
        }
        
        .auth-submit:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .auth-message {
            padding: 12px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        
        .auth-message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .auth-message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .auth-links {
            text-align: center;
            margin-top: 20px;
        }
        
        .auth-logged-in-message {
            text-align: center;
            padding: 20px;
            background: #d4edda;
            color: #155724;
            border-radius: 8px;
        }
        
        .logout-link {
            display: inline-block;
            margin-top: 10px;
            padding: 8px 16px;
            background: #dc3545;
            color: white;
            text-decoration: none;
            border-radius: 4px;
        }
        
        .logout-link:hover {
            background: #c82333;
            color: white;
        }
        
        .auth-loading {
            position: relative;
        }
        
        .auth-loading::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255,255,255,0.8);
            display: flex;
            align-items: center;
            justify-content: center;
        }

		.password-wrapper {
			position: relative;
			display: inline-block;
			width: 100%;
		}
		.password-wrapper input[type="password"],
		.password-wrapper input[type="text"] {
			padding-inline-end: 40px;
			width: 100%;
  			box-sizing: border-box;
		}
		.password-toggle {
			position: absolute;
			right: 10px;
			top: 50%;
			transform: translateY(-50%);
			cursor: pointer;
			font-size: 1.1rem;
			color: #666;

			width: 20px;
			height: 20px;
			font-style: normal;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.fa-eye:before {
			content: "👁";
		}

		.hide-ppp {
			color: red;
		}

		.rtl .password-toggle {
			right: auto;
			left:10px;
		}
        </style>
        <?php
    }
    
    /**
     * Render login JavaScript
     */
    private function render_auth_scripts() {
        static $scripts_rendered = false;
        if ($scripts_rendered) return;
        $scripts_rendered = true;
        ?>
        <script>
			// password eye
			document.addEventListener("DOMContentLoaded", function () {
				// اجلب كل حقول الباسورد
				const passwordFields = document.querySelectorAll('input[type="password"]');

				passwordFields.forEach(function (field) {
					// التفاف العنصر داخل ديف
					const wrapper = document.createElement("div");
					wrapper.className = "password-wrapper";
					field.parentNode.insertBefore(wrapper, field);
					wrapper.appendChild(field);

					// زر التبديل (العين)
					const toggle = document.createElement("i");
					toggle.className = "fa-solid fa-eye password-toggle";
					toggle.setAttribute("aria-hidden", "true");
					wrapper.appendChild(toggle);

					// حدث الضغط
					toggle.addEventListener("click", function () {
					const isHidden = field.type === "password";
					field.type = isHidden ? "text" : "password";
					toggle.className = isHidden
						? "fa-solid fa-eye hide-ppp password-toggle"
						: "fa-solid fa-eye password-toggle";
					});
				});
			});

			jQuery(document).ready(function($) {
				$('#custom-login-form').on('submit', function(e) {
					e.preventDefault();
					
					var form = $(this);
					var messageContainer = $('.auth-message-container');
					var submitButton = form.find('.auth-submit');
					
					// Clear previous messages
					messageContainer.empty();
					
					// Validate form
					var username = form.find('input[name="username"]').val();
					var password = form.find('input[name="password"]').val();
					
					if (!username || !password) {
						messageContainer.html('<div class="auth-message error">' + customAuth.messages.fill_fields + '</div>');
						return;
					}
					
					// Show loading state
					submitButton.prop('disabled', true).text(customAuth.messages.loading);
					form.addClass('auth-loading');
					
					// Submit form
					$.ajax({
						url: DS1InitInfo.ajaxUrl,
						type: 'POST',
						data: form.serialize() + '&action=custom_login',
						dataType: 'json',
						success: function(response) {
							console.log('AJAX Response:', response); // Debug log
							if (response.success) {
								messageContainer.html('<div class="auth-message success">' + response.data.message + '</div>');
								if (response.data.redirect) {
									setTimeout(function() {
										window.location.href = response.data.redirect;
									}, 1000);
								}
							} else {
								var errorMsg = response.data && response.data.message ? response.data.message : 'Login failed. Please try again.';
								messageContainer.html('<div class="auth-message error">' + errorMsg + '</div>');
							}
						},
						error: function(xhr, status, error) {
							console.log('AJAX Error:', xhr.responseText); // Debug log
							messageContainer.html('<div class="auth-message error">An error occurred. Please try again. (' + error + ')</div>');
						},
						complete: function() {
							submitButton.prop('disabled', false).text('<?php echo esc_js(__('Login', $this->text_domain)); ?>');
							form.removeClass('auth-loading');
						}
					});
				});
			});
        </script>
        <?php
    }
    
    /**
     * Render register JavaScript
     */
    private function render_register_scripts() {
        ?>
        <script>
        jQuery(document).ready(function($) {
            $('#custom-register-form').on('submit', function(e) {
                e.preventDefault();
                
                var form = $(this);
                var messageContainer = $('.auth-message-container');
                var submitButton = form.find('.auth-submit');
                
                // Clear previous messages
                messageContainer.empty();
                
                // Validate form
                var username = form.find('input[name="username"]').val();
                var email = form.find('input[name="email"]').val();
                var password = form.find('input[name="password"]').val();
                var confirmPassword = form.find('input[name="confirm_password"]').val();
                
                if (!username || !email || !password || !confirmPassword) {
                    messageContainer.html('<div class="auth-message error">' + customAuth.messages.fill_fields + '</div>');
                    return;
                }
                
                if (password !== confirmPassword) {
                    messageContainer.html('<div class="auth-message error">Passwords do not match.</div>');
                    return;
                }
                
                // Show loading state
                submitButton.prop('disabled', true).text(customAuth.messages.loading);
                form.addClass('auth-loading');
                
                // Submit form
                $.ajax({
                    url: DS1InitInfo.ajaxUrl,
                    type: 'POST',
                    data: form.serialize() + '&action=custom_register',
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            messageContainer.html('<div class="auth-message success">' + response.data.message + '</div>');
                            if (response.data.redirect) {
                                setTimeout(function() {
                                    window.location.href = response.data.redirect;
                                }, 2000);
                            }
                        } else {
                            messageContainer.html('<div class="auth-message error">' + response.data.message + '</div>');
                        }
                    },
                    error: function() {
                        messageContainer.html('<div class="auth-message error">An error occurred. Please try again.</div>');
                    },
                    complete: function() {
                        submitButton.prop('disabled', false).text('<?php echo esc_js(__('Register', $this->text_domain)); ?>');
                        form.removeClass('auth-loading');
                    }
                });
            });
        });
        </script>
        <?php
    }
}

// Initialize the class
new RM_Custom_Auth_System();

/**
 * Helper functions for theme developers
 */

/**
 * Display login form
 * @param array $args Arguments for the form
 */
function display_custom_login_form($args = []) {
    $shortcode_atts = '';
    foreach ($args as $key => $value) {
        $shortcode_atts .= sprintf(' %s="%s"', $key, esc_attr($value));
    }
    echo do_shortcode('[custom_login_form' . $shortcode_atts . ']');
}

/**
 * Display register form
 * @param array $args Arguments for the form
 */
function display_custom_register_form($args = []) {
    $shortcode_atts = '';
    foreach ($args as $key => $value) {
        $shortcode_atts .= sprintf(' %s="%s"', $key, esc_attr($value));
    }
    echo do_shortcode('[custom_register_form' . $shortcode_atts . ']');
}

/**
 * Check if custom login page exists
 */
function has_custom_login_page() {
    return (bool) get_page_by_path('login');
}

/**
 * Get custom login page URL
 */
function get_custom_login_url($redirect_to = '') {
    $login_page = get_page_by_path('login');
    if (!$login_page) {
        return wp_login_url($redirect_to);
    }
    
    $url = get_permalink($login_page);
    if ($redirect_to) {
        $url = add_query_arg('redirect_to', urlencode($redirect_to), $url);
    }
    
    return $url;
}

/**
 * Example usage in themes:
 * 
 * 1. Create a page with slug 'login' for custom login page
 * 2. Use shortcodes in page content:
 *    [custom_login_form]
 *    [custom_register_form]
 * 
 * 3. Or use PHP functions in templates:
 *    display_custom_login_form(['redirect' => home_url('/dashboard')]);
 *    display_custom_register_form(['show_login_link' => 'false']);
 * 
 * 4. Custom redirect hook example:
 *    add_filter('custom_auth_login_redirect', function($redirect, $user) {
 *        if (user_can($user, 'subscriber')) {
 *            return home_url('/member-area');
 *        }
 *        return $redirect;
 *    }, 10, 2);
 */
?>