<?php
function cybreed_authenticate_user($email, $password) {
    // Sanitize and validate user input
    $email = sanitize_email($email);
    if (!is_email($email)) {
        return array('error' => 'Invalid email format');
    }
    
    $password = sanitize_text_field($password);
    if (empty($password)) {
        return array('error' => 'Password cannot be empty');
    }

    // Handles the authentication logic
    $login_url = 'https://api.cybreed.ai/login';
    $body = wp_json_encode(array('email' => $email, 'password' => $password));
    $response = wp_remote_post($login_url, array(
        'headers' => array('Content-Type' => 'application/json'),
        'body' => $body
    ));

    if (is_wp_error($response)) {
        return array('error' => 'Login Failed: ' . esc_html($response->get_error_message()));
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    if (isset($data['access_token']) && isset($data['user']['id'])) {
        return array(
            'access_token' => sanitize_text_field($data['access_token']),
            'user_id' => sanitize_text_field($data['user']['id']),
        );
    } else {
        return array('error' => 'Login failed. Please try again.');
    }
}

function cybreed_enqueue_admin_styles($hook_suffix) {
    // Load styles on both dashboard and settings pages
    if ($hook_suffix === 'toplevel_page_cybreed' || $hook_suffix === 'cybreed_page_cybreed-settings') {
        wp_enqueue_style(
            'cybreed-admin-styles',
            esc_url(plugins_url('assets/css/admin-styles.css', dirname(__DIR__, 2) . '/cybreed.php')),
            [],
            '1.0.3'
        );
    }
}
add_action('admin_enqueue_scripts', 'cybreed_enqueue_admin_styles');

function cybreed_enqueue_admin_scripts($hook_suffix) {
    // Load scripts on both dashboard and settings pages
    if ($hook_suffix === 'toplevel_page_cybreed' || $hook_suffix === 'cybreed_page_cybreed-settings') {
        // Enqueue Cybreed widget
        wp_enqueue_script(
            'cybreed-widget',
            'https://widget.cybreed.ai/cybreed.iife.js?chatVariable=b62e9830-e76f-4e52-a549-a00c43f4a9ce',
            array(),
            CYBREED_CHAT_VERSION,
            true
        );

        wp_enqueue_script(
            'cybreed-admin-scripts',
            esc_url(plugins_url('assets/js/admin-scripts.js', dirname(__DIR__, 2) . '/cybreed.php')),
            ['jquery'], // Dependencies
            '1.0.3',
            true
        );
        
        // Add type="module" to the script tag
        add_filter('script_loader_tag', function($tag, $handle) {
            if ('cybreed-admin-scripts' === $handle) {
                return str_replace('<script', '<script type="module"', $tag);
            }
            return $tag;
        }, 10, 2);
    }
}
add_action('admin_enqueue_scripts', 'cybreed_enqueue_admin_scripts');

function cybreed_enqueue_google_fonts() {
    // Only load fonts on dashboard and settings pages
    $screen = get_current_screen();
    if ($screen && ($screen->base === 'toplevel_page_cybreed' || $screen->base === 'cybreed_page_cybreed-settings')) {
        wp_enqueue_style(
            'cybreed-google-fonts',
            'https://fonts.googleapis.com/css2?family=Sora:wght@400;600;700&family=Space+Grotesk:wght@400;500;600;700&display=swap',
            array(),
            CYBREED_CHAT_VERSION
        );
    }
}
add_action('admin_enqueue_scripts', 'cybreed_enqueue_google_fonts');

// Add AJAX handler for login
function cybreed_handle_ajax_login() {
    check_ajax_referer('cybreed_login_action', 'nonce');
    
    $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
    $password = isset($_POST['password']) ? sanitize_text_field(wp_unslash($_POST['password'])) : '';
    
    if (empty($email) || empty($password)) {
        wp_send_json([
            'success' => false,
            'message' => 'Please fill in all fields.'
        ]);
    }
    
    $auth_result = cybreed_authenticate_user($email, $password);
    
    if (isset($auth_result['access_token']) && isset($auth_result['user_id'])) {
        update_option('cybreed_access_token', $auth_result['access_token']);
        update_option('cybreed_user_id', $auth_result['user_id']);
        
        wp_send_json([
            'success' => true,
            'message' => 'Login successful! Redirecting...'
        ]);
    } else {
        wp_send_json([
            'success' => false,
            'message' => isset($auth_result['error']) ? $auth_result['error'] : 'Login failed. Please try again.'
        ]);
    }
}
add_action('wp_ajax_cybreed_ajax_login', 'cybreed_handle_ajax_login');
add_action('wp_ajax_nopriv_cybreed_ajax_login', 'cybreed_handle_ajax_login');

// Add AJAX handler for logout
function cybreed_handle_ajax_logout() {
    check_ajax_referer('cybreed_logout_action', 'nonce');
    
    // Perform logout actions
    delete_option('cybreed_access_token');
    delete_option('cybreed_user_id');
    
    wp_send_json([
        'success' => true,
        'message' => 'Logged out successfully'
    ]);
}
add_action('wp_ajax_cybreed_ajax_logout', 'cybreed_handle_ajax_logout');