<?php
ob_start();
ob_clean();
require_once '../core/api.php';

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

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') throw new Exception('Método no permitido');

    // Detectar JSON (Videos) o FormData (Docs)
    $contentType = $_SERVER["CONTENT_TYPE"] ?? '';
    $isJson = strpos($contentType, 'application/json') !== false;
    $input = $isJson ? json_decode(file_get_contents('php://input'), true) : [];
    
    $type = $isJson ? ($input['type'] ?? '') : ($_POST['type'] ?? '');
    $staff_id_raw = $isJson ? ($input['staff_id'] ?? '') : ($_POST['staff_id'] ?? '');

    // --- LÓGICA CRÍTICA: GLOBAL VS INDIVIDUAL ---
    $staff_id = ($staff_id_raw === 'global' || $staff_id_raw === '') ? null : (int)$staff_id_raw;

    // CASO 1: VIDEO
    if ($type === 'video') {
        $title = $input['title'] ?? '';
        $url = $input['url'] ?? '';

        if (empty($title) || empty($url)) throw new Exception("Falta título o URL");

        $stmt = $pdo->prepare("INSERT INTO staff_academy (staff_id, title, youtube_url) VALUES (?, ?, ?)");
        $stmt->execute([$staff_id, $title, $url]);
        
        echo json_encode(['success' => true, 'message' => 'Video guardado correctamente']);
    }
    // CASO 2: DOCUMENTO
    elseif ($type === 'document') {
        $name = $_POST['name'] ?? '';
        if (empty($name)) throw new Exception("Falta nombre del documento");
        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== 0) throw new Exception("Error en el archivo");

        // Validar límites
        if ($staff_id === null) {
            $count = $pdo->query("SELECT COUNT(*) FROM staff_documents WHERE staff_id IS NULL")->fetchColumn();
        } else {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM staff_documents WHERE staff_id = ?");
            $stmt->execute([$staff_id]);
            $count = $stmt->fetchColumn();
        }
        if ($count >= 15) throw new Exception("Límite de documentos alcanzado.");

        // Guardar Archivo
        $uploadDir = __DIR__ . '/../uploads/staff_docs/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

        $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
        $fileName = time() . '_' . uniqid() . '.' . $ext;
        $targetPath = $uploadDir . $fileName;

        if (move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
            $dbPath = 'uploads/staff_docs/' . $fileName;
            $stmt = $pdo->prepare("INSERT INTO staff_documents (staff_id, file_name, file_path) VALUES (?, ?, ?)");
            $stmt->execute([$staff_id, $name, $dbPath]);
            echo json_encode(['success' => true, 'message' => 'Documento subido']);
        } else {
            throw new Exception("Error al mover archivo al servidor");
        }
    } else {
        throw new Exception("Tipo de subida no válido");
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
exit;
?>