<?php 

if ( ! defined( 'ABSPATH' ) ) exit;
/**
 * Shortcode for Custom Registration Page with Password Confirmation
 * Usage: [afdp_registration]
 */
add_shortcode('afdp_registration', 'afdp_registration_shortcode');

function afdp_registration_shortcode() {
    
    // 1. IF LOGGED IN: REDIRECT TO CHECKOUT
    if (is_user_logged_in()) {
        $checkout_url = home_url('/afdp-checkout/'); // Ensure this matches your checkout slug
        echo "<script>window.location.href='" . esc_url($checkout_url) . "';</script>";
        return '<div style="text-align:center; padding:100px; font-family:sans-serif; color:#64748b;">Redirecting to checkout...</div>';
    }

    $afdp_errors = [];

    // 2. Handle registration logic
    $afdp_request_method = isset($_SERVER['REQUEST_METHOD']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD'])) : '';

    if ($afdp_request_method === 'POST' && isset($_POST['afdp_register_nonce'])) {
        if (wp_verify_nonce(sanitize_key(wp_unslash($_POST['afdp_register_nonce'])), 'afdp_user_register')) {
            
            // Unslash and Sanitize
            $afdp_username   = isset($_POST['username']) ? sanitize_user(wp_unslash($_POST['username'])) : '';
            $afdp_email      = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
            $afdp_password   = isset($_POST['password']) ? wp_unslash($_POST['password']) : '';
            $afdp_confirm_password = isset($_POST['confirm_password']) ? wp_unslash($_POST['confirm_password']) : '';
            $afdp_full_name  = isset($_POST['full_name']) ? sanitize_text_field(wp_unslash($_POST['full_name'])) : '';
            $afdp_phone      = isset($_POST['phone']) ? sanitize_text_field(wp_unslash($_POST['phone'])) : '';
            $afdp_address    = isset($_POST['address']) ? sanitize_textarea_field(wp_unslash($_POST['address'])) : '';

            // Validation
            if (empty($afdp_username) || username_exists($afdp_username)) {
                $afdp_errors[] = "Username is invalid or already taken.";
            }
            if (!is_email($afdp_email)) {
                $afdp_errors[] = "Please enter a valid email.";
            } elseif (email_exists($afdp_email)) {
                $afdp_errors[] = "This email is already registered.";
            }
            if (strlen($afdp_password) < 6) {
                $afdp_errors[] = "Password must be at least 6 characters.";
            }
            if ($afdp_password !== $afdp_confirm_password) {
                $afdp_errors[] = "Passwords do not match.";
            }
            if (empty($afdp_phone)) {
                $afdp_errors[] = "Phone number is required for delivery.";
            }

            if (empty($afdp_errors)) {
                $afdp_user_id = wp_create_user($afdp_username, $afdp_password, $afdp_email);
                
                if (!is_wp_error($afdp_user_id)) {
                    wp_update_user([
                        'ID'           => $afdp_user_id,
                        'display_name' => $afdp_full_name,
                        'first_name'   => $afdp_full_name
                    ]);
                    
                    update_user_meta($afdp_user_id, 'phone', $afdp_phone);
                    update_user_meta($afdp_user_id, 'address', $afdp_address);
                    update_user_meta($afdp_user_id, 'afdp_user_phone', $afdp_phone);
                    update_user_meta($afdp_user_id, 'afdp_user_address', $afdp_address);
                    
                    wp_set_current_user($afdp_user_id);
                    wp_set_auth_cookie($afdp_user_id);
                    
                    wp_safe_redirect(home_url('/afdp-checkout/'));
                    exit;
                } else {
                    $afdp_errors[] = $afdp_user_id->get_error_message();
                }
            }
        }
    }

    ob_start();
    ?>

    <style>
        .afdp-reg-wrapper { padding: 40px 0; background: #f8fafc; font-family: 'Plus Jakarta Sans', sans-serif; }
        .afdp-reg-card { max-width: 1000px; margin: 0 auto; background: #fff; border-radius: 24px; overflow: hidden; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); }
        .afdp-reg-info-side { background: linear-gradient(135deg, #FF385C 0%, #E31C5F 100%); padding: 50px; color: #fff; display: flex; flex-direction: column; justify-content: center; }
        .afdp-reg-form-side { padding: 50px; }
        .afdp-reg-title { font-size: 32px; font-weight: 800; color: #0f172a; letter-spacing: -1px; }
        .afdp-form-label { display: block; font-weight: 700; color: #64748b; margin-bottom: 8px; font-size: 14px; }
        .afdp-form-control { width: 100%; padding: 12px 18px; border: 2px solid #e2e8f0; border-radius: 12px; font-size: 15px; outline: none; transition: 0.3s; }
        .afdp-form-control:focus { border-color: #FF385C; }
        .afdp-reg-btn { width: 100%; background: #0f172a; color: white; border: none; padding: 18px; border-radius: 15px; font-weight: 800; font-size: 16px; cursor: pointer; transition: 0.3s; margin-top: 20px; }
        .afdp-reg-btn:hover { background: #000; transform: translateY(-2px); }
        .afdp-login-link { color: #FF385C; text-decoration: none; font-weight: 700; }
        .afdp-alert-error-list { background: #fff1f2; border: 1px solid #fecaca; padding: 20px; border-radius: 12px; color: #e11d48; font-weight: 600; }
        .afdp-error-item { margin: 0; font-size: 14px; }
    </style>

    <div class="afdp-reg-wrapper">
        <div class="afdp-reg-card">
            <div style="display: flex; flex-wrap: wrap;">
                <div class="afdp-reg-info-side" style="flex: 1 1 300px;">
                    <h3 style="color:#fff; font-size: 28px; font-weight: 800;">Welcome!</h3>
                    <p style="color:rgba(255,255,255,0.9); margin-top: 15px;">Create an account to track your delicious orders and get faster delivery.</p>
                    <ul style="margin-top: 30px; list-style: none; padding: 0;">
                        <li style="margin-bottom: 15px;"><span class="dashicons dashicons-yes-alt" style="margin-right: 10px;"></span> Save Multiple Addresses</li>
                        <li style="margin-bottom: 15px;"><span class="dashicons dashicons-yes-alt" style="margin-right: 10px;"></span> One-click Ordering</li>
                        <li style="margin-bottom: 15px;"><span class="dashicons dashicons-yes-alt" style="margin-right: 10px;"></span> Exclusive Discounts</li>
                    </ul>
                </div>
                
                <div class="afdp-reg-form-side" style="flex: 1 1 500px;">
                    <h2 class="afdp-reg-title mb-4">Register</h2>
                    
                    <?php if (!empty($afdp_errors)): ?>
                        <div class="afdp-alert-error-list mb-4">
                            <?php foreach ($afdp_errors as $afdp_error) : ?>
                                <p class="afdp-error-item">• <?php echo esc_html($afdp_error); ?></p>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <form method="post" id="afdp-registrationForm">
                        <?php wp_nonce_field('afdp_user_register', 'afdp_register_nonce'); ?>
                        
                        <div style="display:flex; gap: 20px; margin-bottom: 20px;">
                            <div style="flex:1;">
                                <label class="afdp-form-label">Full Name</label>
                                <input type="text" name="full_name" class="afdp-form-control" placeholder="John Doe" required value="<?php echo isset($_POST['full_name']) ? esc_attr(wp_unslash($_POST['full_name'])) : ''; ?>">
                            </div>
                            <div style="flex:1;">
                                <label class="afdp-form-label">Phone Number</label>
                                <input type="tel" name="phone" class="afdp-form-control" placeholder="01XXX XXXXXX" required value="<?php echo isset($_POST['phone']) ? esc_attr(wp_unslash($_POST['phone'])) : ''; ?>">
                            </div>
                        </div>

                        <div style="display:flex; gap: 20px; margin-bottom: 20px;">
                            <div style="flex:1;">
                                <label class="afdp-form-label">Username</label>
                                <input type="text" name="username" class="afdp-form-control" placeholder="johndoe12" required value="<?php echo isset($_POST['username']) ? esc_attr(wp_unslash($_POST['username'])) : ''; ?>">
                            </div>
                            <div style="flex:1;">
                                <label class="afdp-form-label">Email Address</label>
                                <input type="email" name="email" class="afdp-form-control" placeholder="john@example.com" required value="<?php echo isset($_POST['email']) ? esc_attr(wp_unslash($_POST['email'])) : ''; ?>">
                            </div>
                        </div>

                        <div style="margin-bottom: 20px;">
                            <label class="afdp-form-label">Delivery Address</label>
                            <textarea name="address" class="afdp-form-control" rows="2" placeholder="House No, Street, City..." required><?php echo isset($_POST['address']) ? esc_textarea(wp_unslash($_POST['address'])) : ''; ?></textarea>
                        </div>

                        <div style="display:flex; gap: 20px; margin-bottom: 20px;">
                            <div style="flex:1;">
                                <label class="afdp-form-label">Choose Password</label>
                                <input type="password" name="password" class="afdp-form-control" placeholder="••••••••" required>
                            </div>
                            <div style="flex:1;">
                                <label class="afdp-form-label">Confirm Password</label>
                                <input type="password" name="confirm_password" class="afdp-form-control" placeholder="••••••••" required>
                            </div>
                        </div>

                        <button type="submit" class="afdp-reg-btn">Create My Account</button>
                    </form>

                    <div style="text-align: center; margin-top: 30px; border-top: 1px solid #f1f5f9; padding-top: 20px;">
                        <span class="text-muted">Already have an account?</span> 
                        <a href="<?php echo esc_url(home_url('/afdp-login')); ?>" class="afdp-login-link">Login here</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php
    return ob_get_clean();
}