<?php

namespace FleekDash\Controllers\Schema;

use FleekDash\Libs\API\ResponseService;

/**
 * File Upload Handler
 *
 * Handles file uploads to WordPress media library
 *
 * @package FleekDash\Controllers\Schema
 */
class FileUploadHandler
{
    /**
     * Handle file uploads and return attachment IDs
     * POST /upload/files
     *
     * @param \WP_REST_Request $request Request object
     * @return \WP_REST_Response Response
     */
    public function uploadFiles($request)
    {
        try {
            // Load debug helpers
            if (!function_exists('fleekdash_log_debug')) {
                require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
            }
            fleekdash_log_debug("FleekDash: Upload debug - _FILES structure: " . print_r($_FILES, true));

            // Check if files were uploaded
            if (empty($_FILES)) {
                return ResponseService::error('No files uploaded', [], 400);
            }

            // Handle files from FormData files[]
            $files = null;
            if (isset($_FILES['files'])) {
                $files = $_FILES['files'];
                fleekdash_log_debug("FleekDash: Using 'files' field from FormData");
            } else {
                // Fallback: Look for any file field
                foreach ($_FILES as $field_name => $field_data) {
                    if (is_array($field_data) && isset($field_data['name'])) {
                        $files = $field_data;
                        fleekdash_log_debug("FleekDash: Using field '{$field_name}' for upload");
                        break;
                    }
                }
            }

            if (empty($files) || empty($files['name'])) {
                return ResponseService::error('No valid file data found', [], 400);
            }

            $uploaded_attachments = [];

            // Normalize file array structure (handle both single and multiple files)
            if (!is_array($files['name'])) {
                // Single file
                $files = [
                    'name' => [$files['name']],
                    'type' => [$files['type']],
                    'tmp_name' => [$files['tmp_name']],
                    'error' => [$files['error']],
                    'size' => [$files['size']]
                ];
            }

            fleekdash_log_debug("FleekDash: Processing " . count($files['name']) . " files");

            $allowed_types = [
                'image/jpeg',
                'image/jpg',
                'image/png',
                'image/gif',
                'image/webp',
                'application/pdf',
                'text/plain',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            ];

            $max_file_size = 5 * 1024 * 1024; // 5MB

            for ($i = 0; $i < count($files['name']); $i++) {
                // Skip if no file or upload error
                if ($files['error'][$i] !== UPLOAD_ERR_OK) {
                    $uploaded_attachments[] = [
                        'success' => false,
                        'filename' => $files['name'][$i] ?? 'unknown',
                        'error' => $this->getUploadErrorMessage($files['error'][$i])
                    ];
                    continue;
                }

                // Validate file type
                if (!in_array($files['type'][$i], $allowed_types)) {
                    $uploaded_attachments[] = [
                        'success' => false,
                        'filename' => $files['name'][$i],
                        'error' => 'File type not allowed: ' . $files['type'][$i]
                    ];
                    continue;
                }

                // Validate file size
                if ($files['size'][$i] > $max_file_size) {
                    $uploaded_attachments[] = [
                        'success' => false,
                        'filename' => $files['name'][$i],
                        'error' => 'File too large: ' . round($files['size'][$i] / 1024 / 1024, 2) . 'MB (max 5MB)'
                    ];
                    continue;
                }

                // Upload file to WordPress media library
                $attachment_id = $this->uploadToMediaLibrary([
                    'name' => $files['name'][$i],
                    'type' => $files['type'][$i],
                    'tmp_name' => $files['tmp_name'][$i],
                    'size' => $files['size'][$i]
                ]);

                if ($attachment_id) {
                    $uploaded_attachments[] = [
                        'success' => true,
                        'filename' => $files['name'][$i],
                        'attachment_id' => $attachment_id,
                        'url' => \wp_get_attachment_url($attachment_id),
                        'thumbnail' => wp_get_attachment_image_url($attachment_id, 'thumbnail')
                    ];
                    fleekdash_log_info("FleekDash: Successfully uploaded {$files['name'][$i]} as ID {$attachment_id}");
                } else {
                    $uploaded_attachments[] = [
                        'success' => false,
                        'filename' => $files['name'][$i],
                        'error' => 'Failed to upload to media library'
                    ];
                }
            }

            $successful_uploads = array_filter($uploaded_attachments, function ($upload) {
                return $upload['success'];
            });

            return ResponseService::success([
                'uploads' => $uploaded_attachments,
                'total_files' => count($files['name']),
                'successful_uploads' => count($successful_uploads),
                'failed_uploads' => count($uploaded_attachments) - count($successful_uploads)
            ], count($successful_uploads) . ' of ' . count($files['name']) . ' files uploaded successfully');

        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash: File upload error: " . $e->getMessage());
            return ResponseService::error('Upload failed: ' . $e->getMessage(), [], 500);
        }
    }

    /**
     * Upload file to WordPress media library
     *
     * @param array $file File data
     * @return int|false Attachment ID or false on failure
     */
    private function uploadToMediaLibrary($file)
    {
        if (!function_exists('wp_handle_upload')) {
            require_once(ABSPATH . 'wp-admin/includes/file.php');
        }

        if (!function_exists('wp_generate_attachment_metadata')) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
        }

        // Create proper $_FILES structure for wp_handle_upload
        $upload_file = [
            'name' => $file['name'],
            'type' => $file['type'],
            'tmp_name' => $file['tmp_name'],
            'error' => UPLOAD_ERR_OK,
            'size' => $file['size']
        ];

        // Handle the upload
        $uploaded_file = wp_handle_upload($upload_file, [
            'test_form' => false // Don't test for form submission
        ]);

        if (isset($uploaded_file['error'])) {
            fleekdash_log_error("FleekDash: Upload error: " . $uploaded_file['error']);
            return false;
        }

        // Create attachment post
        $attachment = [
            'post_mime_type' => $uploaded_file['type'],
            'post_title' => \call_user_func('sanitize_file_name', pathinfo($file['name'], PATHINFO_FILENAME)),
            'post_content' => '',
            'post_status' => 'inherit'
        ];

        $attachment_id = \wp_insert_attachment($attachment, $uploaded_file['file']);

        if (is_wp_error($attachment_id)) {
            fleekdash_log_error("FleekDash: Attachment creation error: " . $attachment_id->get_error_message());
            return false;
        }

        // Generate metadata for the attachment
        $attachment_data = \wp_generate_attachment_metadata($attachment_id, $uploaded_file['file']);
        \wp_update_attachment_metadata($attachment_id, $attachment_data);

        return $attachment_id;
    }

    /**
     * Get human-readable upload error message
     *
     * @param int $error_code PHP upload error code
     * @return string Error message
     */
    private function getUploadErrorMessage($error_code)
    {
        switch ($error_code) {
            case UPLOAD_ERR_INI_SIZE:
                return 'File exceeds upload_max_filesize directive in php.ini';
            case UPLOAD_ERR_FORM_SIZE:
                return 'File exceeds MAX_FILE_SIZE directive in HTML form';
            case UPLOAD_ERR_PARTIAL:
                return 'File was only partially uploaded';
            case UPLOAD_ERR_NO_FILE:
                return 'No file was uploaded';
            case UPLOAD_ERR_NO_TMP_DIR:
                return 'Missing temporary folder';
            case UPLOAD_ERR_CANT_WRITE:
                return 'Failed to write file to disk';
            case UPLOAD_ERR_EXTENSION:
                return 'File upload stopped by extension';
            default:
                return 'Unknown upload error';
        }
    }
}
