<?php
// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Check if user is logged into WordPress
if (!is_user_logged_in()) {
    ?>
    <div class="aysa-login-container">
        <div class="aysa-login-header">
            <img src="<?php echo esc_url(AYSA_PLUGIN_URL . 'assets/images/aysa-logo.png'); ?>" alt="Aysa.ai Logo" class="aysa-logo">
            <h1>WordPress Login Required</h1>
            <p>You must be logged into WordPress to use Aysa.ai</p>
        </div>
        
        <div class="aysa-login-form-container">
            <div class="aysa-login-error">
                <p><strong>WordPress login required:</strong> Please <a href="<?php echo esc_url(wp_login_url(admin_url('admin.php?page=aysa-login'))); ?>">log into WordPress</a> first to authenticate with Aysa.ai.</p>
                <p class="aysa-login-subnote">This ensures your Aysa authentication is tied to your WordPress account and persists across devices.</p>
            </div>
        </div>
    </div>
    <?php
    return;
}

?>

<div class="aysa-login-container">
    <div class="aysa-login-header">
        <img src="<?php echo esc_url(AYSA_PLUGIN_URL . 'assets/images/aysa-logo.png'); ?>" alt="Aysa.ai Logo" class="aysa-logo">
        <h1>Log in to Aysa.ai</h1>
        <p>Enter your secret key to access the Aysa.ai dashboard</p>
        <div class="wp-user-info">
            <small>Logged in as: <strong><?php echo esc_html(wp_get_current_user()->display_name); ?></strong></small>
        </div>
    </div>
    
    <div class="aysa-login-offer aysa-login-offer-box">
        <strong>Start your 30-day free trial – no credit card required</strong><br>
        <span class="aysa-login-offer-text">Unlock the full power of Aysa AI and see how effortless SEO can be.<br>
        Automated keywords, content, links, and signals – all in one smart plugin.</span><br>
        <span class="aysa-login-offer-line">
            <span class="aysa-login-offer-icon">🔐</span> <em class="aysa-login-offer-em">No commitment. No hidden fees. Just better rankings.</em>
        </span>
        <span class="aysa-login-offer-line">
            <span class="aysa-login-offer-icon">👉</span> <a href="https://app.aysa.ai/" target="_blank" rel="noopener noreferrer" class="aysa-login-offer-link">Click here</a> to get your activation key and connect AYSA.
        </span>
    </div>
    
    <div class="aysa-login-form-container">
        <form id="aysa-login-form" method="post" action="">
            <div class="aysa-form-group">
                <label for="aysa-secret-key">Secret Key</label>
                <input type="password" id="aysa-secret-key" name="aysa-secret-key" placeholder="Enter your secret key" required>
            </div>
            
            <div class="aysa-form-group">
                <button type="submit" id="aysa-login-btn" class="aysa-btn aysa-btn-primary">Access Dashboard</button>
            </div>
        </form>
        
        <div id="aysa-login-error" class="aysa-login-error aysa-hidden">
            <p>Invalid secret key or domain. Please check your credentials and try again.</p>
        </div>
        
        <div id="aysa-api-error" class="aysa-login-error aysa-hidden">
            <p>Unable to connect to Aysa.ai service. Please try again later or contact support.</p>
        </div>
        
        <div id="aysa-detailed-error" class="aysa-login-error aysa-hidden">
            <h4>Error Details:</h4>
            <div id="error-message"></div>
            <div id="error-details" class="aysa-login-error-details"></div>
        </div>
    </div>
</div>

<script>
// Define aysa_ajax for authentication calls
window.aysa_ajax = {
    ajax_url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
    nonce: '<?php echo esc_attr(wp_create_nonce('aysa-ajax-nonce')); ?>'
};

// Helper function to show detailed error
function showDetailedError(message, details = null) {
    console.error('Aysa Auth Error:', message, details);
    
    // Hide other error divs
    $('#aysa-login-error, #aysa-api-error').hide();
    
    // Show detailed error
    $('#error-message').html('<p><strong>' + message + '</strong></p>');
    
    if (details) {
        let detailsHtml = '<p><strong>Technical Details:</strong></p><ul>';
        
        if (typeof details === 'object') {
            for (let key in details) {
                if (details.hasOwnProperty(key)) {
                    detailsHtml += '<li><strong>' + key + ':</strong> ' + details[key] + '</li>';
                }
            }
        } else {
            detailsHtml += '<li>' + details + '</li>';
        }
        
        detailsHtml += '</ul>';
        $('#error-details').html(detailsHtml);
    } else {
        $('#error-details').empty();
    }
    
    $('#aysa-detailed-error').show();
}

