<?php
/**
 * API: File Upload
 * Handle file uploads via AJAX
 */

require_once '../config/config.php';
require_once '../includes/auth.php';
require_once '../includes/upload-handler.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;
}

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

$type = $_POST['type'] ?? 'temp';
$caseId = isset($_POST['case_id']) ? (int)$_POST['case_id'] : null;

$uploader = getUploadHandler();
$result = $uploader->upload($_FILES['file'], $type, $caseId);

if ($result['success']) {
    // Save to database if case attachment
    if ($type == 'cases' && $caseId) {
        $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, 
                $result['filename'], 
                $result['original_name'], 
                $type, 
                $result['mime_type'], 
                $result['size']
            ]);
            $result['attachment_id'] = $pdo->lastInsertId();
        }
    }
    
    echo json_encode($result);
} else {
    http_response_code(400);
    echo json_encode($result);
}