<?php
session_start();
header('Content-Type: application/json');
include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$user_id = $_SESSION['user_id'];
$order_test_id = isset($_POST['order_test_id']) ? intval($_POST['order_test_id']) : 0;

if (!$order_test_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid test order']);
    exit();
}

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

$file = $_FILES['file'];
$allowed_types = ['image/jpeg', 'image/png', 'image/jpg', 'application/pdf'];
$max_size = 10 * 1024 * 1024;

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

if ($file['size'] > $max_size) {
    echo json_encode(['success' => false, 'message' => 'File too large']);
    exit();
}

$upload_dir = '../uploads/audiograms/' . date('Y/m/');
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = 'audiogram_' . $order_test_id . '_' . time() . '.' . $extension;
$file_path = $upload_dir . $filename;
$relative_path = 'uploads/audiograms/' . date('Y/m/') . $filename;

if (!move_uploaded_file($file['tmp_name'], $file_path)) {
    echo json_encode(['success' => false, 'message' => 'Failed to save file']);
    exit();
}

$files_json = json_encode([[
    'path' => $relative_path,
    'filename' => $filename,
    'uploaded_at' => date('Y-m-d H:i:s'),
    'uploaded_by' => $user_id
]]);

$update_sql = "UPDATE lab_order_tests 
               SET result_files = ?, status = 'IN_PROGRESS', started_at = NOW()
               WHERE order_test_id = ?";
$stmt = $conn->prepare($update_sql);
$stmt->bind_param("si", $files_json, $order_test_id);

if ($stmt->execute()) {
    echo json_encode([
        'success' => true,
        'message' => 'Audiogram uploaded successfully',
        'file_path' => $relative_path,
        'order_test_id' => $order_test_id
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update database']);
}

$conn->close();
?>