<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Dental File Upload Handlers
 * Handles secure file uploads with progress tracking and database integration
 */

// AJAX handler for file upload
add_action('wp_ajax_upload_dental_file', 'handle_dental_file_upload');
add_action('wp_ajax_nopriv_upload_dental_file', 'handle_dental_file_upload');

function handle_dental_file_upload() {
    // Verify nonce for security
    if (!wp_verify_nonce($_POST['nonce'], 'dental_file_upload')) {
        wp_die(json_encode([
            'success' => false,
            'message' => 'Security check failed'
        ], JSON_UNESCAPED_UNICODE));
    }
    
    // Check if user is logged in
    if (!is_user_logged_in()) {
        wp_die(json_encode([
            'success' => false,
            'message' => 'User not authenticated'
        ], JSON_UNESCAPED_UNICODE));
    }
    
    // Check if file was uploaded
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        wp_die(json_encode([
            'success' => false,
            'message' => 'No file uploaded or upload error'
        ], JSON_UNESCAPED_UNICODE));
    }
    
    $file = $_FILES['file'];
    $user_id = intval($_POST['user_id']);
    $dental_id = !empty($_POST['dental_id']) ? sanitize_text_field($_POST['dental_id']) : null;
    
    // Validate file
    $validation = validate_uploaded_file($file);
    if (!$validation['is_valid']) {
        wp_die(json_encode([
            'success' => false,
            'message' => $validation['message']
        ], JSON_UNESCAPED_UNICODE));
    }
    
    // Process file upload
    $result = process_file_upload($file, $user_id, $dental_id);
    
    if ($result['success']) {
        wp_die(json_encode([
            'success' => true,
            'data' => $result['data']
        ], JSON_UNESCAPED_UNICODE));
    } else {
        wp_die(json_encode([
            'success' => false,
            'message' => $result['message']
        ], JSON_UNESCAPED_UNICODE));
    }
}

// AJAX handler for file deletion
add_action('wp_ajax_delete_dental_file', 'handle_dental_file_delete');
add_action('wp_ajax_nopriv_delete_dental_file', 'handle_dental_file_delete');

function handle_dental_file_delete() {
    // Verify nonce for security
    if (!wp_verify_nonce($_POST['nonce'], 'dental_file_delete')) {
        wp_die(json_encode([
            'success' => false,
            'message' => 'Security check failed'
        ], JSON_UNESCAPED_UNICODE));
    }
    
    // Check if user is logged in
    if (!is_user_logged_in()) {
        wp_die(json_encode([
            'success' => false,
            'message' => 'User not authenticated'
        ], JSON_UNESCAPED_UNICODE));
    }
    
    $attachment_id = intval($_POST['attachment_id']);
    
    // Delete file
    $result = delete_dental_file($attachment_id);
    
    wp_die(json_encode($result, JSON_UNESCAPED_UNICODE));
}

/**
 * Validate uploaded file
 */
