<?php

if (!isset($baseDir)) $baseDir = $_SERVER['DOCUMENT_ROOT'];

require_once $baseDir . '/../scripts/session_functions.php';

ini_wkvs_session();

check_multiple_allowed_permissions(['trainer', 'wk_leitung']);

verify_csrf();

$isTrainer = isset($_SESSION['access_granted_trainer']) && $_SESSION['access_granted_trainer'];
$userId = $isTrainer ? intval($_SESSION['user_id_trainer'] ?? 0) : intval($_SESSION['user_id_wk_leitung'] ?? 0);

// Allow large uploads and enough memory for GD processing
ini_set('memory_limit', '256M');
ini_set('max_execution_time', '120');


if (!isset($_FILES['music_file']) || $_FILES['music_file']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode([
        'success' => false,
        'message' => 'Keine Musik' . $_FILES['music_file']['error'] ?? 'NO ERROR KNOWN'
    ]);
    exit;
}

$type = ($isTrainer) ? 'tr' : 'wkl';

$data = include $baseDir . '/../scripts/db/db-verbindung-script.php';

if ($data['success'] === false){
	echo json_encode(['success' => false, 'message' => $data['message']]);
    exit; 
}

require $baseDir . '/../scripts/db/db-tables.php';
require $baseDir . '/../scripts/db/db-functions.php';

$saveDir = '/files/music/';

$normalDir = $saveDir;

$uploadDir = $baseDir . $saveDir;

$maxLengthMusic = 0;

if ($isTrainer) {
    $geraet_id = (int) $_POST['geraetId'] ?? 0;

    $geraet_exists = db_get_var($mysqli, "SELECT 1 FROM $db_tabelle_disziplinen WHERE `id` = ?", [$geraet_id]);

    if ($geraet_exists === null) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalides Gerät angegeben.']);
        exit;
    }

    $geraet_max_duration_audio_db = db_get_var($mysqli, "SELECT `audiofile_max_duration` FROM $db_tabelle_disziplinen WHERE `id` = ?", [$geraet_id]);

    $maxLengthMusic = (int) $geraet_max_duration_audio_db;
}

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}


$tmpPath = $_FILES['music_file']['tmp_name'];
$originalName = $_FILES['music_file']['name'];
$extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

$allowedExt = ['mp3', 'wav', 'ogg'];
if (!in_array($extension, $allowedExt, true)) {
    echo json_encode(['success' => false, 'message' => 'Falsches Format (Endung)']);
    http_response_code(422);
    exit;
}

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($tmpPath);
$allowedMime = ['audio/mpeg', 'audio/wav', 'audio/x-wav', 'audio/ogg', 'application/ogg'];

if (!in_array($mimeType, $allowedMime, true)) {
    echo json_encode(['success' => false, 'message' => 'Dateiinhalt ist kein gültiges Audio']);
    http_response_code(422);
    exit;
}


$filename = uniqid('userupload_', true) . '.' . $extension;
$destination = $uploadDir . $filename;
$normalPath = $normalDir . $filename;


if (!move_uploaded_file($tmpPath, $destination)) {
    http_response_code(500);
    exit;
}

if ($isTrainer && $maxLengthMusic !== null && intval($maxLengthMusic) !== 0) {
    require $baseDir . '/../composer/vendor/autoload.php';

    $getID3 = new getID3;
    $fileInfo = $getID3->analyze($destination);

    if (empty($fileInfo['playtime_seconds'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Fehler beim Bestimmen der Musiklänge'
        ]);
        exit;
    }

    $duration = (float) $fileInfo['playtime_seconds'];

    if ($duration > intval($maxLengthMusic)) {
        unlink($destination);
        echo json_encode([
            'success' => false,
            'message' => 'Musik zu lange (über ' . intval($maxLengthMusic) . ' Sekunden)'
        ]);
        http_response_code(422);
        exit;
    }
}


$sql = "INSERT INTO $db_tabelle_audiofiles (`file_name`,`file_path`,`edited_by`) VALUES (?, ?, ?)";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssi", $originalName, $normalPath, $userId);

if (!$stmt->execute()) {
    http_response_code(500);
    exit;
}

$id = $mysqli->insert_id;

$stmt->close();

echo json_encode([
    'success' => true,
    'id' => $id,
    'filename' => $originalName,
    'filepath' => $normalPath
]);
