<?php

/**
 * LolaCore � Widget
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\Admin;

use LolaCore\Chat\OnboardingFlow;
use LolaCore\Compat\DesktopMode;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Required for core functionality, dynamic queries, and performance. Validated inputs.

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Widget
 *
 * Injects the floating chat widget on all wp-admin pages
 * and passes the initial state to the frontend.
 */
class Widget
{
    /**
     * Register the widget output hook.
     */
    public function register(): void
    {
        \add_action('admin_footer', [$this, 'render']);
    }

    /**
     * Render the widget HTML via template.
     * Only for users with 'manage_options' capability.
     */
    public function render(): void
    {
        if (!\current_user_can('manage_options')) {
            return;
        }

        // Inside a Desktop Mode window the shell's parent page already carries
        // the widget; painting it here too would box a clone in every window.
        if (DesktopMode::isShellWindow()) {
            return;
        }

        $widgetState = $this->getWidgetState();
        $avatar_url = $widgetState['avatar_url'];

        // Widget state is injected via wp_localize_script() in Assets.php
        // to comply with WordPress enqueue standards. No inline <script> tags.

        $templatePath = \plugin_dir_path(dirname(__DIR__)) . 'templates/widget-chat.php';
        if (\file_exists($templatePath)) {
            require $templatePath;
        }
    }

    /**
     * Get initial state for the widget.
     *
     * @return array
     */
    public function getWidgetState(): array
    {
        global $wpdb;
        $table = $wpdb->prefix . 'lolacore_config';

        $isConfigured = OnboardingFlow::hasProviderForChat();
        $triggerFirstRealGreeting = OnboardingFlow::shouldTriggerFirstRealGreeting();

        // Check if onboarding has been completed (explicit flag in config table)
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table.
        $onboardingFlag = $wpdb->get_var($wpdb->prepare("SELECT config_value FROM {$table} WHERE config_key = %s", 'onboarding_complete'));
        $onboardingComplete = ($onboardingFlag === '1');

        // Scan data is stored under 'initial_scan' config key
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table.
        $scanDataRaw = $wpdb->get_var($wpdb->prepare("SELECT config_value FROM {$table} WHERE config_key = %s", 'initial_scan'));
        $hasScanData = !empty($scanDataRaw);
        $scanData = $hasScanData ? \json_decode($scanDataRaw, true) : null;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table.
        $lastSessionSummary = $wpdb->get_var($wpdb->prepare("SELECT config_value FROM {$table} WHERE config_key = %s", 'last_session_summary')) ?: '';
        
        // Avatar setup
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table.
        $avatarAttachmentId = (int) $wpdb->get_var($wpdb->prepare("SELECT config_value FROM {$table} WHERE config_key = %s", 'lola_avatar_attachment_id'));
        $avatarUrl = '';
        if ($avatarAttachmentId > 0) {
            $avatarUrl = \wp_get_attachment_image_url($avatarAttachmentId, 'thumbnail') ?: '';
        }
        if (!$avatarUrl) {
            $avatarUrl = \plugin_dir_url(dirname(__DIR__)) . 'assets/img/lola-default.png';
        }

        return [
            'is_configured'                  => $isConfigured,
            'onboarding_complete'            => $onboardingComplete,
            'should_auto_open_first_greeting'=> $triggerFirstRealGreeting,
            'trigger_first_real_greeting'    => $triggerFirstRealGreeting,
            'has_scan_data'                  => $hasScanData,
            'scan_data'                      => $scanData,
            'last_session_summary'             => $lastSessionSummary,
            'active_session_id'              => null, // Will be managed by frontend sessionStorage
            'avatar_url'                     => $avatarUrl,
            'user_avatar_url'                => \get_avatar_url(\get_current_user_id(), ['size' => 64]),
        ];
    }
}
