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

$con = Database::getCon();

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

$userId = intval($_POST['user_id'] ?? 0);
$docTypeId = intval($_POST['document_type_id'] ?? 0);
$fileType = $_POST['file_type'] ?? '';

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

// Verificar que el usuario existe
$stmt = $con->prepare("SELECT id, role FROM user WHERE id = ?");
$stmt->bind_param('i', $userId);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
if (!$user) {
    die('Usuario no encontrado');
}

// Verificar que el tipo de documento existe y es aplicable al role
$stmt = $con->prepare("SELECT id FROM personnel_document_type WHERE id = ? AND applies_to = ?");
$stmt->bind_param('is', $docTypeId, $user['role']);
$stmt->execute();
if (!$stmt->get_result()->fetch_assoc()) {
    die('Tipo de documento no valido para el rol del usuario');
}

$file = $_FILES['file'];

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

$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);
}

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

// Nombre unico: personnel_{userId}_{docTypeId}_{timestamp}_{filename}
$safeName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', pathinfo($file['name'], PATHINFO_FILENAME));
$newName = 'personnel_' . $userId . '_' . $docTypeId . '_' . time() . '_' . $safeName . '.' . $ext;
$destPath = $uploadDir . $newName;

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

// Si ya existe un archivo para este usuario+tipo, reemplazar (eliminar anterior)
$stmt = $con->prepare("SELECT id, file_path FROM personnel_document_file WHERE user_id = ? AND document_type_id = ?");
$stmt->bind_param('ii', $userId, $docTypeId);
$stmt->execute();
$existing = $stmt->get_result()->fetch_assoc();

if ($existing) {
    $oldPath = __DIR__ . '/' . $existing['file_path'];
    if (file_exists($oldPath)) {
        unlink($oldPath);
    }
    $del = $con->prepare("DELETE FROM personnel_document_file WHERE id = ?");
    $del->bind_param('i', $existing['id']);
    $del->execute();
}

// Guardar nuevo registro
$filePath = 'uploads/documents/' . $newName;
$stmt = $con->prepare("INSERT INTO personnel_document_file (user_id, document_type_id, file_name, file_path, file_type, file_size, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('iissiii', $userId, $docTypeId, $file['name'], $filePath, $fileType, $file['size'], $sessionUserId);
$stmt->execute();

// Redirigir al detalle del personal
header('Location: ./?view=personnel-detail&user_id=' . $userId);
exit;