function validate_uploaded_file($file) {
    $max_size = 200 * 1024 * 1024; // 200 MB
    $allowed_types = [
        // Images
        'image/png', 'image/jpeg', 'image/webp', 'image/heic', 'image/heif',
        'image/heic-sequence', 'image/heif-sequence',
        // Videos
        'video/mp4', 'video/webm', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska',
        // Audio
        'audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/mp4', 'audio/aac', 'audio/flac',
        // Archives
        'application/zip', 'application/x-zip-compressed', 'application/x-zip', 'application/zip-compressed',
        'application/vnd.rar', 'application/x-rar-compressed',
        'application/x-7z-compressed', 'application/x-tar', 'application/gzip',
        // 3D & CAD
        'application/vnd.ms-pki.stl', 'application/sla', 'application/x-navistyle',
        'text/vnd.fly',
        // Documents
        'application/pdf', 'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'text/csv', 'text/plain', 'application/rtf'
    ];
    
    // Check file size
    if ($file['size'] > $max_size) {
        return [
            'is_valid' => false,
            'message' => 'File size exceeds 200 MB limit'
        ];
    }
    
    // Check file type
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    // Add more ZIP MIME types that might be detected
    $zip_mime_types = [
        'application/zip',
        'application/x-zip-compressed',
        'application/octet-stream', // Sometimes ZIP files are detected as this
        'application/x-zip',
        'application/zip-compressed'
    ];
    
    // Check if it's a ZIP file by extension and allow it
    $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if ($file_extension === 'zip' && in_array($mime_type, $zip_mime_types)) {
        $mime_type = 'application/zip'; // Normalize to standard ZIP MIME type
    }
    
    // Fallback: Allow files with valid extensions even if MIME type is generic
    $valid_extensions = [
        'zip', 'rar', '7z', 'tar', 'gz',
        'png', 'jpg', 'jpeg', 'webp', 'heic', 'heif',
        'mp4', 'webm', 'mov', 'avi', 'mkv',
        'mp3', 'wav', 'ogg', 'm4a', 'aac', 'flac',
        'stl', 'fly',
        'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'csv', 'txt', 'rtf'
    ];
    
    if (!in_array($mime_type, $allowed_types)) {
        // If MIME type is generic but extension is valid, allow it
        if ($mime_type === 'application/octet-stream' && in_array($file_extension, $valid_extensions)) {
            // Allow the file
        } else {
            return [
                'is_valid' => false,
                'message' => 'File type not allowed. Detected MIME: ' . $mime_type . ', Extension: ' . $file_extension
            ];
        }
    }
    
    // Additional security checks
    if (!is_uploaded_file($file['tmp_name'])) {
        return [
            'is_valid' => false,
            'message' => 'Invalid upload'
        ];
    }
    
    return ['is_valid' => true];
}

/**
 * Process file upload using FTP
 */
function process_file_upload($file, $user_id, $dental_id = null) {
    global $wpdb;
    
    try {
        // Generate secure file information
        $file_info = generate_secure_file_info($file, $user_id, $dental_id);
        
        // FTP Configuration
        $ftp_host = '78.110.121.158';
        $ftp_user = 'app@sv1.etiuse.com';
        $ftp_pass = 'F)?Zm+EzlP7w';
        $ftp_port = 21;
        
        // File paths - Updated for new FTP structure (public_html root)
        $remote_dir = '/dental-files/' . $file_info['file_path'];
        $remote_file = $remote_dir . '/' . $file_info['stored_name'];
        
        // Web URL for the file - Updated for shorter URLs
        $web_base_url = 'https://sv1.etiuse.com';
        $web_file_url = $web_base_url . '/dental-files/' . $file_info['file_path'] . '/' . $file_info['stored_name'];
        
        // Connect to FTP server
        $ftp_conn = ftp_connect($ftp_host, $ftp_port, 30);
        if (!$ftp_conn) {
            return [
                'success' => false,
                'message' => 'Failed to connect to FTP server'
            ];
        }
        
        // Login to FTP
        if (!ftp_login($ftp_conn, $ftp_user, $ftp_pass)) {
            ftp_close($ftp_conn);
            return [
                'success' => false,
                'message' => 'Failed to login to FTP server'
            ];
        }
        
        // Enable passive mode
        ftp_pasv($ftp_conn, true);
        
        // Create remote directory recursively
        $dir_parts = explode('/', trim($remote_dir, '/'));
        $current_path = '';
        
        foreach ($dir_parts as $part) {
            if (!empty($part)) {
                $current_path .= '/' . $part;
                
                // Check if directory exists
                $dir_exists = false;
                
                // Try to change to the directory to see if it exists
                if (ftp_chdir($ftp_conn, $current_path)) {
                    $dir_exists = true;
                    // Change back to root
                    ftp_chdir($ftp_conn, '/');
                } else {
                    // Directory doesn't exist, try to create it
                    if (!ftp_mkdir($ftp_conn, $current_path)) {
                        ftp_close($ftp_conn);
                        return [
                            'success' => false,
                            'message' => 'Failed to create FTP directory: ' . $current_path
                        ];
                    }
                }
            }
        }
        
        // Upload file
        if (!ftp_put($ftp_conn, $remote_file, $file['tmp_name'], FTP_BINARY)) {
            ftp_close($ftp_conn);
            return [
                'success' => false,
                'message' => 'Failed to upload file via FTP: ' . $remote_file
            ];
        }
        
        // Close FTP connection
        ftp_close($ftp_conn);
        
        // Generate file hash for integrity (from uploaded file)
        $file_hash = hash_file('sha256', $file['tmp_name']);
        
        // Prepare file data for database - only after successful upload
        $file_data = [
            'original_name' => $file['name'],
            'stored_name' => $file_info['stored_name'],
            'file_path' => $file_info['file_path'],
            'file_url' => $web_file_url,
            'file_size' => $file['size'],
            'mime_type' => $file_info['mime_type'],
            'file_extension' => pathinfo($file['name'], PATHINFO_EXTENSION),
            'uploaded_by' => $user_id,
            'is_temp' => $dental_id ? 0 : 1, // If dental_id is provided, it's permanent
            'dental_id' => $dental_id,
            'file_hash' => $file_hash,
            'file_status' => 'active',
            'deleted_at' => null
        ];
        
        // Store file information in database - only after successful upload
        $result = store_file_in_database($file_data);
        
        if (!$result['success']) {
            // Clean up file if database storage failed
            // Note: We can't easily delete via FTP here, but the file will be cleaned up later
            return $result;
        }
        
        // Add the attachment ID to the response
        $file_data['attachment_id'] = $result['attachment_id'];
        
        return [
            'success' => true,
            'data' => $file_data
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'message' => 'Upload processing error: ' . $e->getMessage()
        ];
    }
}

