<?php
/**
 * Plugin Name:       SmallPict
 * Plugin URI:        https://smallpict.tuxnoob.com/
 * Description:       Serverless Image Optimization for WordPress. Automatically compresses and converts images using SmallPict Managed Service.
 * Version:           1.1.7
 * Author:            Tuxnoob Team
 * Author URI:        https://tuxnoob.com/
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       smallpict
 * Domain Path:       /languages
 * Requires at least: 5.8
 * Requires PHP:      7.4
 */

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



	define( 'SMALLPICT_PATH', plugin_dir_path( __FILE__ ) );
	define( 'SMALLPICT_URL', plugin_dir_url( __FILE__ ) );
	define( 'SMALLPICT_VERSION', '1.1.7' );

	// Freemius Config (Public)
	define( 'SMALLPICT_FS_ID', '22816' );
	define( 'SMALLPICT_FS_PUBLIC_KEY', 'pk_e17eb3527c02a11d4709dc8313f52' );

	// Managed Service API (Deployed via Terraform)
	define( 'SMALLPICT_API_BASE', 'https://7jq2u3l69a.execute-api.ap-southeast-1.amazonaws.com/v1' );

	

	// New Managed Service Includes
	require_once SMALLPICT_PATH . 'includes/class-smallpict-api.php';
	require_once SMALLPICT_PATH . 'includes/class-presigned-transport.php';
	require_once SMALLPICT_PATH . 'includes/class-settings.php';
	require_once SMALLPICT_PATH . 'includes/class-image-processor.php';
	require_once SMALLPICT_PATH . 'includes/class-quota-manager.php'; // Keep if useful for local display

	register_uninstall_hook( __FILE__, array( 'SmallPict', 'plugin_uninstall' ) );

	class SmallPict {

		private static $instance = null;
		public $api;
		public $transport;
		public $image_processor;
		public $settings;

		public static function get_instance() {
			if ( null === self::$instance ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		private function __construct() {
			$this->init_components();
			$this->init_hooks();
		}

		private function init_components() {
			$this->api             = new SmallPict_API_Client();
			$this->transport       = new SmallPict_Presigned_Transport();
			$this->image_processor = new SmallPict_Image_Processor( $this->api, $this->transport );
			$this->settings        = new SmallPict_Settings( $this->api );

			// Check for existing session
			$token = get_option( 'smallpict_session_token' );
			if ( $token ) {
				$this->api->set_token( $token );
			}
		}

		public function authenticate() {
			if ( ! function_exists( 'smallpict_fs' ) ) {
				return;
			}

			$fs = smallpict_fs();
			if ( ! $fs->is_registered() ) {
				return;
			}

			$site = $fs->get_site();
			if ( ! $site ) {
				return;
			}

			$install_id = (int) $site->id;
			$public_key = $site->public_key;
			$domain     = home_url();

			// Get Plan Slug
			$plan_slug = 'free';
			

			// error_log("SmallPict: Authenticating for Plan: $plan_slug");

			// Plan Change Logic (Upgrade/Downgrade)
			$old_plan_slug = get_option( 'smallpict_current_plan_slug' );

			// 1. Detect Change
			if ( $old_plan_slug && $old_plan_slug !== $plan_slug ) {
				// Reset Usage & Set new Anchor Day to Today
				SmallPict_Quota_Manager::init_tracking( 0, (int) gmdate( 'j' ) );
				// error_log( "SmallPict: Plan change detected ({$old_plan_slug} -> {$plan_slug}). Quota reset and anchor updated to today." );

				// FORCE CLEANUP of Cache to prevent UI lag
				delete_option( 'smallpict_account_limits' );
				delete_option( 'smallpict_account_capabilities' );
			}
			// 2. Init if missing
			elseif ( ! get_option( 'smallpict_usage_tracking' ) ) {
				SmallPict_Quota_Manager::get_tracking_data();
			}

			// Always update current plan slug
			update_option( 'smallpict_current_plan_slug', $plan_slug );

			// Sandbox check
			$is_sandbox = false;
			if ( isset( $site->is_sandbox ) ) {
				$is_sandbox = $site->is_sandbox;
			} elseif ( method_exists( $fs, 'is_sandbox' ) ) {
				$is_sandbox = $fs->is_sandbox();
			}

			// Call Backend
			$res = $this->api->exchange_auth( $install_id, $public_key, $domain, $plan_slug, $is_sandbox );

			if ( ! is_wp_error( $res ) && isset( $res['session_token'] ) ) {
				update_option( 'smallpict_session_token', $res['session_token'] );
				update_option( 'smallpict_tenant_id', $res['tenant_id'] );
				update_option( 'smallpict_plan_cache', $res['plan'] );
				// CRITICAL FIX: Trust Backend Plan for UI Logic
				update_option( 'smallpict_current_plan_slug', $res['plan'] );

				if ( isset( $res['limits'] ) ) {
					update_option( 'smallpict_account_limits', $res['limits'] );
					// error_log("SmallPict: Limits Updated: " . print_r($res['limits'], true));
				}

				if ( isset( $res['capabilities'] ) ) {
					update_option( 'smallpict_account_capabilities', $res['capabilities'] );
				}

				$this->api->set_token( $res['session_token'] );
			} else {
				// error_log("SmallPict: Auth Failed: " . print_r($res, true));
			}
		}

		private function init_hooks() {
			add_action( 'admin_menu', array( $this->settings, 'add_admin_menu' ) );
			add_action( 'admin_init', array( $this->settings, 'register_settings' ) );
			add_action( 'admin_notices', array( $this, 'display_admin_notices' ) );

			// Real-time Warning for AJAX Uploads
			add_filter( 'wp_prepare_attachment_for_js', array( $this, 'prepare_attachment_js' ), 10, 3 );
			add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );

			// Hook into upload (After metadata is generated)
			add_filter( 'wp_generate_attachment_metadata', array( $this->image_processor, 'trigger_optimization' ), 10, 2 );

			// Disable WordPress Big Image Threshold to prevent "-scaled" filenames
			// (Removed from here, moved to global scope)

			

			// Initial check if not authed
			add_action(
				'admin_init',
				function () {
					if ( ! get_option( 'smallpict_session_token' ) ) {
						$this->authenticate();
						return;
					}

					
				}
			);
		}

		public function display_admin_notices() {
			$transient_name = 'smallpict_upload_warning_' . get_current_user_id();
			$msg            = get_transient( $transient_name );
			if ( $msg ) {
				echo '<div class="notice notice-warning is-dismissible"><p>' . esc_html( $msg ) . '</p></div>';
				delete_transient( $transient_name );
			}
		}

		public function prepare_attachment_js( $response, $attachment, $meta ) {
			$warning = get_post_meta( $attachment->ID, 'smallpict_warning', true );
			if ( $warning ) {
				$response['smallpict_warning'] = $warning;
			}
			return $response;
		}

		public function admin_enqueue_scripts() {
			$inline_js = "
            jQuery(document).ready(function($) {
                if ( typeof wp !== 'undefined' && wp.media && wp.Uploader ) {
                    var _origSuccess = wp.Uploader.prototype.success;
                    wp.Uploader.prototype.success = function( file_obj ) {
                        _origSuccess.apply( this, arguments );
                        if ( file_obj && file_obj.attributes && file_obj.attributes.smallpict_warning ) {
                             var msg = file_obj.attributes.smallpict_warning;
                             var notice = '<div class=\"notice notice-warning is-dismissible smallpict-ajax-notice\"><p>' + msg + '</p><button type=\"button\" class=\"notice-dismiss\"><span class=\"screen-reader-text\">Dismiss this notice.</span></button></div>';
                             $('.wrap > h1').after(notice);
                             $('.smallpict-ajax-notice .notice-dismiss').on('click', function() {
                                 $(this).closest('.notice').remove();
                             });
                        }
                    };
                }
            });
            ";
			wp_enqueue_script( 'jquery' );
			wp_add_inline_script( 'jquery', $inline_js );

			// S-P3: Pass nonce to JS so any future AJAX calls can be verified via check_ajax_referer()
			wp_localize_script(
				'jquery',
				'smallpict_ajax',
				array( 'nonce' => wp_create_nonce( 'smallpict_admin_nonce' ) )
			);
		}

		public static function plugin_uninstall() {
			// 1. Settings & Session
			delete_option( 'smallpict_settings' ); // Legacy
			delete_option( 'smallpict_session_token' );
			delete_option( 'smallpict_tenant_id' );

			// 2. Plan & Account Data
			delete_option( 'smallpict_current_plan_slug' );
			delete_option( 'smallpict_plan_cache' );
			delete_option( 'smallpict_account_limits' );
			delete_option( 'smallpict_account_capabilities' );

			// 3. Usage & Tracking
			delete_option( 'smallpict_usage_tracking' );
			delete_option( 'smallpict_monthly_usage' ); // Legacy

			// 4. Individual Settings (matches register_setting)
			delete_option( 'smallpict_auto_optimize' );
			delete_option( 'smallpict_compression_mode' );
			delete_option( 'smallpict_output_format' );
			delete_option( 'smallpict_quality' );
			delete_option( 'smallpict_target_size_enabled' );
			delete_option( 'smallpict_target_kb' );
			delete_option( 'smallpict_aggressive_resize' );
			delete_option( 'smallpict_max_edge' );
		}
	}

	if ( defined( 'ABSPATH' ) ) {
		SmallPict::get_instance();

		// GLOBAL OVERRIDE: Disable Big Image Threshold
		// Executed IMMEDIATELY to prevent "Scaling" logic in wp_generate_attachment_metadata
		add_filter( 'big_image_size_threshold', '__return_false', 9999 );

		// Optimize memory for upload processing
		// @ini_set( 'memory_limit', '-1' );
		// @set_time_limit( 0 ); // Prevent Timeout

		// Ensure max upload size is respected
		add_filter(
			'upload_size_limit',
			function ( $size ) {
				return 1024 * 1024 * 1024; // 1GB
			},
			9999
		);

		/**
		 * CRITICAL: Prevent WordPress from attempting to resize HUGE images locally.
		 */
		add_filter(
			'intermediate_image_sizes_advanced',
			function ( $sizes, $metadata = array() ) {
				// DEBUG LOG
				// error_log("SmallPict: intermediate_image_sizes_advanced filter called.");

				// Safety check for arguments
				if ( ! is_array( $metadata ) || ! isset( $metadata['width'] ) || ! isset( $metadata['height'] ) ) {
					// error_log("SmallPict: Metadata missing dimensions in filter. Meta: " . print_r($metadata, true));
					return $sizes;
				}

				// error_log("SmallPict: Checking dimensions: {$metadata['width']}x{$metadata['height']}");

				// Check if "Huge"
				if ( $metadata['width'] > 2560 || $metadata['height'] > 2560 ) {
					// error_log("SmallPict: Image IS huge. Returning empty sizes to STOP resize.");
					return array();
				}

				return $sizes;
			},
			9999,
			2
		);


	}
	
// Log File Load
// error_log("SmallPict: Plugin File Loaded.");
