<?php
/**
 * File handling utility
 *
 * @package SPAI_Contact_Form
 */

class SPAI_File_Handler {
    
    /**
     * Process file uploads
     */
    public function process_uploads($files, $form_id) {
        $upload_dir = $this->get_upload_dir($form_id);
        $uploaded_files = array();
        $errors = array();
        
        // Get settings
        $settings = get_option('spai_contact_form_settings');
        $max_size = isset($settings['max_file_size']) ? $settings['max_file_size'] * 1024 * 1024 : 10 * 1024 * 1024;
        $max_attachments = isset($settings['max_attachments']) ? $settings['max_attachments'] : 2;
        $allowed_types = isset($settings['allowed_file_types']) ? $settings['allowed_file_types'] : array('pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png');
        
        $file_count = 0;
        
        // Restructure multiple files from single input fields
        $processed_files = array();
        foreach ($files as $field_name => $file_data) {
            // Check if this is a multiple file upload (arrays in name, type, etc.)
            if (is_array($file_data['name'])) {
                // Multiple files from single input - restructure them
                for ($i = 0; $i < count($file_data['name']); $i++) {
                    $processed_files[$field_name . '_' . $i] = array(
                        'name' => $file_data['name'][$i],
                        'type' => $file_data['type'][$i],
                        'tmp_name' => $file_data['tmp_name'][$i],
                        'error' => $file_data['error'][$i],
                        'size' => $file_data['size'][$i],
                        'original_field' => $field_name
                    );
                }
            } else {
                // Single file - keep as is
                $processed_files[$field_name] = $file_data;
                $processed_files[$field_name]['original_field'] = $field_name;
            }
        }
        
        foreach ($processed_files as $field_name => $file) {
            // Skip if no file uploaded
            if (empty($file['name']) || $file['error'] === UPLOAD_ERR_NO_FILE) {
                continue;
            }
            
            // Check max attachments
            if ($file_count >= $max_attachments) {
                $errors[] = sprintf(__('Maximum number of files exceeded (Max: %d)', 'spai-contact-form'), $max_attachments);
                break;
            }
            
            // Check for upload errors
            if ($file['error'] !== UPLOAD_ERR_OK) {
                $errors[] = sprintf(__('Upload failed for %s', 'spai-contact-form'), $file['name']);
                continue;
            }
            
            // Check file size
            if ($file['size'] > $max_size) {
                $errors[] = sprintf(__('%s exceeds maximum file size', 'spai-contact-form'), $file['name']);
                continue;
            }
            
            // Check file type
            $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            if (!in_array($file_extension, $allowed_types)) {
                $errors[] = sprintf(__('%s has invalid file type', 'spai-contact-form'), $file['name']);
                continue;
            }
            
            // Generate unique filename
            $unique_name = $this->generate_unique_filename($file['name']);
            $destination = $upload_dir['path'] . '/' . $unique_name;
            
            // Move uploaded file
            if (move_uploaded_file($file['tmp_name'], $destination)) {
                $uploaded_files[] = array(
                    'name' => $file['name'],
                    'unique_name' => $unique_name,
                    'type' => $file['type'],
                    'size' => $file['size'],
                    'path' => $destination,
                    'url' => $upload_dir['url'] . '/' . $unique_name,
                    'field' => isset($file['original_field']) ? $file['original_field'] : $field_name
                );
                $file_count++;
            } else {
                $errors[] = sprintf(__('Failed to save %s', 'spai-contact-form'), $file['name']);
            }
        }
        
        if (!empty($errors)) {
            return array(
                'success' => false,
                'errors' => $errors
            );
        }
        
        return array(
            'success' => true,
            'files' => $uploaded_files
        );
    }
    
    /**
     * Get upload directory
     */
    private function get_upload_dir($form_id) {
        $upload_dir = wp_upload_dir();
        
        // Create directory structure
        $subdir = sprintf(
            '/%s/%s/%s/%d',
            SPAI_CONTACT_FORM_UPLOAD_DIR,
            date('Y'),
            date('m'),
            $form_id
        );
        
        $dir = $upload_dir['basedir'] . $subdir;
        $url = $upload_dir['baseurl'] . $subdir;
        
        // Create directory if it doesn't exist
        if (!file_exists($dir)) {
            wp_mkdir_p($dir);
            
            // Add index.php to prevent directory listing
            file_put_contents($dir . '/index.php', '<?php // Silence is golden');
        }
        
        return array(
            'path' => $dir,
            'url' => $url
        );
    }
    
    /**
     * Generate unique filename
     */
    private function generate_unique_filename($original_name) {
        $info = pathinfo($original_name);
        $extension = isset($info['extension']) ? '.' . $info['extension'] : '';
        $filename = sanitize_file_name($info['filename']);
        
        // Generate unique ID
        $unique_id = wp_generate_password(8, false);
        
        return $filename . '-' . $unique_id . $extension;
    }
    
    /**
     * Delete file
     */
    public function delete_file($file_path) {
        if (file_exists($file_path) && is_file($file_path)) {
            return unlink($file_path);
        }
        
        return false;
    }
    
    /**
     * Get file download URL
     */
    public function get_download_url($file_path) {
        $upload_dir = wp_upload_dir();
        $base_path = $upload_dir['basedir'];
        $base_url = $upload_dir['baseurl'];
        
        // Convert path to URL
        $relative_path = str_replace($base_path, '', $file_path);
        
        return $base_url . $relative_path;
    }
}