/**
 * Generate secure file information
 */
function generate_secure_file_info($file, $user_id, $dental_id = null) {
    // Generate secure stored name
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $stored_name = uniqid() . '_' . time() . '.' . $extension;
    
    // Get username for folder name
    $user = get_userdata($user_id);
    $username = $user ? $user->user_login : 'user_' . $user_id;
    
    // Determine file path - always use permanent directory structure
    $year = date('Y');
    $month = date('m');
    
    if ($dental_id) {
        // If dental_id is provided, use permanent structure
        $file_path = "{$year}/{$month}/{$username}/dental_{$dental_id}";
    } else {
        // For initial uploads, use temporary structure but in permanent directory
        $file_path = "{$year}/{$month}/{$username}";
    }
    
    // Get MIME type
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    return [
        'stored_name' => $stored_name,
        'file_path' => $file_path,
        'mime_type' => $mime_type
    ];
}

/**
 * Store file information in database
 */
function store_file_in_database($file_data) {
    global $wpdb;
    
    // Use the new dental_attachments table
    $table_name = $wpdb->prefix . 'dental_attachments';
    
    // Prepare data for the new table structure
    $attachment_data = [
        'original_name' => $file_data['original_name'],
        'stored_name' => $file_data['stored_name'],
        'file_size' => $file_data['file_size'],
        'mime_type' => $file_data['mime_type'],
        'file_extension' => $file_data['file_extension'],
        'file_path' => $file_data['file_path'],
        'file_url' => $file_data['file_url'],
        'uploaded_by' => $file_data['uploaded_by'],
        'is_temp' => $file_data['is_temp'],
        'dental_id' => $file_data['dental_id'],
        'file_hash' => $file_data['file_hash'],
        'file_status' => $file_data['file_status'],
        'deleted_at' => $file_data['deleted_at']
    ];
    
    $result = $wpdb->insert($table_name, $attachment_data);
    
    if ($result) {
        return ['success' => true, 'attachment_id' => $wpdb->insert_id];
    } else {
        return [
            'success' => false,
            'message' => 'Failed to store file information: ' . $wpdb->last_error
        ];
    }
}
/**
 * Delete dental file (Soft Delete - Database Only)
 */
function delete_dental_file($attachment_id) {
    global $wpdb;
    
    // Get file information
    $table_name = $wpdb->prefix . 'dental_attachments';
    $file_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table_name} WHERE id = %d AND file_status = 'active'", $attachment_id));
    
    if (!$file_data) {
        return [
            'success' => false,
            'message' => 'File not found or already deleted'
        ];
    }
    
    // Mark as deleted in database (soft delete only)
    $wpdb->update(
        $table_name,
        [
            'file_status' => 'deleted',
            'deleted_at' => current_time('mysql')
        ],
        ['id' => $attachment_id]
    );
    
    return ['success' => true];
}
