<?php
namespace LivraisonAPI;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Cache {
    
    const GROUP = 'livraison_api';
    const DEFAULT_DURATION = 300; // 5 minutes
    
    /**
     * Récupérer une valeur du cache
     */
    public static function get( $key ) {
        return wp_cache_get( $key, self::GROUP );
    }
    
    /**
     * Mettre en cache une valeur
     */
    public static function set( $key, $value, $duration = self::DEFAULT_DURATION ) {
        return wp_cache_set( $key, $value, self::GROUP, $duration );
    }
    
    /**
     * Supprimer une valeur du cache
     */
    public static function delete( $key ) {
        return wp_cache_delete( $key, self::GROUP );
    }
    
    public static function flush() {
        global $wpdb;
        
        wp_cache_flush();
        
        $cache_key = 'livraison_transient_keys';
        $transient_keys = wp_cache_get( $cache_key, 'livraison_api' );
        
        if ( false === $transient_keys ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $transient_keys = $wpdb->get_col(
                $wpdb->prepare(
                    "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
                    '_transient_livraison_%'
                )
            );
            wp_cache_set( $cache_key, $transient_keys, 'livraison_api', 300 );
        }
        
        foreach ( $transient_keys as $key ) {
            delete_transient( str_replace( '_transient_', '', $key ) );
        }
    }
    
    public static function invalidate_orders_cache( $order_id = null ) {
        self::delete( 'livraison_dashboard_stats' );
        self::delete( 'livraison_recent_logs' );
        self::delete( 'livraison_ajax_stats' );
        self::delete( 'livraison_admin_logs' );
        
        // ✅ Invalider les caches de recherche
        global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$cache_keys = $wpdb->get_col(
    "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '_transient_livraison_orders_stats_%'"
);
        foreach ( $cache_keys as $key ) {
            delete_transient( str_replace( '_transient_', '', $key ) );
        }
        
        if ( $order_id ) {
            self::delete( 'livraison_order_status_' . md5( $order_id ) );
            self::delete( 'livraison_price_' . md5( $order_id ) );
            self::delete( 'livraison_status_' . md5( $order_id ) );
        }
    }
    
   
}