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


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

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

ini_wkvs_session();

check_user_permission('trainer');

verify_csrf();

$audiofileId    = intval($_POST['musicId'] ?? 0);
$personId = intval($_POST['turnerinId'] ?? 0);
$geraetId = intval($_POST['geraetId'] ?? 0);

if ($audiofileId < 1 || $personId < 1 || $geraetId < 1) {
    echo json_encode(['success' => false, 'message' => 'Ungültige Eingabe.']);
    http_response_code(400);
    exit;
}

$type = 'tr';

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

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

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

$sql = "INSERT INTO $db_tabelle_teilnehmende_audiofiles (`person_id`, `geraet_id`, `audiofile_id`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `audiofile_id` = VALUES(`audiofile_id`)";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param("iii", $personId, $geraetId, $audiofileId);

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

$stmt->close();

$sql = "SELECT name, vorname FROM $db_tabelle_teilnehmende WHERE id = ?";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $turnerinId);

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

$result = $stmt->get_result();
$rows = $result->fetch_all(MYSQLI_ASSOC);

$stmt->close();

$_SESSION['form_message_type'] = 1;

if (!isset($rows) || !is_array($rows) || count($rows) !== 1) {
    $_SESSION['form_message'] = 'Musik aktualisiert';
} else {
    $_SESSION['form_message'] = 'Musik für '.$rows[0]['name'].' '.$rows[0]['vorname'].' aktualisiert';
}

$mysqli->close();

echo json_encode(['success' => true]);





