<?php
function cybreed_auth_dashboard_init() {
    function cybreed_auth_dashboard_page() {
        $access_token = get_option('cybreed_access_token', '');
        $user_id = get_option('cybreed_user_id', '');

        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST') {
            if (isset($_POST['logout_submit'])) {
                // Handle non-AJAX fallback
                check_admin_referer('cybreed_logout_action', 'cybreed_logout_nonce');
                delete_option('cybreed_access_token');
                delete_option('cybreed_user_id');
                wp_safe_redirect(admin_url('admin.php?page=cybreed&logout=success'));
                exit;
            } elseif (isset($_POST['login_submit'])) {
                check_admin_referer('cybreed_login_action', 'cybreed_login_nonce');
                $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
                $password = isset($_POST['password']) ? sanitize_text_field(wp_unslash($_POST['password'])) : '';
                $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']);
                    $access_token = $auth_result['access_token'];
                    $user_id = $auth_result['user_id'];
                    echo '<div class="updated"><p>Login successful.</p></div>';
                } else {
                    echo '<div class="error"><p>An error occurred. Please try again.</p></div>';
                }
            }
        }

        if (!$access_token) {
            // Show logout success message if redirected after logout
            if (isset($_GET['logout']) && $_GET['logout'] === 'success') {
                echo '<div class="updated"><p>You have been logged out successfully.</p></div>';
            }
            ?>
            <div class="cybreed-dashboard-wrapper">
                <div id="cybreed-logo">
                    <?php 
                    $logo_id = attachment_url_to_postid(plugins_url('assets/images/logo.svg', dirname(__DIR__, 2) . '/cybreed.php'));
                    if ($logo_id) {
                        echo wp_get_attachment_image($logo_id, 'full', false, array('alt' => 'CyBreed'));
                    } else {
                        // Fallback if image is not in media library
                        echo '<img src="' . esc_url(plugins_url('assets/images/logo.svg', dirname(__DIR__, 2) . '/cybreed.php')) . '" alt="' . esc_attr('CyBreed') . '" />';
                    }
                    ?>
                </div>

                <div class="cybreed-dashboard-inner-wrapper">
                    <h1 class="cybreed-dashboard-header">The future of AI is here</h1>
                    <h2 class="cybreed-dashboard-subheader">You train your own AI Breed to suit your needs. </h2>
                    
                    <div class="cybreed-auth-container">
                        <div class="cybreed-auth-card cybreed-login-card">
                            <h3>Already have an account?</h3>
                            <p>Sign in to access your dashboard and manage your Cybreed settings.</p>
                            <a href="#" class="cybreed-button">Sign In</a>
                        </div>

                        <div class="cybreed-auth-card" onclick="window.open('https://app.cybreed.ai/register/', '_blank')">
                            <h3>New to Cybreed?</h3>
                            <p>Create an account to get started with our amazing features and services.</p>
                            <a href="https://app.cybreed.ai/register/" target="_blank" class="cybreed-button">Register Now</a>
                        </div>
                    </div>
                    <div class="join-us">
                        <h2>Join our community: </h2>
                        <div class="comunity-wrapper">
                            <div>
                                <a href="https://x.com/cybreedAI" target="_blank" title="CyBreed's X">
                                    <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-dnmrzs r-bnwqim r-lrvibr r-m6rgpd r-lrsllp r-1nao33i r-16y2uox r-8kz0gk"><g><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"></path></g></svg>
                                </a>
                            </div>
                            <div>
                                <a href="https://discord.gg/MXTjNMgA5W" target="_blank" title="CyBreed's Discord server">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 127.14 96.36"><defs><style>.cls-1{fill:#fff;}</style></defs><g id="图层_2" data-name="图层 2"><g id="Discord_Logos" data-name="Discord Logos"><g id="Discord_Logo_-_Large_-_White" data-name="Discord Logo - Large - White"><path class="cls-1" d="M107.7,8.07A105.15,105.15,0,0,0,81.47,0a72.06,72.06,0,0,0-3.36,6.83A97.68,97.68,0,0,0,49,6.83,72.37,72.37,0,0,0,45.64,0,105.89,105.89,0,0,0,19.39,8.09C2.79,32.65-1.71,56.6,.54,80.21h0A105.73,105.73,0,0,0,32.71,96.36,77.7,77.7,0,0,0,39.6,85.25a68.42,68.42,0,0,1-10.85-5.18c.91-.66,1.8-1.34,2.66-2a75.57,75.57,0,0,0,64.32,0c.87.71,1.76,1.39,2.66,2a68.68,68.68,0,0,1-10.87,5.19,77,77,0,0,0,6.89,11.1A105.25,105.25,0,0,0,126.6,80.22h0C129.24,52.84,122.09,29.11,107.7,8.07ZM42.45,65.69C36.18,65.69,31,60,31,53s5-12.74,11.43-12.74S54,46,53.89,53,48.84,65.69,42.45,65.69Zm42.24,0C78.41,65.69,73.25,60,73.25,53s5-12.74,11.44-12.74S96.23,46,96.12,53,91.08,65.69,84.69,65.69Z"/></g></g></g><script xmlns=""/></svg>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="cybreed-login-form">
                    <form method="post" action="">
                        <h3>Sign in to Cybreed</h3>
                        <p> New user: <a href="https://app.cybreed.ai/register/" target="_blank" class="cursor-pointer font-bold text-primary">Create an Account</a></p>
                        <?php wp_nonce_field('cybreed_login_action', 'cybreed_login_nonce'); ?>
                        <label class="sr-only">Email:</label>
                        <input type="email" name="email" required placeholder="Email">
                        <label class="sr-only">Password:</label>
                        <input type="password" name="password" required placeholder="Password">
                        <input type="submit" name="login_submit" value="Login" class="cybreed-button">
                    </form>
                </div>
            </div>
            <?php
        } else {
            ?>
            <div class="cybreed-dashboard-wrapper">
                <div id="cybreed-logo">
                    <?php 
                    $logo_id = attachment_url_to_postid(plugins_url('assets/images/logo.svg', dirname(__DIR__, 2) . '/cybreed.php'));
                    if ($logo_id) {
                        echo wp_get_attachment_image($logo_id, 'full', false, array('alt' => 'CyBreed'));
                    } else {
                        // Fallback if image is not in media library
                        echo '<img src="' . esc_url(plugins_url('assets/images/logo.svg', dirname(__DIR__, 2) . '/cybreed.php')) . '" alt="' . esc_attr('CyBreed') . '" />';
                    }
                    ?>
                </div>
                
                <div class="cybreed-dashboard-card">
                    <h2 class="cybreed-dashboard-header">Welcome Back!</h2>
                    <p class="cybreed-dashboard-subheader">Manage your plugin settings and explore new features.</p>
                    <?php
                    $selected_organisation_id = get_option('cybreed_selected_organisation_id', '');
                    $selected_chat_id = get_option('cybreed_selected_chat_id', '');
                    
                    $base_url = 'https://app.cybreed.ai/dashboard';
                    $org_url = $selected_organisation_id ? "{$base_url}/organization/{$selected_organisation_id}" : "{$base_url}/organization";
                    $chat_url = ($selected_organisation_id && $selected_chat_id) ? "{$org_url}/chat/{$selected_chat_id}" : $org_url;
                    ?>
                    <div class="cybreed-auth-container">
                        <div class="cybreed-auth-card">
                            <h3>Change plugin settings</h3>
                            <p>Choose which and where the chat should display on your website!</p>
                            <a href="/wp-admin/admin.php?page=cybreed-settings" class="cybreed-button">Settings</a>
                        </div>
                        <div class="cybreed-auth-card">
                            <h3>Custom Appearance</h3>
                            <p>Stylize your chat to fit your needs!</p>
                            <a href="<?php echo esc_url($chat_url); ?>/configuration?configuration=2" target="_blank" class="cybreed-button">Appearance</a>
                        </div>
                        <div class="cybreed-auth-card">
                            <h3>Converstations</h3>
                            <p>Collect information & converse with your clients in real-time!</p>
                            <a href="<?php echo esc_url($chat_url); ?>/configuration?configuration=0" target="_blank" class="cybreed-button">See Conversations</a>
                        </div>
                        <div class="cybreed-auth-card">
                            <h3>Cybreed Agents</h3>
                            <p>Check out our powerful agents to train your chat with custom knowledge and many more!</p>
                            <a href="<?php echo esc_url($chat_url); ?>/configuration?configuration=1" target="_blank" class="cybreed-button">Find out more</a>
                        </div>
                    </div>
                    <form id="logoutF" method="post" action="">

                        <?php wp_nonce_field('cybreed_logout_action', 'cybreed_logout_nonce'); ?>

                        <input type="hidden" name="redirect_to" value="<?php echo esc_url(admin_url('admin.php?page=cybreed&logout=success')); ?>">

                        <input type="submit" name="logout_submit" value="Logout" class="cybreed-button">

                    </form>
                </div>
                <div class="join-us">
                    <h2>Join our community: </h2>
                    <div class="comunity-wrapper">
                        <div>
                            <a href="https://x.com/cybreedAI" target="_blank" title="CyBreed's X">
                                <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-dnmrzs r-bnwqim r-lrvibr r-m6rgpd r-lrsllp r-1nao33i r-16y2uox r-8kz0gk"><g><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"></path></g></svg>
                            </a>
                        </div>
                        <div>
                            <a href="https://discord.gg/MXTjNMgA5W" target="_blank" title="CyBreed's Discord server">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 127.14 96.36"><defs><style>.cls-1{fill:#fff;}</style></defs><g id="图层_2" data-name="图层 2"><g id="Discord_Logos" data-name="Discord Logos"><g id="Discord_Logo_-_Large_-_White" data-name="Discord Logo - Large - White"><path class="cls-1" d="M107.7,8.07A105.15,105.15,0,0,0,81.47,0a72.06,72.06,0,0,0-3.36,6.83A97.68,97.68,0,0,0,49,6.83,72.37,72.37,0,0,0,45.64,0,105.89,105.89,0,0,0,19.39,8.09C2.79,32.65-1.71,56.6,.54,80.21h0A105.73,105.73,0,0,0,32.71,96.36,77.7,77.7,0,0,0,39.6,85.25a68.42,68.42,0,0,1-10.85-5.18c.91-.66,1.8-1.34,2.66-2a75.57,75.57,0,0,0,64.32,0c.87.71,1.76,1.39,2.66,2a68.68,68.68,0,0,1-10.87,5.19,77,77,0,0,0,6.89,11.1A105.25,105.25,0,0,0,126.6,80.22h0C129.24,52.84,122.09,29.11,107.7,8.07ZM42.45,65.69C36.18,65.69,31,60,31,53s5-12.74,11.43-12.74S54,46,53.89,53,48.84,65.69,42.45,65.69Zm42.24,0C78.41,65.69,73.25,60,73.25,53s5-12.74,11.44-12.74S96.23,46,96.12,53,91.08,65.69,84.69,65.69Z"/></g></g></g><script xmlns=""/></svg>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php
        }
    }
}
