<?php

/**
 * JCOGS Image Pro - Cache Status Widget
 * =====================================
 * Dashboard widget displaying overall cache system status and statistics
 * 
 * @category   ExpressionEngine Add-on
 * @package    JCOGS Image Pro
 * @author     JCOGS Design <contact@jcogs.net>
 * @copyright  Copyright (c) 2021 - 2025 JCOGS Design
 * @license    https://jcogs.net/add-ons/license/jcogs_img_pro
 * @version    2.0.6
 * @link       https://JCOGS.net/
 * @since      Dashboard Widget Implementation
 */

namespace JCOGSDesign\JCOGSImagePro\Widgets;

use ExpressionEngine\Addons\Pro\Service\Dashboard;

class CacheStatus extends Dashboard\AbstractDashboardWidget implements Dashboard\DashboardWidgetInterface
{
    public function getTitle()
    {
        return lang('Cache Status');
    }

    public function getContent()
    {
        // Import the Caching route
        $caching = new \JCOGSDesign\JCOGSImagePro\ControlPanel\Routes\Caching();
        
        // Load async JavaScript for cache management
        $caching->loadCacheManagementAssets();
        
        // Get the Action ID for CacheAjaxEndpoints
        $action_id = ee()->db->select('action_id')
            ->from('actions')
            ->where('class', 'Jcogs_img_pro')
            ->where('method', 'CacheAjaxEndpoints')
            ->get()
            ->row('action_id');
        
        // Build Action URL for cache statistics
        $ajax_url = ee()->functions->fetch_site_index(0, 0) . QUERY_MARKER . 'ACT=' . $action_id . '&method=cache_statistics';
        
        // ASYNC LOADING: Render loading placeholder instead of calculating stats synchronously
        // JavaScript will load the actual data via AJAX using EE Action URL
        $status_html = '<div id="cache-statistics-container" class="cache-statistics-container" data-ajax-url="' . htmlspecialchars($ajax_url, ENT_QUOTES, 'UTF-8') . '">';
        $status_html .= '<div class="cache-loading-state">';
        $status_html .= '<div class="cache-stat-box loading">';
        $status_html .= '<i class="fas fa-spinner fa-spin" style="font-size: 2rem; color: #6366f1; margin-bottom: 0.5rem;"></i>';
        $status_html .= '<div class="cache-stat-label" style="color: #64748b;">Loading cache statistics...</div>';
        $status_html .= '<div class="cache-stat-sublabel" style="font-size: 0.875rem; color: #94a3b8; margin-top: 0.25rem;">This may take a moment for remote storage</div>';
        $status_html .= '</div>';
        $status_html .= '</div>';
        $status_html .= '</div>';
        
        return $status_html;
    }

    public function getRightHead()
    {
        return '<a href="' . ee('CP/URL', 'addons/settings/jcogs_img_pro/caching') . '" class="button button--default button--small">' . lang('JCOGS Image Pro') . '</a>';
    }
}
