<?php
require_once __DIR__ . '/../lib.php';

hw_require_auth(['client']);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    hw_json(['success' => false, 'error' => 'Method not allowed'], 405);
}

$authUser = hw_get_auth_user();

try {
    // Check if file was uploaded
    if (!isset($_FILES['report']) || $_FILES['report']['error'] !== UPLOAD_ERR_OK) {
        $error = $_FILES['report']['error'] ?? UPLOAD_ERR_NO_FILE;
        $errorMsg = match($error) {
            UPLOAD_ERR_NO_FILE => 'No file uploaded',
            UPLOAD_ERR_INI_SIZE => 'File exceeds server limit',
            UPLOAD_ERR_FORM_SIZE => 'File exceeds form limit',
            UPLOAD_ERR_PARTIAL => 'File upload incomplete',
            UPLOAD_ERR_NO_TMP_DIR => 'Server configuration error',
            default => 'Upload error'
        };
        hw_json(['success' => false, 'error' => $errorMsg], 400);
    }
    
    $file = $_FILES['report'];
    
    // Validate file size (10 MB max)
    $maxSize = 10 * 1024 * 1024;
    if ($file['size'] > $maxSize) {
        hw_json(['success' => false, 'error' => 'File exceeds 10 MB limit'], 413);
    }
    
    // Validate file type
    $allowed = ['pdf', 'jpg', 'jpeg', 'png', 'csv', 'txt'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    if (!in_array($ext, $allowed)) {
        hw_json(['success' => false, 'error' => 'Invalid file type. Allowed: PDF, JPG, PNG, CSV, TXT'], 400);
    }
    
    // Validate MIME type for basic safety
    $mimeAllowed = ['application/pdf', 'image/jpeg', 'image/png', 'text/plain', 'text/csv', 'application/vnd.ms-excel'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    if (!in_array($mime, $mimeAllowed)) {
        hw_json(['success' => false, 'error' => 'File MIME type not allowed'], 400);
    }
    
    // Create upload directory
    $uploadDir = __DIR__ . '/../../uploads/medical-reports/' . $authUser['id'] . '/';
    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true)) {
            hw_json(['success' => false, 'error' => 'Failed to create upload directory'], 500);
        }
    }
    
    // Generate unique filename
    $filename = uniqid('report_', true) . '.' . $ext;
    $targetPath = $uploadDir . $filename;
    
    // Move uploaded file
    if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
        hw_json(['success' => false, 'error' => 'Failed to save file'], 500);
    }
    
    // Create medical_reports table if it doesn't exist
    $db = hw_db();
    $db->exec("
        CREATE TABLE IF NOT EXISTS medical_reports (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            filename VARCHAR(255) NOT NULL,
            original_filename VARCHAR(255) NOT NULL,
            file_path VARCHAR(512) NOT NULL,
            file_size INT NOT NULL,
            mime_type VARCHAR(100),
            uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            KEY (user_id, uploaded_at)
        )
    ");
    
    // Store metadata in database
    $stmt = $db->prepare("
        INSERT INTO medical_reports (user_id, filename, original_filename, file_path, file_size, mime_type)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->execute([
        $authUser['id'],
        $filename,
        basename($file['name']),
        str_replace(__DIR__ . '/../../', '', $targetPath),
        $file['size'],
        $mime
    ]);
    
    hw_json([
        'success' => true,
        'message' => 'Medical report uploaded successfully',
        'id' => $db->lastInsertId(),
        'filename' => $filename
    ]);
    
} catch (PDOException $e) {
    error_log('Medical report upload DB error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Database error'], 500);
} catch (Exception $e) {
    error_log('Medical report upload error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Server error'], 500);