jQuery(document).ready(function($) {
    console.log('Document ready, checking AysaAPI...');
    console.log('AysaAPI type:', typeof AysaAPI);
    
    if (typeof AysaAPI !== 'undefined') {
        console.log('AysaAPI object:', AysaAPI);
        console.log('AysaAPI.checkAuthStatus type:', typeof AysaAPI.checkAuthStatus);
        console.log('Available AysaAPI methods:', Object.keys(AysaAPI));
    }
    
    // If checkAuthStatus doesn't exist, add it using AJAX directly
    if (typeof AysaAPI !== 'undefined' && typeof AysaAPI.checkAuthStatus !== 'function') {
        console.log('Adding missing checkAuthStatus function...');
        
        AysaAPI.checkAuthStatus = function() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: window.aysa_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'aysa_get_auth_status',
                        nonce: window.aysa_ajax.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            resolve(response.data);
                        } else {
                            reject(new Error(response.data || 'Status check failed'));
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('[AysaAPI] Auth status check failed:', { status, error });
                        reject(new Error('Network error during auth status check'));
                    }
                });
            });
        };
        
        AysaAPI.verifySecretKey = function(secretKey, domain) {
            return new Promise((resolve, reject) => {
                console.log('Making AJAX call with:', {
                    action: 'aysa_verify_secret_key',
                    secret_key: secretKey.substring(0, 10) + '...',
                    domain: domain,
                    nonce: window.aysa_ajax.nonce.substring(0, 10) + '...',
                    ajax_url: window.aysa_ajax.ajax_url
                });
                
                $.ajax({
                    url: window.aysa_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'aysa_verify_secret_key',
                        secret_key: secretKey,
                        domain: domain,
                        nonce: window.aysa_ajax.nonce
                    },
                    success: function(response) {
                        console.log('AJAX success response:', response);
                        
                        if (response.success) {
                            console.log('[AysaAPI] Authentication successful:', response.data);
                            resolve(response.data);
                        } else {
                            console.error('Backend returned error:', response.data);
                            reject(new Error(response.data || 'Verification failed'));
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('[AysaAPI] AJAX error:', { 
                            status, 
                            error,
                            responseText: xhr.responseText,
                            statusCode: xhr.status
                        });
                        reject(new Error('Network error during verification'));
                    }
                });
            });
        };
        
        console.log('Added missing authentication functions to AysaAPI');
    }
    
    // Temporary behavior for testing: keep login manual, no auto-redirect on page load.
    const aysaAutoRedirectAfterStatusCheck = false;

    // Wait for AysaAPI to be available with longer timeout
    function waitForAysaAPI(attempts = 0) {
        console.log('Waiting for AysaAPI, attempt:', attempts);
        
        if (typeof AysaAPI !== 'undefined' && typeof AysaAPI.checkAuthStatus === 'function') {
            console.log('AysaAPI is ready!');
            
            // Check if already authenticated on page load
            AysaAPI.checkAuthStatus()
                .then(function(authStatus) {
                    console.log('Auth status check result:', authStatus);
                    if (authStatus.authenticated && aysaAutoRedirectAfterStatusCheck) {
                        // Already authenticated, redirect to dashboard
                        window.location.href = 'admin.php?page=aysa-dashboard';
                        return;
                    }
                })
                .catch(function(error) {
                    console.log('Auth status check failed, showing login form:', error);
                });
        } else if (attempts < 50) { // Wait up to 5 seconds
            setTimeout(function() {
                waitForAysaAPI(attempts + 1);
            }, 100);
        } else {
            console.error('AysaAPI failed to load after 5 seconds');
        }
    }
    
    // Start waiting for AysaAPI
    waitForAysaAPI();
    
    $('#aysa-login-form').on('submit', function(e) {
        e.preventDefault();
        
        const secretKey = $('#aysa-secret-key').val();
        const currentDomain = window.location.hostname;
        
        // Show loading state
        $('#aysa-login-btn').text('Verifying...').prop('disabled', true);
        
        // Hide any previous error messages
        $('#aysa-login-error, #aysa-api-error').hide();
        
        // Make direct AJAX call to WordPress instead of using AysaAPI
        $.ajax({
            url: window.aysa_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_verify_secret_key',
                secret_key: secretKey,
                domain: currentDomain,
                nonce: window.aysa_ajax.nonce
            },
            success: function(response) {
                console.log('Direct AJAX success response:', response);
                
                if (response.success) {
                    console.log('Authentication successful:', response.data);
                    // Redirect to welcome page
                    window.location.href = 'admin.php?page=aysa-welcome';
                } else {
                    console.error('Backend returned error:', response.data);
                    
                    // Show specific error message with details
                    $('#aysa-login-error, #aysa-api-error').hide();
                    
                    let errorMessage = response.data || 'Authentication failed';
                    let errorHtml = '<p><strong>Error:</strong> ' + errorMessage + '</p>';
                    
                    // Add more details if available
                    if (response.data_details) {
                        errorHtml += '<p><strong>Details:</strong> ' + response.data_details + '</p>';
                    }
                    
                    $('#aysa-api-error').html(errorHtml).show();
                    $('#aysa-login-btn').text('Access Dashboard').prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                console.error('Direct AJAX error:', { 
                    status, 
                    error,
                    responseText: xhr.responseText,
                    statusCode: xhr.status
                });
                
                $('#aysa-login-error, #aysa-api-error').hide();
                
                let errorMessage = 'Network error during verification';
                let errorDetails = [];
                
                if (xhr.status) {
                    errorDetails.push('HTTP Status: ' + xhr.status);
                }
                if (status) {
                    errorDetails.push('Status: ' + status);
                }
                if (error) {
                    errorDetails.push('Error: ' + error);
                }
                if (xhr.responseText && xhr.responseText.trim()) {
                    try {
                        let parsed = JSON.parse(xhr.responseText);
                        if (parsed.data) {
                            errorDetails.push('Server Response: ' + parsed.data);
                        }
                    } catch (e) {
                        if (xhr.responseText.length < 200) {
                            errorDetails.push('Server Response: ' + xhr.responseText);
                        }
                    }
                }
                
                let errorHtml = '<p><strong>' + errorMessage + '</strong></p>';
                if (errorDetails.length > 0) {
                    errorHtml += '<p><strong>Technical Details:</strong></p><ul>';
                    errorDetails.forEach(function(detail) {
                        errorHtml += '<li>' + detail + '</li>';
                    });
                    errorHtml += '</ul>';
                }
                
                $('#aysa-api-error').html(errorHtml).show();
                $('#aysa-login-btn').text('Access Dashboard').prop('disabled', false);
            }
        });
    });
});
</script>

