<?php

require_once plugin_dir_path( __FILE__ ) . '../config/CloudConstants.php';
/**
 * CloudToolsController
 * 
 * Handles AWS S3 operations, migrations, status checks, and retry operations for the Upcasted S3 Offload plugin.
 * This controller serves as the main interface between the WordPress admin interface and the CloudActions service.
 * 
 * @package Upcasted_S3_Offload
 * @since 3.0.0
 */
class CloudToolsController {
    // ============================================================
    // CONNECTION & INITIALIZATION FUNCTIONS
    // ============================================================
    /**
     * Connect to S3 and retrieve bucket list
     * 
     * Establishes connection to AWS S3 using provided credentials and returns
     * a list of available buckets for the account.
     * 
     * @since 3.0.0
     * @return void Sends JSON response with bucket list or error
     */
    public function upcasted_offload_connect() {
        try {
            // Verify the nonce for security
            if ( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'wp_rest' ) ) {
                wp_send_json_error( array(
                    'message' => __( 'Invalid nonce.', 'your-plugin-textdomain' ),
                ), 403 );
                return;
            }
            // Check user capabilities (optional but recommended for sensitive operations)
            if ( !current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array(
                    'message' => __( 'Unauthorized action.', 'your-plugin-textdomain' ),
                ), 403 );
                return;
            }
            // Sanitize and encrypt the input values
            $accessKeyId = ( !empty( $_POST['access_key_id'] ) ? CloudCredentialsEncryption::getInstance()->encrypt( sanitize_text_field( wp_unslash( $_POST['access_key_id'] ) ) ) : null );
            $secretAccessKey = ( !empty( $_POST['secret_access_key'] ) ? CloudCredentialsEncryption::getInstance()->encrypt( sanitize_text_field( wp_unslash( $_POST['secret_access_key'] ) ) ) : null );
            $region = ( !empty( $_POST['region'] ) ? sanitize_text_field( wp_unslash( $_POST['region'] ) ) : null );
            $customEndpoint = ( !empty( $_POST['custom_endpoint'] ) ? sanitize_text_field( wp_unslash( preg_replace( "(^https?://)", "", $_POST['custom_endpoint'] ) ) ) : null );
            // Reinitialize the Cloud Application
            CloudApplication::destroy();
            $cloudApp = CloudApplication::getInstance(
                $accessKeyId,
                $secretAccessKey,
                $region,
                $customEndpoint
            );
            // Return the list of buckets
            wp_send_json_success( $cloudApp->cloudManipulator->get_buckets(), 200 );
        } catch ( Exception $exception ) {
            error_log( 'Upcasted S3 Offload - Credentials verification failed: ' . $exception->getMessage() );
            // Send error message and troubleshooting tips as separate fields
            $indications = '<div class="upcasted-aws-error-help"><p>Usually, if you get an error here you should double check:</p>' . '<ol>' . '<li>Check if your credentials are correct (Key and Secret)</li>' . '<li>Check if the region is correct</li>' . '<li>Check if your custom endpoint is correct. If you don\'t use AWS S3 then you should set a custom endpoint.</li>' . '<li>Check if the IAM user has full permissions over the bucket</li>' . '</ol></div>';
            wp_send_json_error( array(
                'message'     => esc_html( $exception->getMessage() ),
                'indications' => $indications,
            ), 500 );
        }
    }

    /**
     * Initialize cloud application with selected bucket
     * 
     * Sets up the CloudApplication instance with the user-selected S3 bucket
     * and prepares the plugin for file operations.
     * 
     * @since 3.0.0
     * @return void Sends JSON success or error response
     */
    public function upcasted_init() {
        try {
            // Verify the nonce for security
            if ( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'wp_rest' ) ) {
                wp_send_json_error( array(
                    'message' => __( 'Invalid nonce.', 'upcasted-s3-offload' ),
                ), 403 );
                return;
            }
            // Check user capabilities (optional but recommended for sensitive operations)
            if ( !current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array(
                    'message' => __( 'Unauthorized action.', 'upcasted-s3-offload' ),
                ), 403 );
                return;
            }
            // Sanitize and process the bucket name
            $bucket = ( isset( $_POST['bucket'] ) ? sanitize_text_field( wp_unslash( $_POST['bucket'] ) ) : null );
            if ( empty( $bucket ) ) {
                wp_send_json_error( array(
                    'message' => __( 'Bucket name is required.', 'upcasted-s3-offload' ),
                ), 400 );
                return;
            }
            // Initialize the CloudApplication with the provided bucket
            CloudApplication::getInstance()->upcasted_init( $bucket );
            // Send success response
            wp_send_json_success( __( 'Cloud application initialized successfully.', 'upcasted-s3-offload' ), 200 );
        } catch ( Exception $exception ) {
            error_log( 'Upcasted S3 Offload - Cloud application initialization failed: ' . $exception->getMessage() );
            // Handle exceptions and send an error response
            wp_send_json_error( array(
                'message' => sprintf( __( 'An error occurred during initialization: %s', 'upcasted-s3-offload' ), esc_html( $exception->getMessage() ) ),
            ), ( $exception->getCode() ?: 500 ) );
        }
    }

    /**
     * Create a new S3 bucket
     * 
     * Creates a new bucket in the connected S3 account with the specified name.
     * 
     * @since 3.0.6
     * @return void Sends JSON success or error response
     */
    public function upcasted_create_bucket() {
        // Verify the nonce for security
        if ( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'wp_rest' ) ) {
            wp_send_json_error( __( 'Invalid nonce.', 'upcasted-s3-offload' ), 403 );
            return;
        }
        // Check user capabilities (optional but recommended for sensitive operations)
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Unauthorized action.', 'upcasted-s3-offload' ), 403 );
            return;
        }
        try {
            // Sanitize the bucket name from the POST request
            $bucket_name = sanitize_text_field( $_POST['bucket_name'] ?? '' );
            if ( empty( $bucket_name ) ) {
                wp_send_json_error( 'Bucket name is required.', 400 );
                // Bad Request
            }
            // Call the premium method to create the bucket
            CloudApplication::getInstance()->upcasted_create_bucket( $bucket_name );
            // Send a success response
            wp_send_json_success( 'Bucket created successfully.', 200 );
        } catch ( Exception $exception ) {
            error_log( 'Upcasted S3 Offload - Bucket creation failed: ' . $exception->getMessage() );
            // Fallback to a default error code if the exception doesn't have one
            $error_code = ( $exception->getCode() > 0 ? $exception->getCode() : 500 );
            // Send an error response with details
            wp_send_json_error( "There was an error creating the bucket: {$exception->getMessage()}", $error_code );
        }
    }

    /**
     * Update file type and behavior settings
     * 
     * Saves file type filters and upload/delete behaviors independently
     * of S3 connection settings.
     * 
     * @since 3.1.0
     * @return void Sends JSON success or error response
     */
    public function upcasted_update_behavior_settings() {
        // Verify the nonce for security
        if ( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'wp_rest' ) ) {
            wp_send_json_error( __( 'Invalid nonce.', 'upcasted-s3-offload' ), 403 );
            return;
        }
        // Check user capabilities
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( __( 'Unauthorized action.', 'upcasted-s3-offload' ), 403 );
            return;
        }
        try {
            CloudApplication::getInstance()->upcasted_update_behavior_settings();
            wp_send_json_success( __( 'Behavior settings updated successfully!', 'upcasted-s3-offload' ) );
        } catch ( Exception $exception ) {
            wp_send_json_error( array(
                'message' => $exception->getMessage(),
                'code'    => $exception->getCode(),
            ) );
        }
    }

}
