<?php

/**
 * JCOGS Image Pro - Active Cache Locations Widget
 * ===============================================
 * Dashboard widget displaying active cache storage locations with 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 ActiveCacheLocations extends Dashboard\AbstractDashboardWidget implements Dashboard\DashboardWidgetInterface
{

    public $width = 'full';
    
    public function getTitle()
    {
        return lang('Active Cache Locations');
    }

    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 locations
        $ajax_url = ee()->functions->fetch_site_index(0, 0) . QUERY_MARKER . 'ACT=' . $action_id . '&method=cache_locations';
        
        // ASYNC LOADING: Render loading placeholder instead of building table synchronously
        // JavaScript will load the actual table via AJAX using EE Action URL
        $loading_html = '<div id="cache-locations-container" class="cache-locations-container" data-ajax-url="' . htmlspecialchars($ajax_url, ENT_QUOTES, 'UTF-8') . '">';
        $loading_html .= '<div class="cache-loading-state" style="text-align: center; padding: 2rem;">';
        $loading_html .= '<i class="fas fa-spinner fa-spin" style="font-size: 2rem; color: #6366f1; margin-bottom: 0.5rem;"></i>';
        $loading_html .= '<div style="color: #64748b; font-weight: 500;">Loading cache locations...</div>';
        $loading_html .= '<div style="font-size: 0.875rem; color: #94a3b8; margin-top: 0.25rem;">Retrieving data from all configured connections</div>';
        $loading_html .= '</div>';
        $loading_html .= '</div>';
        
        return $loading_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>';
    }
}
