<?php
if (!defined('ABSPATH')) exit;

// Google OAuth config (move these to wp-config.php in production).
if (!defined('VS_GOOGLE_CLIENT_ID')) {
    define('VS_GOOGLE_CLIENT_ID', '545820790834-laapjtditrhmev00tos6e6u8es968eju.apps.googleusercontent.com');
}
if (!defined('VS_GOOGLE_CLIENT_SECRET')) {
    define('VS_GOOGLE_CLIENT_SECRET', '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');
}

// 0. Google Login (button + callback)

function vs_google_redirect_uri() {
    return admin_url('admin-ajax.php?action=google_login_callback');
}

add_action('woocommerce_login_form', 'vs_add_google_login_button');
function vs_add_google_login_button() {
    if (is_user_logged_in()) return;
    static $style_printed = false;

    $redirect_uri = vs_google_redirect_uri();
    $state = wp_create_nonce('vs_google_state');

    $auth_url = add_query_arg([
        'client_id' => VS_GOOGLE_CLIENT_ID,
        'redirect_uri' => $redirect_uri,
        'response_type' => 'code',
        'scope' => 'openid email profile',
        'access_type' => 'online',
        'prompt' => 'select_account',
        'state' => $state,
    ], 'https://accounts.google.com/o/oauth2/v2/auth');

    if (!$style_printed) {
        $style_printed = true;
        echo '<style>
        .vs-google-login {
            text-align: center;
            margin: 20px 0;
        }

        .vs-google-button {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: #fff;
            border: 1px solid #ddd;
            padding: 10px 16px;
            border-radius: 4px;
            font-family: \'Roboto\', sans-serif;
            font-size: 14px;
            color: #555;
            text-decoration: none;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: background 0.3s, box-shadow 0.3s;
        }
        .vs-google-button:hover {
            background: #f7f7f7;
            box-shadow: 0 4px 6px rgba(0,0,0,0.15);
        }

        .vs-google-icon {
            width: 18px;
            height: 18px;
        }

        .vs-google-text {
            font-weight: 500;
        }
        </style>';
    }

    echo '<div class="vs-google-login">';
    echo '<a class="vs-google-button" href="' . esc_url($auth_url) . '">';
    echo '<img src="' . plugin_dir_url(__FILE__) . 'google.png" alt="G" class="vs-google-icon">';
    echo '<span class="vs-google-text" style="color:black">' . esc_html__('Continue with Google', 'vendor-space') . '</span>';
    echo '</a>';
    echo '</div>';
}

// Hook for logged-in users: handle Google login callback
add_action('wp_ajax_google_login_callback', 'vs_handle_google_login');

// Hook for non-logged-in users: handle Google login callback
add_action('wp_ajax_nopriv_google_login_callback', 'vs_handle_google_login');

add_filter('authenticate', 'vs_block_vendor_login', 30, 3);

function vs_block_vendor_login($user, $username, $password) {
    if (is_wp_error($user)) {
        return $user;
    }

    if ($user instanceof WP_User) {
        $status = get_user_meta($user->ID, 'vs_vendor_status', true);

       if ($status === 'pending') {
    $message = __('Your account is pending approval by the administrator. It will be activated once your request is approved. Thank you for your patience.', 'vendor-space');
    error_log('[VS] Login blocked - pending account: ' . $user->user_email);
    return new WP_Error('pending_approval', $message);

} elseif ($status === 'rejected') {
    $message = __('Your account request has been rejected. Please contact the support team for more information.', 'vendor-space');
    error_log('[VS] Login blocked - rejected account: ' . $user->user_email);
    return new WP_Error('rejected_account', $message);

} elseif ($status === 'deleted') {
    $message = __('Your account has been closed and you cannot log in. Please contact the support team.', 'vendor-space');
    error_log('[VS] Login blocked - deleted account: ' . $user->user_email);
    return new WP_Error('blocked_account', $message);
}
    }

    return $user;
}

