<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $user_id = Auth::check();

    if (!isset($_FILES['file'])) {
        throw new Exception("No se ha seleccionado ningún archivo.");
    }

    $file = $_FILES['file'];
    $name = isset($_POST['name']) ? $_POST['name'] : $file['name'];
    $type = isset($_POST['type']) ? $_POST['type'] : 'image'; // image, video, audio, etc.
    $description = isset($_POST['description']) ? $_POST['description'] : '';
    $price = isset($_POST['price']) ? (int)$_POST['price'] : 0;
    $is_public = isset($_POST['is_public']) ? (int)$_POST['is_public'] : 0;

    // Validar tipo enum
    $allowed_types = ['image', 'video', 'audio', 'pdf', 'documento', 'otro'];
    if (!in_array($type, $allowed_types)) {
        $type = 'otro';
    }

    // Carpeta de destino
    $upload_dir = '../../uploads/vault/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    // Generar nombre de archivo único
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $new_filename = 'vault_' . $user_id . '_' . bin2hex(random_bytes(8)) . '.' . $extension;
    $target_file = $upload_dir . $new_filename;

    // Subir archivo
    if (move_uploaded_file($file['tmp_name'], $target_file)) {
        // En producción real esto sería la URL absoluta o relativa al servidor
        $file_url = 'server/uploads/vault/' . $new_filename;

        // Registrar en BD
        $stmt = $pdo->prepare("INSERT INTO chest_items (user_id, name, type, file_url, price, is_public, description) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$user_id, $name, $type, $file_url, $price, $is_public, $description]);
        
        $item_id = $pdo->lastInsertId();

        echo json_encode([
            'success' => true,
            'message' => 'Archivo subido correctamente al cofre.',
            'data' => [
                'id' => $item_id,
                'name' => $name,
                'type' => $type,
                'file_url' => $file_url,
                'price' => $price,
                'is_public' => $is_public
            ]
        ]);
    } else {
        throw new Exception("Error al mover el archivo al servidor.");
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