<style>
.aysa-login-container {
    max-width: 500px;
    margin: 50px auto;
    background-color: white;
    border-radius: 10px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.aysa-login-header {
    text-align: center;
    padding: 30px;
    background-color: #f5f8ff;
}

.aysa-logo {
    max-width: 120px;
    margin-bottom: 20px;
}

.aysa-login-header h1 {
    font-size: 24px;
    margin: 0 0 10px;
    color: #333;
}

.aysa-login-header p {
    color: #666;
    margin: 0;
}

.wp-user-info {
    margin-top: 10px;
    padding: 8px 12px;
    background-color: #e8f4fd;
    border-radius: 4px;
    border: 1px solid #d0e8f5;
}

.wp-user-info small {
    color: #0073aa;
    font-size: 13px;
}

.aysa-login-form-container {
    padding: 30px;
}

.aysa-form-group {
    margin-bottom: 20px;
}

.aysa-form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #444;
}

.aysa-form-group input {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    box-sizing: border-box;
}

.aysa-form-group input:focus {
    border-color: #0073aa;
    outline: none;
    box-shadow: 0 0 0 1px #0073aa;
}

.aysa-btn {
    display: block;
    width: 100%;
    padding: 12px;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    text-align: center;
}

.aysa-btn-primary {
    background-color: #0073aa;
    color: white;
}

.aysa-btn-primary:hover {
    background-color: #005f8b;
}

.aysa-btn:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

.aysa-login-error {
    background-color: #fdeeee;
    border-left: 4px solid #dc3232;
    padding: 12px;
    margin-top: 20px;
    color: #dc3232;
}
</style> 