function vs_handle_google_login() {
    // Check if 'code' and 'state' exist in the URL
    if (empty($_GET['code']) || empty($_GET['state'])) return;

    // Verify the nonce to protect against CSRF attacks
    if (!wp_verify_nonce(sanitize_text_field($_GET['state']), 'vs_google_state')) {
        wc_add_notice(__('Google login validation failed.', 'vendor-space'), 'error');
        return;
    }

    $redirect_uri = vs_google_redirect_uri();
    $code = sanitize_text_field(wp_unslash($_GET['code']));

    $token_res = wp_remote_post('https://oauth2.googleapis.com/token', [
        'timeout' => 20,
        'body' => [
            'code' => $code,
            'client_id' => VS_GOOGLE_CLIENT_ID,
            'client_secret' => VS_GOOGLE_CLIENT_SECRET,
            'redirect_uri' => $redirect_uri,
            'grant_type' => 'authorization_code',
        ],
    ]);

    if (is_wp_error($token_res)) {
        wc_add_notice(__('Google login failed. Please try again.', 'vendor-space'), 'error');
        return;
    }

    $token_body = json_decode(wp_remote_retrieve_body($token_res), true);
    $access_token = isset($token_body['access_token']) ? $token_body['access_token'] : '';

    if (!$access_token) {
        wc_add_notice(__('Google login failed. Access token not received.', 'vendor-space'), 'error');
        return;
    }

    $user_res = wp_remote_get('https://openidconnect.googleapis.com/v1/userinfo', [
        'timeout' => 20,
        'headers' => [
            'Authorization' => 'Bearer ' . $access_token,
        ],
    ]);

    if (is_wp_error($user_res)) {
        wc_add_notice(__('Google login failed. Please try again.', 'vendor-space'), 'error');
        return;
    }

    $user_body = json_decode(wp_remote_retrieve_body($user_res), true);
    $email = isset($user_body['email']) ? sanitize_email($user_body['email']) : '';
    $name = isset($user_body['name']) ? sanitize_text_field($user_body['name']) : '';

    if (!$email) {
        wc_add_notice(__('Google login failed. Email not found.', 'vendor-space'), 'error');
        return;
    }

    $user = get_user_by('email', $email);

    if ($user) {
        $vendor_status = get_user_meta($user->ID, 'vs_vendor_status', true);

        // Full account status check
        if ($vendor_status === 'pending') {
            $message = __('Your account is still pending admin approval. Please wait or contact support.', 'vendor-space');
            wc_add_notice($message, 'error');
            error_log('[VS] Google login blocked - pending account: ' . $email);
            wp_safe_redirect(wc_get_page_permalink('myaccount'));
            exit;

        } elseif ($vendor_status === 'rejected') {
            $message = __('Your account has been rejected. Please contact support for more information.', 'vendor-space');
            wc_add_notice($message, 'error');
            error_log('[VS] Google login blocked - rejected account: ' . $email);
            wp_safe_redirect(wc_get_page_permalink('myaccount'));
            exit;

        } elseif ($vendor_status === 'deleted') {
            $message = __('Your account is disabled. Please contact support.', 'vendor-space');
            wc_add_notice($message, 'error');
            error_log('[VS] Google login blocked - deleted account: ' . $email);
            wp_safe_redirect(wc_get_page_permalink('myaccount'));
            exit;
        }
    }

    if (!$user) {
        $base = sanitize_user(current(explode('@', $email)), true);
        $username = $base ?: 'googleuser';
        $i = 1;

        while (username_exists($username)) {
            $username = $base . $i;
            $i++;
        }

        $password = wp_generate_password(20, true);
        $user_id = wp_create_user($username, $password, $email);

        if (is_wp_error($user_id)) {
            wc_add_notice(__('Google login failed. Could not create account.', 'vendor-space'), 'error');
            return;
        }

        if ($name) {
            wp_update_user([
                'ID' => $user_id,
                'display_name' => $name
            ]);
        }

        $user = get_user_by('id', $user_id);

        if ($user && $user instanceof WP_User) {
            $user->set_role('customer');
        }
    }

    wp_set_current_user($user->ID);
    wp_set_auth_cookie($user->ID, true);
    wp_safe_redirect(wc_get_page_permalink('myaccount'));
    exit;
}

