<?php
// study-upload.php - Subir archivo a patient_study (estudios o anexos, opcionalmente por consulta)
include __DIR__ . '/core/autoload.php';

$con = Database::getCon();

// Category → view name mapping (category is singular, view name is plural)
$catToView = ['study' => 'studies', 'anexo' => 'anexos'];
$viewName = 'studies';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['file'])) {
    header('Location: ./?view=' . urlencode($viewName) . '&pacient_id=' . intval($_POST['pacient_id'] ?? 0));
    exit;
}

$pacientId     = intval($_POST['pacient_id'] ?? 0);
$evaluationId  = intval($_POST['evaluation_id'] ?? 0) ?: null;
$category      = $_POST['category'] ?? 'study';
$studyType     = trim($_POST['study_type'] ?? '');
$title         = trim($_POST['title'] ?? '');
$description   = trim($_POST['description'] ?? '');
$fileType      = $_POST['file_type'] ?? '';

if (isset($catToView[$category])) {
    $viewName = $catToView[$category];
}

if ($pacientId <= 0 || !in_array($category, ['study', 'anexo']) || $studyType === '' || !in_array($fileType, ['pdf', 'image'])) {
    header('Location: ./?view=' . urlencode($viewName) . '&pacient_id=' . $pacientId . '&error=params');
    exit;
}

$file = $_FILES['file'];

// Validar tamaño (max 10MB)
if ($file['size'] > 10 * 1024 * 1024) {
    header('Location: ./?view=' . urlencode($viewName) . '&pacient_id=' . $pacientId . '&error=size');
    exit;
}

// Validar extensión
$allowed = [
    'pdf' => ['pdf'],
    'image' => ['jpg', 'jpeg', 'png', 'gif'],
];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowed[$fileType])) {
    header('Location: ./?view=' . urlencode($viewName) . '&pacient_id=' . $pacientId . '&error=ext');
    exit;
}

$uploadDir = __DIR__ . '/uploads/patient_studies/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$userId = $_SESSION['user_id'] ?? null;

// Nombre único: pacientId[_evalId]_timestamp_nombre.ext
$prefix = $pacientId . ($evaluationId ? '_e' . $evaluationId : '');
$safeName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', pathinfo($file['name'], PATHINFO_FILENAME));
$newName = $prefix . '_' . time() . '_' . $safeName . '.' . $ext;
$destPath = $uploadDir . $newName;

if (!move_uploaded_file($file['tmp_name'], $destPath)) {
    header('Location: ./?view=' . urlencode($viewName) . '&pacient_id=' . $pacientId . '&error=upload');
    exit;
}

$stmt = $con->prepare("INSERT INTO patient_study (pacient_id, evaluation_id, category, study_type, title, description, file_name, file_path, file_type, file_size, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$filePath = 'uploads/patient_studies/' . $newName;
$stmt->bind_param('iisssssssis', $pacientId, $evaluationId, $category, $studyType, $title, $description, $file['name'], $filePath, $fileType, $file['size'], $userId);
$stmt->execute();

header('Location: ./?view=' . urlencode($viewName) . '&pacient_id=' . $pacientId . '&uploaded=1');
exit;