<?php
/**
 * Media Upload Handler for SmartPress
 * 
 * Handles image upload to the WordPress media library and selection in the media modal
 */

// Prevent direct access to this file
if (!defined('ABSPATH')) {
    exit;
}

class SmartPress_Media_Upload {
    
    private static $instance = null;
    
    /**
     * Get singleton instance
     */
    public static function get_instance() {
        if (self::$instance == null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Register REST API endpoints
        add_action('rest_api_init', array($this, 'register_rest_routes'));
    }
    
    /**
     * Register REST API routes
     */
    public function register_rest_routes() {
        register_rest_route('smartpress/v1', '/upload-image', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_image_upload'),
            'permission_callback' => array($this, 'upload_permissions_check')
        ));
        
        register_rest_route('smartpress/v1', '/upload-data-url', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_data_url_upload'),
            'permission_callback' => array($this, 'upload_permissions_check')
        ));
    }
    
    /**
     * Upload permissions check
     */
    public function upload_permissions_check($request) {
        // Add nonce verification
        $nonce = $request->get_header('X-WP-Nonce');
        if (!$nonce || !wp_verify_nonce($nonce, 'wp_rest')) {
            wp_die(
                esc_html__('Sorry, you are not allowed to upload files without a valid nonce.', 'smartpress-pro'),
                esc_html__('Security Error', 'smartpress-pro'),
                array('response' => 403)
            );
        }
        
        return current_user_can('upload_files');
    }
    
    /**
     * Handle image upload from a data URL
     */
    public function handle_data_url_upload($request) {
        $data = $request->get_json_params();
        
        if (empty($data['data_url'])) {
            return new WP_Error('no_data_url', 'No data URL was provided', array('status' => 400));
        }
        
        $data_url = $data['data_url'];
        $filename = !empty($data['filename']) ? sanitize_file_name($data['filename']) : 'smartpress-image.webp';
        
        // Require WordPress media handling functions
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        
        // Get the mime type and raw data from the data URL
        if (preg_match('/^data:image\/(\w+);base64,/', $data_url, $matches)) {
            $image_type = strtolower($matches[1]);
            $base64_data = substr($data_url, strpos($data_url, ',') + 1);
            $image_data = base64_decode($base64_data);
            
            if ($image_data === false) {
                return new WP_Error('invalid_base64', 'Invalid base64 data', array('status' => 400));
            }
            
            // Create a temporary file
            $upload_dir = wp_upload_dir();
            $temp_file = wp_tempnam($filename);
            file_put_contents($temp_file, $image_data);
            
            // Prepare filename with correct extension
            // Ensure we honor the extension from the filename if provided
            $file_extension = pathinfo($filename, PATHINFO_EXTENSION);
            
            // If no extension in the filename or it doesn't match the detected type,
            // use the detected type instead
            if (empty($file_extension) || ($image_type !== $file_extension && $image_type !== 'jpeg' && $file_extension !== 'jpg')) {
                if ($image_type === 'jpeg' || $image_type === 'jpg') {
                    $file_extension = 'jpg';
                } elseif ($image_type === 'png') {
                    $file_extension = 'png';
                } elseif ($image_type === 'gif') {
                    $file_extension = 'gif';
                } elseif ($image_type === 'webp') {
                    $file_extension = 'webp';
                } else {
                    wp_delete_file($temp_file);
                    return new WP_Error('invalid_image_type', 'Invalid image type: ' . esc_html($image_type), array('status' => 400));
                }
            }
            
            // Ensure the filename uses the detected extension
            $filename_parts = pathinfo($filename);
            $filename = $filename_parts['filename'] . '.' . $file_extension;
            $file_path = $upload_dir['path'] . '/' . $filename;
            
            // Check if file already exists, rename if needed
            $i = 1;
            $original_filename = $filename_parts['filename'];
            while (file_exists($file_path)) {
                $filename = $original_filename . '-' . $i . '.' . $file_extension;
                $file_path = $upload_dir['path'] . '/' . $filename;
                $i++;
            }
            
            // Initialize the WordPress filesystem
            if (!function_exists('WP_Filesystem')) {
                require_once(ABSPATH . 'wp-admin/includes/file.php');
            }
            WP_Filesystem();
            global $wp_filesystem;

            // Move the file using WP_Filesystem
            if (!$wp_filesystem->move($temp_file, $file_path, true)) {
                wp_delete_file($temp_file);
                return new WP_Error('move_error', 'Failed to move the file', array('status' => 500));
            }
            
            // Prepare a title from the filename
            $title = preg_replace('/[_\-.]/', ' ', $original_filename);
            $title = ucwords($title);
            
            // Create attachment
            $attachment = array(
                'post_mime_type' => 'image/' . $image_type,
                'post_title' => $title,
                'post_content' => 'Generated by SmartPress AI',
                'post_status' => 'inherit'
            );
            
            $attachment_id = wp_insert_attachment($attachment, $file_path);
            
            if (is_wp_error($attachment_id)) {
                return $attachment_id;
            }
            
            // Generate attachment metadata
            $attachment_data = wp_generate_attachment_metadata($attachment_id, $file_path);
            
            // Update attachment with metadata
            wp_update_attachment_metadata($attachment_id, $attachment_data);
            
            // Return success with attachment details
            $attachment_url = wp_get_attachment_url($attachment_id);
            
            return rest_ensure_response(array(
                'success' => true,
                'id' => $attachment_id,
                'url' => $attachment_url,
                'title' => get_the_title($attachment_id),
                'filename' => basename($file_path)
            ));
        } else {
            return new WP_Error('invalid_data_url', 'Invalid data URL format', array('status' => 400));
        }
    }
    
    /**
     * Handle image upload and return media details
     */
    public function handle_image_upload($request) {
        // Verify the nonce first
        $nonce = $request->get_header('X-WP-Nonce');
        if (!$nonce || !wp_verify_nonce($nonce, 'wp_rest')) {
            return new WP_Error(
                'invalid_nonce',
                'Invalid nonce',
                array('status' => 403)
            );
        }

        // Check if file data is present
        if (empty($_FILES['file'])) {
            return new WP_Error('no_file', 'No file was uploaded', array('status' => 400));
        }
        
        // Require WordPress media handling functions
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        
        // Get file info
        $file = $_FILES['file'];
        $filename = isset($_POST['filename']) ? sanitize_file_name($_POST['filename']) : null;
        
        // Set up upload overrides
        $overrides = array(
            'test_form' => false,
            'test_size' => true,
        );
        
        // Handle file upload
        $uploaded_file = wp_handle_upload($file, $overrides);
        
        if (isset($uploaded_file['error'])) {
            return new WP_Error('upload_error', $uploaded_file['error'], array('status' => 500));
        }
        
        // Prepare attachment data
        $attachment = array(
            'post_mime_type' => $uploaded_file['type'],
            'post_title' => $filename ? $filename : preg_replace('/\.[^.]+$/', '', basename($uploaded_file['file'])),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        
        // Insert attachment into WordPress media library
        $attachment_id = wp_insert_attachment($attachment, $uploaded_file['file']);
        
        if (is_wp_error($attachment_id)) {
            return $attachment_id;
        }
        
        // Generate attachment metadata
        $attachment_data = wp_generate_attachment_metadata($attachment_id, $uploaded_file['file']);
        
        // Update attachment with metadata
        wp_update_attachment_metadata($attachment_id, $attachment_data);
        
        // Get attachment details
        $attachment_url = wp_get_attachment_url($attachment_id);
        $attachment_details = array(
            'id' => $attachment_id,
            'url' => $attachment_url,
            'title' => get_the_title($attachment_id),
            'filename' => basename($uploaded_file['file']),
            'sizes' => isset($attachment_data['sizes']) ? $attachment_data['sizes'] : array()
        );
        
        // Return success response with attachment details
        return rest_ensure_response(array(
            'success' => true,
            'attachment' => $attachment_details
        ));
    }
}

// Initialize the class
SmartPress_Media_Upload::get_instance(); 