// 1. Add fields to the registration form
add_action('woocommerce_register_form', 'vs_add_registration_fields');
function vs_add_registration_fields() {
    ?>
    <?php $vs_gen_pw = (get_option('woocommerce_registration_generate_password') === 'yes'); ?>
    <div class="vs-registration-fields" style="margin-bottom: 20px; padding: 15px; border-radius: none; border: none;">
        <p class="form-row form-row-wide">
                <label for="reg_display_name"><?php echo esc_html__('Display Name', 'vendor-space'); ?> <span class="required">*</span></label>
                <input type="text" class="input-text" name="display_name" id="reg_display_name" required />
            </p>
       <?php if ($vs_gen_pw): ?>
        <p class="form-row form-row-wide">
            <label for="reg_password"><?php echo esc_html__('Password', 'vendor-space'); ?> <span class="required">*</span></label>
            <span class="vs-pass-wrap">
                <input type="password" class="input-text" name="password" id="reg_password" required />
            </span>
        </p>
        <?php endif; ?>
        <p class="form-row form-row-wide">
            <label for="reg_password2"><?php echo esc_html__('Confirm Password', 'vendor-space'); ?> <span class="required">*</span></label>
            <span class="vs-pass-wrap">
                <input type="password" class="input-text" name="password2" id="reg_password2" required />
            </span>
        </p>

           
        <div id="vs_customer_optional_fields" style="margin-top:15px; border-top:1px solid #ddd; padding-top:15px;">
         <p class="form-row form-row-wide">
                <label for="reg_phone"><?php echo esc_html__('Phone Number', 'vendor-space'); ?></label>
                <input type="tel" class="input-text" name="phone" id="reg_phone" />
            </p>   
            <p class="form-row form-row-wide">
                <label for="reg_billing_address_1"><?php echo esc_html__('Address', 'vendor-space'); ?></label>
                <input type="text" class="input-text" name="billing_address_1" id="reg_billing_address_1" />
            </p>
        </div>

        <div id="vs_vendor_fields" style="display:none; margin-top:15px; border-top:1px solid #ddd; padding-top:15px;">
            <p class="form-row form-row-wide">
                <label for="reg_shop_name"><?php echo esc_html__('Store Name', 'vendor-space'); ?> <span class="required">*</span></label>
                <input type="text" class="input-text" name="shop_name" id="reg_shop_name" required/>
            </p>
            
            <p class="form-row form-row-wide">
                <label for="reg_shop_url"><?php echo esc_html__('Store URL Slug', 'vendor-space'); ?></label>
                <input type="text" class="input-text" name="shop_url" id="reg_shop_url" placeholder="<?php echo esc_attr__('e.g. my-awesome-shop', 'vendor-space'); ?>" />
            </p>

          
        </div>
         <label style="font-weight:bold; display:block; margin-bottom:10px;"><?php echo esc_html__('Register as', 'vendor-space'); ?></label>
        
        <label style="margin-right: 15px; cursor:pointer;">
            <input type="radio" name="account_type" value="customer" checked onchange="toggleVendorFields()"> <?php echo esc_html__('Customer', 'vendor-space'); ?>
        </label>
        <label style="cursor:pointer;">
            <input type="radio" name="account_type" value="vendor" onchange="toggleVendorFields()"> <?php echo esc_html__('Vendor', 'vendor-space'); ?>
        </label>

    </div>

    <script>
        function toggleVendorFields() {
            var isVendor = document.querySelector('input[name="account_type"][value="vendor"]').checked;
            var fields = document.getElementById('vs_vendor_fields');
            var shopName = document.getElementById('reg_shop_name');
            if (!fields) return;
            if (isVendor) {
                fields.style.display = 'block';
                if (shopName) shopName.setAttribute('required', 'required');
            } else {
                fields.style.display = 'none';
                if (shopName) shopName.removeAttribute('required');
            }
        }
        document.addEventListener('DOMContentLoaded', toggleVendorFields);
    </script>

    <?php
}

require_once __DIR__ . '/registration-otp.php';

add_filter('woocommerce_email_subject_customer_new_account', function () {
    return __('Welcome to Our Marketplace', 'vendor-space');
});
