<?php
// document-upload.php - Subir archivo a un tipo de documento
include __DIR__ . '/core/autoload.php';

$con = Database::getCon();

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['file'])) {
    header('Location: ./?view=documentation');
    exit;
}

$typeId = intval($_POST['document_type_id'] ?? 0);
$fileType = $_POST['file_type'] ?? '';

if ($typeId <= 0 || !in_array($fileType, ['pdf', 'image'])) {
    die('Parametros invalidos');
}

$file = $_FILES['file'];

// Validar tamano (max 10MB)
if ($file['size'] > 10 * 1024 * 1024) {
    die('Archivo muy grande (max 10MB)');
}

// Validar extension segun tipo
$allowed = [
    'pdf' => ['pdf'],
    'image' => ['jpg', 'jpeg', 'png', 'gif'],
];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowed[$fileType])) {
    die('Extension no permitida para el tipo ' . $fileType);
}

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

// Obtener nombre del tipo para el nombre del archivo
$stmt = $con->prepare("SELECT name FROM document_type WHERE id = ?");
$stmt->bind_param('i', $typeId);
$stmt->execute();
$typeData = $stmt->get_result()->fetch_assoc();
if (!$typeData) die('Tipo de documento no encontrado');

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

// Nombre unico: id_nombre_archivo
$safeName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', pathinfo($file['name'], PATHINFO_FILENAME));
$newName = $typeId . '_' . time() . '_' . $safeName . '.' . $ext;
$destPath = $uploadDir . $newName;

if (!move_uploaded_file($file['tmp_name'], $destPath)) {
    die('Error al subir el archivo');
}

// Guardar en DB
$stmt = $con->prepare("INSERT INTO document_file (document_type_id, file_name, file_path, file_type, file_size, uploaded_by) VALUES (?, ?, ?, ?, ?, ?)");
$filePath = 'uploads/documents/' . $newName;
$stmt->bind_param('isssii', $typeId, $file['name'], $filePath, $fileType, $file['size'], $userId);
$stmt->execute();

// Redirigir
header('Location: ./?view=documentation&type_id=' . $typeId);
exit;
