<?php

/**
 * JCOGS Image Pro - Cache Settings Update Route
 * =============================================
 * Handles form submissions for cache management settings updates
 * 
 * @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      2.0.0 - Named Connections System
 */

namespace JCOGSDesign\JCOGSImagePro\ControlPanel\Routes\Caching;

use JCOGSDesign\JCOGSImagePro\ControlPanel\Routes\ImageAbstractRoute;
use Exception;

class UpdateSettings extends ImageAbstractRoute
{
    
    /**
     * @var array|null Cached named filesystem adapters configuration
     */
    private $cached_named_adapters_config = null;

    /**
     * @var string Route path for URL generation
     */
    protected $route_path = 'caching/update_settings';

    /**
     * Process cache settings update form submission
     * 
     * This route handles POST form submissions from the unified cache management form.
     * After processing, it redirects back to the main cache management page.
     * 
     * @param mixed $id Route parameter (unused for this action)
     * @return $this Fluent interface for EE7 routing
     */
    public function process($id = false)
    {
        // Load language file for internationalization
        $this->loadLanguage();

        if (!$this->ensureMutationAllowed('save_cache_settings', 'caching')) {
            return $this;
        }
        
        try {
            // Get form data
            $default_cache_duration_raw = ee()->input->post('img_cp_default_cache_duration', true);
            $cache_auto_manage = ee()->input->post('img_cp_cache_auto_manage', true);
            $default_connection = ee()->input->post('default_cache_connection', true);
            $cache_log_preload_threshold = ee()->input->post('img_cp_cache_log_preload_threshold', true);

            // Parse cache duration using DurationParser
            $duration_parser = new \JCOGSDesign\JCOGSImagePro\Service\DurationParser();
            $parsed = $duration_parser->parseToSeconds($default_cache_duration_raw);
            if ($parsed['error']) {
                throw new Exception($parsed['error']);
            }
            $cache_duration = $parsed['value'];
            $validation = $duration_parser->validateForContext($cache_duration, 'cache');
            if (!$validation['valid']) {
                throw new Exception($validation['error']);
            }

            // Get current settings and update them
            $current_settings = $this->getCurrentSettings();
            $current_settings['img_cp_default_cache_duration'] = strval($cache_duration);
            $current_settings['img_cp_cache_auto_manage'] = $cache_auto_manage;

            // Handle default connection update if provided
            if (!empty($default_connection)) {
                $this->utilities_service->debug_log("JCOGS IMG PRO DEBUG - Processing default connection update");
                // Decode the named adapters JSON
                $named_adapters = [];
                if (!empty($current_settings['img_cp_named_filesystem_adapters'])) {
                    $named_adapters = json_decode($current_settings['img_cp_named_filesystem_adapters'], true);
                    if (!is_array($named_adapters)) {
                        $named_adapters = [];
                    }
                }
                // Update the default_connection value
                $named_adapters['default_connection'] = $default_connection;
                // Encode back to JSON and save
                $current_settings['img_cp_named_filesystem_adapters'] = json_encode($named_adapters);
            } else {
                $this->utilities_service->debug_log("JCOGS IMG PRO DEBUG - No default_connection provided in POST");
            }

            // Validate auto-manage setting
            if (!in_array($cache_auto_manage, ['y', 'n'])) {
                $cache_auto_manage = 'y'; // Default to enabled
            }
            
            // Validate and save cache log preload threshold
            if (isset($cache_log_preload_threshold)) {
                $threshold_value = intval($cache_log_preload_threshold);
                if ($threshold_value <= 0) {
                    throw new Exception('Cache log preload threshold must be greater than 0');
                }
                $current_settings['img_cp_cache_log_preload_threshold'] = strval($threshold_value);
            }

            // Save settings using the settings service
            $this->saveSettings($current_settings);

            // Show success message
            $saved_items = [];
            if (!empty($default_connection)) {
                $saved_items[] = 'default cache connection';
            }
            $saved_items[] = 'cache duration';
            $saved_items[] = 'auto-management setting';
            if (isset($cache_log_preload_threshold)) {
                $saved_items[] = 'cache log preload threshold';
            }

            ee('CP/Alert')->makeInline('cache-settings')
                ->asSuccess()
                ->withTitle('Settings Saved')
                ->addToBody('Successfully saved: ' . implode(', ', $saved_items) . '.');

        } catch (Exception $e) {
            // Show error message
            ee('CP/Alert')->makeInline('cache-settings')
                ->asIssue()
                ->withTitle('Error Saving Settings')
                ->addToBody('Failed to save cache settings: ' . $e->getMessage());
        }

        // Redirect back to cache management
        ee()->functions->redirect(ee('CP/URL')->make('addons/settings/jcogs_img_pro/caching'));
        return $this;
    }
}
