<?php
/**
 * 🗄️ CACHE CONTROLLER - V2.2 PURE
 *
 * @package FleekDash\Controllers
 * @since 2.2.0
 * @SuppressWarnings(PHPMD.UnusedFormalParameter) Request param required by REST route callback signature
 */

namespace FleekDash\Controllers;

use WP_REST_Request;
use FleekDash\Services\ResponseService;

class CacheController
{
    public function checkInvalidation(WP_REST_Request $_request) // NOSONAR php:S1172 - WP REST callback signature
    {
        try {
            $last_invalidation = \get_option('fleekdash_invalidate_frontend_cache', 0);
            $last_check = \get_option('fleekdash_last_cache_check', 0);
            $should_invalidate = $last_invalidation > $last_check;

            return ResponseService::success('Cache invalidation status retrieved', [
                'should_invalidate' => $should_invalidate,
                'last_invalidation' => $last_invalidation,
                'last_check' => $last_check,
            ]);
        } catch (\Exception $e) {
            return ResponseService::error('Failed to check invalidation', ['error' => $e->getMessage()], 500);
        }
    }

    public function clearInvalidationFlag(WP_REST_Request $_request) // NOSONAR php:S1172 - WP REST callback signature
    {
        try {
            \update_option('fleekdash_last_cache_check', time(), false);
            return ResponseService::success('Cache invalidation flag cleared');
        } catch (\Exception $e) {
            return ResponseService::error('Failed to clear flag', ['error' => $e->getMessage()], 500);
        }
    }

    public function clearAllTransients(WP_REST_Request $_request) // NOSONAR php:S1172 - WP REST callback signature
    {
        try {
            global $wpdb;
            $cleared_count = $wpdb->query(
                "DELETE FROM {$wpdb->options}
                 WHERE option_name LIKE '_transient_fleekdash_%'
                 OR option_name LIKE '_transient_timeout_fleekdash_%'"
            );

            return ResponseService::success('Transients cleared', ['cleared_count' => $cleared_count]);
        } catch (\Exception $e) {
            return ResponseService::error('Failed to clear transients', ['error' => $e->getMessage()], 500);
        }
    }

    public function setInvalidationFlag(WP_REST_Request $_request) // NOSONAR php:S1172 - WP REST callback signature
    {
        try {
            \update_option('fleekdash_invalidate_frontend_cache', time(), false);
            return ResponseService::success('Cache invalidation flag set');
        } catch (\Exception $e) {
            return ResponseService::error('Failed to set flag', ['error' => $e->getMessage()], 500);
        }
    }
}
