<?php
/**
 * AJAX: File Upload
 * Upload patient documents and case attachments
 * Method: POST
 */

require_once '../config/config.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

session_start();
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

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

$caseId = (int)($_POST['case_id'] ?? 0);
$fileType = $_POST['file_type'] ?? 'document'; // document, prescription, report

if (empty($_FILES['file'])) {
    echo json_encode(['success' => false, 'error' => 'No file uploaded']);
    exit;
}

$file = $_FILES['file'];

// Validate file size (max 10MB)
if ($file['size'] > 10 * 1024 * 1024) {
    echo json_encode(['success' => false, 'error' => 'File too large. Max 10MB']);
    exit;
}

// Validate file type
$allowedTypes = [
    'image/jpeg', 'image/png', 'image/gif',
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
];

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!in_array($mimeType, $allowedTypes)) {
    echo json_encode(['success' => false, 'error' => 'Invalid file type']);
    exit;
}

// Create upload directory
$uploadDir = '../assets/uploads/';
if ($caseId > 0) {
    $uploadDir .= "cases/$caseId/";
} else {
    $uploadDir .= "temp/";
}

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// Generate unique filename
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = time() . '_' . bin2hex(random_bytes(8)) . '.' . $extension;
$filepath = $uploadDir . $filename;

if (move_uploaded_file($file['tmp_name'], $filepath)) {
    // Save to database if case exists
    if ($caseId > 0) {
        $pdo = getDB();
        $userId = $_SESSION['user_id'];
        
        // Verify case belongs to doctor
        $stmt = $pdo->prepare("SELECT id FROM cases WHERE id = ? AND user_id = ?");
        $stmt->execute([$caseId, $userId]);
        if ($stmt->fetch()) {
            $stmt = $pdo->prepare("INSERT INTO case_attachments (case_id, filename, original_name, file_type, mime_type, file_size, uploaded_at) 
                                  VALUES (?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $caseId, $filename, $file['name'], $fileType, $mimeType, $file['size']
            ]);
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'File uploaded successfully',
        'data' => [
            'filename' => $filename,
            'original_name' => $file['name'],
            'size' => formatFileSize($file['size']),
            'path' => str_replace('../', '', $filepath)
        ]
    ]);
} else {
    echo json_encode(['success' => false, 'error' => 'Failed to upload file']);
}
?>