<?php

namespace MovieEngine\Core;

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

/**
 * Cache Manager Class
 * 
 * Handles hybrid caching: Database Transients and Physical File Assets.
 *
 * @package MovieEngine
 */
class Cache {

    public static function init() {
        $base_dir = self::ensure_upload_dir();

        $css_file = $base_dir . '/custom-style.css';
        if (!file_exists($css_file)) {
            self::update_custom_css();
        }

        add_action('save_post', [__CLASS__, 'purge_on_post_update'], 10, 3);
        add_action('deleted_post', [__CLASS__, 'purge_on_post_update'], 10, 3);
    }

    public static function purge_on_post_update($post_id, $post, $update = null) {
        if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) {
            return;
        }

        $types = ['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode', 'movie_engine_person'];

        $post_type = is_object($post) ? $post->post_type : get_post_type($post_id);

        if (in_array($post_type, $types)) {
            self::purge_fragments();
        }
    }

    public static function purge_fragments() {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_movie_engine_cache_%' OR option_name LIKE '_transient_timeout_movie_engine_cache_%'");
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_tmdb_api_%' OR option_name LIKE '_transient_timeout_tmdb_api_%'");
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_omdb_ratings_%' OR option_name LIKE '_transient_timeout_omdb_ratings_%'");
        // WP_Query ID cache — stored as _transient_me_q_* directly (bypasses Cache::set)
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_me_q_%' OR option_name LIKE '_transient_timeout_me_q_%'");
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_shortcode_%' OR option_name LIKE '_transient_timeout_shortcode_%'");
    }

    public static function ensure_upload_dir() {
        $upload_dir = wp_upload_dir();
        $base_dir   = trailingslashit($upload_dir['basedir']) . 'cine-movie-engine';

        if (!file_exists($base_dir)) {
            wp_mkdir_p($base_dir);
        }

        $htaccess_file = $base_dir . '/.htaccess';
        if (!file_exists($htaccess_file)) {
            $content = "Options -Indexes\n";
            $content .= "<Files *.php>\n    Order Deny,Allow\n    Deny from all\n</Files>";
            @file_put_contents($htaccess_file, $content);
        }

        $index_file = $base_dir . '/index.html';
        if (!file_exists($index_file)) {
            @file_put_contents($index_file, '');
        }

        return $base_dir;
    }

    public static function get_upload_url() {
        $upload_dir = wp_upload_dir();
        return set_url_scheme(trailingslashit($upload_dir['baseurl']) . 'cine-movie-engine');
    }

    public static function generate_design_css($design_settings) {
        $container_width = !empty($design_settings['container_width']) ? intval($design_settings['container_width']) : 1170;
        $border_radius   = isset($design_settings['border_radius']) ? intval($design_settings['border_radius']) : 8;

        $preset = $design_settings['color_preset'] ?? 'netflix';
        $presets = [
            'netflix'   => ['primary' => '#E50914', 'hover' => '#B2070F', 'text' => '#FFFFFF', 'gray' => '#A3A3A3', 'border' => '#23252c', 'bg' => '#141414', 'surface' => '#1a1b1f'],
            'hulu'      => ['primary' => '#1CE783', 'hover' => '#15AB61', 'text' => '#FFFFFF', 'gray' => '#A3A3A3', 'border' => '#23252c', 'bg' => '#0b0c0f', 'surface' => '#14151a'],
            'prime'     => ['primary' => '#00A8E1', 'hover' => '#007FB2', 'text' => '#FFFFFF', 'gray' => '#A3A3A3', 'border' => '#23252c', 'bg' => '#0f171e', 'surface' => '#1b2530'],
        ];

        $default_colors = ['primary' => '#E50914', 'hover' => '#B2070F', 'text' => '#FFFFFF', 'gray' => '#A3A3A3', 'border' => '#23252c', 'bg' => '#141414', 'surface' => '#1a1b1f'];

        if ($preset === 'custom') {
            $primary = $design_settings['primary_color'] ?? $default_colors['primary'];
            $hover   = $design_settings['primary_hover_color'] ?? $default_colors['hover'];
            $text    = $design_settings['text_color'] ?? $default_colors['text'];
            $gray    = $design_settings['gray_color'] ?? $default_colors['gray'];
            $border  = $design_settings['border_color'] ?? $default_colors['border'];
            $bg      = $design_settings['background_color'] ?? $default_colors['bg'];
            $surface = $design_settings['surface_color'] ?? $default_colors['surface'];
        } else {
            $p = $presets[$preset] ?? $presets['netflix'];
            $primary = $p['primary'];
            $hover   = $p['hover'];
            $text    = $p['text'];
            $gray    = $p['gray'];
            $border  = $p['border'];
            $bg      = $p['bg'];
            $surface = $p['surface'];
        }

        $primary_rgb = self::hex2rgb($primary);
        $bg_rgb      = self::hex2rgb($bg);
        $surface_rgb = self::hex2rgb($surface);

        $custom_css = ":root {\n";
        $custom_css .= "  --movie-engine-container-width: {$container_width}px;\n";
        $custom_css .= "  --movie-engine-border-radius: {$border_radius}px;\n";
        $custom_css .= "  --movie-engine-primary-color: {$primary};\n";
        $custom_css .= "  --movie-engine-primary-rgb: {$primary_rgb};\n";
        $custom_css .= "  --movie-engine-primary-hover-color: {$hover};\n";
        $custom_css .= "  --movie-engine-body-color: {$text};\n";
        $custom_css .= "  --movie-engine-muted-color: {$gray};\n";
        $custom_css .= "  --movie-engine-border-color: {$border};\n";
        $custom_css .= "  --movie-engine-bg-color: {$bg};\n";
        $custom_css .= "  --movie-engine-bg-rgb: {$bg_rgb};\n";
        $custom_css .= "  --movie-engine-black-color: {$surface};\n";
        $custom_css .= "  --movie-engine-surface-color: {$surface};\n";
        $custom_css .= "  --movie-engine-black-rgb: {$surface_rgb};\n";

        if (!empty($design_settings['archive_columns_desktop'])) {
            $val = intval($design_settings['archive_columns_desktop']);
            $custom_css .= "  --me-grid-columns-desktop: {$val}; --movie-engine-grid-columns-desktop: {$val};\n";
        }
        if (!empty($design_settings['archive_columns_laptop'])) {
            $val = intval($design_settings['archive_columns_laptop']);
            $custom_css .= "  --me-grid-columns-laptop: {$val}; --movie-engine-grid-columns-laptop: {$val};\n";
        }
        if (!empty($design_settings['archive_columns_tablet'])) {
            $val = intval($design_settings['archive_columns_tablet']);
            $custom_css .= "  --me-grid-columns-tablet: {$val}; --movie-engine-grid-columns-tablet: {$val};\n";
        }
        if (!empty($design_settings['archive_columns_mobile'])) {
            $val = intval($design_settings['archive_columns_mobile']);
            $custom_css .= "  --me-grid-columns-mobile: {$val}; --movie-engine-grid-columns-mobile: {$val};\n";
        }

        $custom_css .= "}\n";

        return $custom_css;
    }

    private static function hex2rgb($hex) {
        $hex = str_replace("#", "", $hex);

        if (strlen($hex) == 3) {
            $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
            $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
            $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
        } else {
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
        }
        return "$r, $g, $b";
    }

    public static function minify_css($css) {
        $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
        $css = str_replace(': ', ':', $css);
        $css = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $css);
        return $css;
    }

    public static function update_custom_css($css_content = null) {
        $base_dir = self::ensure_upload_dir();
        $file_path = $base_dir . '/custom-style.css';

        if ($css_content === null) {
            $design_settings = get_option('movie_engine_design_settings', []);
            $css_content = self::generate_design_css($design_settings);
        }

        if (empty($css_content)) {
            if (file_exists($file_path)) {
                wp_delete_file($file_path);
            }
            return false;
        }

        $css_content = self::minify_css($css_content);

        $result = @file_put_contents($file_path, $css_content);

        if ($result !== false) {
            update_option('movie_engine_css_cache_version', time());
            return true;
        }

        return false;
    }

    public static function purge_all() {
        global $wpdb;
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_movie_engine_%' OR option_name LIKE '_transient_timeout_movie_engine_%'");
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_shortcode_%' OR option_name LIKE '_transient_timeout_shortcode_%'");
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_tmdb_api_%' OR option_name LIKE '_transient_timeout_tmdb_api_%'");
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_omdb_ratings_%' OR option_name LIKE '_transient_timeout_omdb_ratings_%'");
        // WP_Query ID cache stored directly as me_q_* (not via Cache::set)
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_me_q_%' OR option_name LIKE '_transient_timeout_me_q_%'");

        $base_dir = self::ensure_upload_dir();
        $files = glob($base_dir . '/*');
        foreach ($files as $file) {
            if (is_file($file) && !in_array(basename($file), ['.htaccess', 'index.html'])) {
                wp_delete_file($file);
            }
        }

        wp_cache_flush();
        update_option('movie_engine_css_cache_version', time());
    }

    public static function is_enabled() {
        $options = get_option('movie_engine_general_settings', []);
        return (bool) ($options['movie_engine_enable_cache'] ?? 1);
    }

    public static function set($key, $value, $expiration = HOUR_IN_SECONDS) {
        if (!self::is_enabled()) {
            return false;
        }
        $prefix = 'movie_engine_cache_';
        return set_transient($prefix . $key, $value, $expiration);
    }

    public static function get($key) {
        if (!self::is_enabled()) {
            return false;
        }
        $prefix = 'movie_engine_cache_';
        return get_transient($prefix . $key);
    }

    public static function delete($key) {
        $prefix = 'movie_engine_cache_';
        return delete_transient($prefix . $key);
    }
}
