<?php

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

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

ini_wkvs_session();

check_user_permission('kampfrichter');

verify_csrf();

$type = 'kr';

$data = require $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';

// ---------- Get and sanitize input ----------
$personId = intval($_POST['personId'] ?? 0);
$gereatId = intval($_POST['geraetId'] ?? 0);

if ($gereatId < 1) {
    echo json_encode(['success' => false, 'message' => 'Kein Gerät angegeben']);
    exit;
}

if ($personId < 1) {
    echo json_encode(['success' => false, 'message' => 'Invalid ID']);
    exit;
}

// ---------- Step 2: Get values from DB ----------

$sqlQuery = "SELECT
                paf.`audiofile_id`,
                af.`file_path`,
                af.`file_name`,
                tu.`name`,
                tu.`vorname`
                FROM $db_tabelle_teilnehmende_audiofiles paf
                INNER JOIN $db_tabelle_audiofiles af
                    ON paf.`audiofile_id` = af.`id`
                LEFT JOIN $db_tabelle_teilnehmende tu
                    ON paf.`person_id` = tu.`id`
                WHERE paf.`person_id` = ?
                AND paf.`geraet_id` = ?
            ";

$stmt = $mysqli->prepare($sqlQuery);

$stmt->bind_param('ii', $personId, $gereatId);

$stmt->execute();

$result = $stmt->get_result();

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

if (count($rows) !== 1 || !isset($rows[0]['file_path']) || $rows[0]['file_path'] === null) {
    echo json_encode(['success' => false, 'message' => 'Keine Musik']);
    exit;
}

$row = $rows[0];

$folder = realpath($baseDir . '/externe-geraete/json');
if ($folder === false) {
    echo json_encode([
        'success' => false,
        'message' => 'Could not find displays folder.'
    ]);
    exit;
}

$filename = 'audio-id-'. $gereatId .'.json';
$filepath = $folder . '/' . $filename;

if (!is_writable($folder)) {
    echo json_encode(['success' => false, 'message' => 'Folder not writable.']);
    exit;
}


if (!is_file($filepath)){
    file_put_contents($filepath, []);
}


$json = [
    "audio_path" => $row['file_path'],
    "audio_name" => $row['file_name'],
    "start" => true,
    "person" => [
        "name" => $row['name'],
        "vorname" => $row['vorname']
    ]
];

$jsonData = json_encode($json);

// Write file
if (file_put_contents($filepath, $jsonData) === false) {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to write JSON file'
    ]);
    exit;
}



// ---------- Return JSON ----------
echo json_encode([
    'success' => true,
    'message' => 'Audio JSON updated successfully'
]);
exit;