<?php

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

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

ini_wkvs_session();

check_user_permission('trainer');

verify_csrf();

ini_set('display_errors', 1);

$type = 'tr';

$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';

$ids = isset($_POST['ids']) ? htmlspecialchars(strip_tags(trim($_POST['ids'])), ENT_QUOTES) : '';
$user = intval($_SESSION['user_id_trainer']);


$arrayids = array_filter(array_map('trim', explode(',', $ids)));

if (!$arrayids || !is_array($arrayids) || count($arrayids) === 0) {
    http_response_code(422);
    exit;
}

if ($user <= 0) {
    http_response_code(422);
    exit;
}

$placeholders = [];
$values = [];
$types = '';

foreach ($arrayids as $id) {
    if ($id <= 0) {
        http_response_code(422);
        exit;
    }

    $sql = "SELECT bezahlt FROM $db_tabelle_teilnehmende WHERE id = ?";

    $checkstmt = $mysqli->prepare($sql);
    $checkstmt->bind_param("i", $id);
    if (!$checkstmt->execute()) {
        http_response_code(500);
        exit;
    }

    $checkstmt->bind_result($bezahlt);

    $checkstmt->fetch();

    $checkstmt->close();

    $sql2 = "SELECT COUNT(*) FROM $db_tabelle_warenkorb_startgebueren WHERE user_id = ? AND item_id = ?";

    $checkstmt2 = $mysqli->prepare($sql2);
    $checkstmt2->bind_param("ii", $user, $id);

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

    // Bind the result
    $checkstmt2->bind_result($countProd);
    $checkstmt2->fetch(); // fetch into $countProd

    $checkstmt2->close();

    if (isset($bezahlt) && in_array($bezahlt, [1,2]) && $countProd === 0) {
        $placeholders[] = '(?, ?)';
        $types .= 'ii';
        $values[] = $user;
        $values[] = $id;
    }
}

if ($values === [] || $placeholders === [] || $types === '') {
    http_response_code(406);
    exit;
}

$sql = "INSERT INTO `$db_tabelle_warenkorb_startgebueren` (user_id, item_id) VALUES " . implode(',', $placeholders);

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

$stmt->bind_param($types, ...$values);

$success = $stmt->execute();

$stmt->close();

if (!$success) {
    http_response_code(500);
    exit;
}

// Prepare statements once
$sSql = "SELECT `name`, `vorname`, `programm`, `betrag_bezahlt`, `verein`
         FROM $db_tabelle_teilnehmende
         WHERE id = ?";

$kats = db_select($mysqli, $db_tabelle_kategorien, '`preis`, `programm`');

$indexed_kat_preise = array_column($kats, 'preis', 'programm');

$vereine = db_select($mysqli, $db_tabelle_vereine, '`verein`, `konto`, `id`');

$indexed_vereine_kontos = array_column($vereine, 'konto', 'verein');

$indexed_vereine = array_column($vereine, 'id', 'verein');

$sStmt = $mysqli->prepare($sSql);

$id = null;

$sStmt->bind_param("i", $id);

$array_response_gebueren = [];
$array_response_abzuege = [];

$array_vereine = [];

foreach ($arrayids as $id) {

    // --- Turnerinnen ---

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

    $row = $sStmt->get_result()->fetch_assoc();

    if (!$row || !isset($row['programm'])) {
        http_response_code(500);
        exit;
    }

    $kat = $row['programm'];

    if (!isset($indexed_kat_preise[$kat])) {
        echo json_encode(['success' => false, 'message' => 'Der Preis einer Kat ist nicht definiert. Kat: '. $kat ]);
        http_response_code(500);
        exit;
    }

    $betrag_bezahlt = (float) $row['betrag_bezahlt'] ?? 0;

    $preis = ((float) $indexed_kat_preise[$kat]) - $betrag_bezahlt;

    $array_vereine[$row['verein']] ??= 0.00;

    $array_vereine[$row['verein']] += $preis;

    $formated_preis = number_format($preis, 2, '.', "'");

    // --- Build response ---
    $array_response_gebueren[$id] = [
        'turnerinName' => $row['name'],
        'turnerinVorname' => $row['vorname'],
        'programm' => $row['programm'],
        'preis' => $preis,
        'verein' => $row['verein'],
        'formated_preis'    => $formated_preis,
        'appendix' => ($betrag_bezahlt !== 0.00) ? ' (Red.)' : ''
    ];
}

foreach ($array_vereine as $verein => $betrag) {
    $array_response_abzuege[$verein]['betrag'] = $betrag;
    $array_response_abzuege[$verein]['max'] = $indexed_vereine_kontos[$verein] ?? 0;
    $array_response_abzuege[$verein]['vereinId'] = $indexed_vereine[$verein];
}

// Close statements once
$sStmt->close();


http_response_code(200);
echo json_encode([
    'success' => true,
    'message' => 'Zum Warenkorb hinzugefügt',
    'arrayGebueren' => $array_response_gebueren,
    'arrayAbzuege' => $array_response_abzuege
]);
exit;