<?php

use TCPDF;

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

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

ini_wkvs_session();

check_user_permission('kampfrichter');

verify_csrf();

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

$type = 'kr';
$data = require $baseDir . '/../scripts/db/db-verbindung-script.php';

if ($data['success'] === false) {
    header('Content-Type: application/json');
	echo json_encode(['success' => false, 'message' => $data['message']]);
	exit;
}

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

$wkName = db_get_var($mysqli, "SELECT `value` FROM $db_tabelle_var WHERE `name` = ?", ['wkName']);

$wkName = ($wkName === null) ? 'Keinen Wettkampfname angegeben. Setzen unter: /intern/wk-leitung/einstellungen' : $wkName;

$normalFontSize = 11;
$marginSide = 10;
$marginTop = 10;
$minMarginBottomTable = 20;
$format = 'A4';
$orientation = 'L';

$abt = intval($_POST['abteilungId'] ?? 1);

$now = trim($_POST['date'] ?? date('Y-m-d H:i:s'));

$geraete = db_select($mysqli, $db_tabelle_disziplinen, "*", '', [], "start_index ASC");

$IndexedGeraete = array_column($geraete, 'name', 'id');

$notenBezeichnungen = db_select($mysqli, $db_tabelle_wertungstypen, "`name`, `id`, `nullstellen`, `anzahl_laeufe_json`", '', [], "");

$IndexedNotenBezeichnungen = array_column($notenBezeichnungen, 'name', 'id');

$IndexedNotenNullstellen = array_column($notenBezeichnungen, 'nullstellen', 'id');

$IndexedNotenJsonGeraete = array_column($notenBezeichnungen, 'anzahl_laeufe_json', 'id');

$programme = db_select($mysqli, $db_tabelle_kategorien, "`programm`, `id`", '', [], "");

$indexedProgramme = array_column($programme, 'id', 'programm');

// Prepare SQL statement
$stmt = $mysqli->prepare("
    SELECT 
        t.id AS person_id, 
        t.name, 
        t.vorname,
        t.programm, 
        t.verein,
        ab.id AS abteilung_id,
        tab.geraet_id AS start_geraet_id,
        tab.turnerin_index
    FROM $db_tabelle_teilnehmende_gruppen tab 
    INNER JOIN $db_tabelle_teilnehmende t ON tab.turnerin_id = t.id
    INNER JOIN $db_tabelle_gruppen ab ON ab.id = tab.abteilung_id
    WHERE ab.id = ?
    ORDER BY t.id ASC
");

$stmt->bind_param('i', $abt);
$stmt->execute();

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

$indexedPersonen = array_column($personen, null, 'person_id');

// Close statement
$stmt->close();

// 1. Get the IDs from the first query results
$personenIds = array_column($personen, 'person_id');

$current_wk_id = (int) db_get_variable($mysqli, $db_tabelle_var, ['current_wk_id']) ?: 0;

if (!empty($personenIds)) {
    $placeholders = implode(',', array_fill(0, count($personenIds), '?'));

    $sqlNotenChanges = "SELECT * FROM $db_tabelle_wertungen_log WHERE person_id IN ($placeholders) AND `wk_id` = ?";
    $stmtNotenChanges = $mysqli->prepare($sqlNotenChanges);

    $paramsArray = array_merge($personenIds, [$current_wk_id]);

    $types = str_repeat('i', count($personenIds)) . 's';

    $stmtNotenChanges->bind_param($types, ...$paramsArray);

    $stmtNotenChanges->execute();
    $notenChangesResult = $stmtNotenChanges->get_result();
    $notenChangesEntries = $notenChangesResult->fetch_all(MYSQLI_ASSOC);
    
    $stmtNotenChanges->close();
} else {
    $notenChangesEntries = [];
}

$kampfrichterIds = array_column($notenChangesEntries, 'edited_by');

if (!empty($kampfrichterIds)) {
    $placeholders = implode(',', array_fill(0, count($kampfrichterIds), '?'));

    $sqlKampfrichter = "SELECT `id` AS `id_kampfrichter`, `name_person` AS `name_kampfrichter` FROM $db_tabelle_intern_benutzende WHERE id IN ($placeholders)";
    $stmtKampfrichter = $mysqli->prepare($sqlKampfrichter);

    $types = str_repeat('i', count($kampfrichterIds));

    $stmtKampfrichter->bind_param($types, ...$kampfrichterIds);

    $stmtKampfrichter->execute();
    $kampfrichterResult = $stmtKampfrichter->get_result();
    $kampfrichter = $kampfrichterResult->fetch_all(MYSQLI_ASSOC);

	$indexedKampfrichter = array_column($kampfrichter, 'name_kampfrichter', 'id_kampfrichter');
    
    $stmtKampfrichter->close();
} else {
    $indexedKampfrichter = [];
}

$entriesArray = [];



foreach ($notenChangesEntries as $snce) {

    $programmId = $indexedProgramme[$indexedPersonen[$snce['person_id']]['programm']] ?? 0;

    $runs = json_decode($IndexedNotenJsonGeraete[$snce['note_bezeichnung_id']], true) ?? [];

    $countRuns = (int) $runs[$snce['geraet_id']][$programmId] ?? (int) $runs['default'] ?? 1;

    $notenTextRaw = $IndexedNotenBezeichnungen[$snce['note_bezeichnung_id']] ?? 'Unbekannter Notenname';

    $notenText = ($countRuns > 1) ? $notenTextRaw . ' (R' . ($snce['run_number'] ?? 1 ). ')' : $notenTextRaw;

    $nullstellen = (int) $IndexedNotenNullstellen[$snce['note_bezeichnung_id']] ?? 2;
    $value = ($snce['old_value'] !== null) ? number_format((float) $snce['old_value'], $nullstellen) . ' ' . json_decode('"\u2192"') . ' ' . number_format((float) $snce['new_value'], $nullstellen) : number_format((float) $snce['new_value'], $nullstellen);

	$entriesArray[$snce['geraet_id']][$indexedPersonen[$snce['person_id']]['start_geraet_id']][] = [
		'name' => ($indexedPersonen[$snce['person_id']]['name'] ?? 'Unbekannter Nachname') . ', ' . ($indexedPersonen[$snce['person_id']]['vorname'] ?? 'Unbekannter Vorname'),
		'programm' => $indexedPersonen[$snce['person_id']]['programm'] ?? 'Unbekanntes Programm',
        'verein' => $indexedPersonen[$snce['person_id']]['verein'] ?? 'Unbekannter Verein',
		'note' => $notenText,
		'value' => $value,
		'kampfrichter' => $indexedKampfrichter[$snce['edited_by']] ?? 'Unbekannter Kampfrichter',
        'timestamp' => new DateTime($snce['timestamp'])->format('d.m.Y H:i:s') ?? '---'
	];
}

// Load TCPDF
require $baseDir . '/../composer/vendor/autoload.php';
/*
// Optional: load custom font
$fontfile = $baseDir . '/wp-content/uploads/fonts/Inter-Regular.ttf'; // adjust path
if (file_exists($fontfile)) {
    $fontname = TCPDF_FONTS::addTTFfont($fontfile, 'TrueTypeUnicode', '', 32);
}
*/
class ProtokollPDF extends TCPDF
{
	public $current_year;
	public $subAbt;
	public $abt;
	public $columns;
	public $discipline;
    public $wkName;
    public $marginSide;
    public $marginTop;
    public $pdfHeight;
    public $pdfWidth;
    public $headerType;
    public $now;
	// Page header

	public $headerBottomY = 0;


	public function Header()
	{
        $this->SetFillColor(255, 255, 255);

        $this->Rect(0, 0, $this->pdfWidth, $this->pdfHeight, 'F');

        $arrayTitles = [];
		$image_file = $_SERVER['DOCUMENT_ROOT'] . '/intern/img/logo-normal.png';
		$this->SetY($this->marginTop);
        $this->SetX(($this->marginSide ?? 10));
		$this->SetFont('freesans', '', 20);

        if ($this->headerType === 'bigHeader') {

            $this->Cell(0, 0, 'Protokoll ' . $this->wkName . ' ' . $this->current_year, 0, 1, 'L', 0, '', 0, false, 'T', 'M');
            $preimageX = $this->GetX();
            $preimageY = $this->GetY();
            $this->Image($image_file, $this->pdfWidth - 10 - $this->marginSide, $this->marginTop, '', 10, 'png', '', 'T');

            $this->SetY($preimageY + 5); 
            $this->SetX($this->marginSide ?? 10); // Force back to left margin
            $this->SetFont('freesans', '', 11);
            $this->Cell(0, 6, 'Gereat: ' . $this->discipline, 0, 1, 'L');
            $this->Cell(0, 6, 'Abteilung: ' . $this->abt, 0, 1, 'L');
            $this->Cell(0, 6, 'Gruppe: ' . $this->subAbt, 0, 1, 'L');

            $this->Ln(5);

        } else {

            $this->Cell(10, 0, 'Protokoll ' . $this->wkName . ' ' . $this->current_year, 0, 1, 'L', 0, '', 0, false, 'T', 'M');
            $this->SetFont('freesans', '', 11);
            $info = "Gerät: {$this->discipline}  |  Abt: {$this->abt}  |  Gruppe: {$this->subAbt}";
            $this->Cell(10, 6, $info, 0, 1, 'L'); // Align all info to the right while title is on the left

            $this->Image($image_file, $this->pdfWidth - 10 - $this->marginSide, $this->marginTop, '', 10, 'png', '', 'T');

            $this->Ln(18);
        }

		$columns = $this->columns;
		$startY = $this->GetY();
		$this->SetFont('', 'B');

        $this->SetX($this->marginSide ?? 10);

		foreach ($columns as $col) {

            $title = $col['header'];

			if (($col['rotate'] ?? false)) {
				$x = $this->GetX();
				$y = $this->GetY() + 7;

				$this->StartTransform();
				$this->Rotate(45, $x, $y);

				$lineY = $startY + 7;
				if (($col['id'] ?? '') === 'gesamt') {
					$this->SetLineWidth(0.6);
				} else {
					$this->SetLineWidth(0.2);
				}
				
				$this->Line($x, $lineY, $x + ($col['width_header'] ?? 0), $lineY);
				$this->SetLineWidth(0.2);

				$this->Cell($col['width_header'] ?? 0, 7, $title ?? '', 0, 0, 'C');
				$this->StopTransform();
				$this->SetX($x + ($col['max_width'] ?? 0));
			} else {
				$this->Cell($col['max_width'] ?? 0, 7, $title ?? '', 0, 0, $col['align'] ?? 'L');
			}
		}

		$this->Ln();
		$this->headerBottomY = $this->GetY();
	}


	// Page footer
	public function Footer()
	{
		$this->SetLineWidth(0.6);
		$this->Line($this->marginSide ?? 10, $this->headerBottomY, $this->pdfWidth - ($this->marginSide ?? 10), $this->headerBottomY);

		$this->SetLineWidth(0.2);

		$this->SetY(0);
		$this->SetX(0);

		$this->SetFillColor(255, 255, 255); // white

		$this->Cell(($this->marginSide ?? 10), $this->pdfHeight, '', 0, 0, 'L', true);

		$this->SetY(0);
		$this->SetX($this->pdfWidth - ($this->marginSide ?? 10));

		$this->Cell(($this->marginSide ?? 10), $this->pdfHeight, '', 0, 0, 'L', true);

        $this->SetY(-15);
        $this->SetFont('freesans', 'I', 8);

        // 1. Page Number - Centered
        $this->Cell(0, 10, 'Seite ' . $this->getAliasNumPage() . ' von ' . $this->getAliasNbPages(), 0, false, 'C');

        // 2. Timestamp - Force to Left
        $this->SetX($this->getMargins()['left']); // Reset to left margin
        $this->Cell(0, 10, 'Zeitstempel: ' . $this->now, 0, false, 'L');

        // 3. Host - Force to Right (Cell with width 0 and align 'R' handles this)
        $this->SetX($this->getMargins()['left']); // Reset again so 'R' alignment works from the start
        $this->Cell(0, 10, $_SERVER['HTTP_HOST'], 0, 0, 'R', false, 'https://'.$_SERVER['HTTP_HOST']);
	}
}

$pdf = new ProtokollPDF($orientation, 'mm', $format, true, 'UTF-8', false);

$pdfHeight = $pdf->getPageHeight();
$pdfWidth = $pdf->getPageWidth();

$pdf->current_year = $current_year;
$pdf->wkName = $wkName;
$pdf->abt = $abt;
$pdf->marginSide = $marginSide;
$pdf->marginTop = $marginTop;
$pdf->pdfHeight = $pdfHeight;
$pdf->pdfWidth = $pdfWidth;
$pdf->now = $now;

$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor($wkName);
$pdf->SetTitle($wkName . "_Protokoll_" . $abt . "_" . $current_year . ".pdf");

$pdf->SetAutoPageBreak(FALSE);


$pdf->SetFont('freesans', '', 11);

// Define columns dynamically
$columns = [
    ['id' => 'name', 'header' => 'Name Person', 'align' => 'L', 'flex' => true, 'type' => 'field', 'field' => 'name'],
	['id' => 'programm', 'header' => 'Programm', 'align' => 'L', 'flex' => true, 'type' => 'field', 'field' => 'programm'],
	['id' => 'verein', 'header' => 'Verein', 'align' => 'L', 'flex' => true, 'type' => 'field', 'field' => 'verein'],
	['id' => 'note', 'header' => 'Note', 'align' => 'C', 'flex' => false, 'type' => 'field', 'field' => 'note'],
	['id' => 'value', 'header' => 'Wert', 'align' => 'C', 'flex' => false, 'type' => 'field', 'field' => 'value'],
	['id' => 'kr', 'header' => 'Kampfrichter/in', 'align' => 'C', 'flex' => true, 'type' => 'field', 'field' => 'kampfrichter'],
    ['id' => 'timestamp', 'header' => 'Zeitstempel', 'align' => 'C', 'flex' => false, 'type' => 'field', 'field' => 'timestamp'],
];


$padding = 4;

unset($col);

// 1. Calculate initial max widths based on headers
foreach ($columns as &$col) {
    $col['width_header'] = $pdf->GetStringWidth($col['header']) + ($padding * 2);
    if ($col['type'] !== 'note') {
        $col['max_width'] = $col['width_header'];
    } else {
        $col['max_width'] = 0;
    }
}

foreach ($entriesArray as $geratId => $singleGeraet) {

    $pdf->discipline = $IndexedGeraete[$geratId] ?? 'Unbekanntes Gerät';

    foreach ($singleGeraet as $geratIdStart => $singleStartGeraet) {

        $pdf->subAbt = $geratIdStart;

        $tcolumns = $columns;

        foreach ($singleStartGeraet as $se) {
            foreach ($tcolumns as &$col) {
                $text = '';
                if (isset($se[$col['field']])) {
                    $text = $se[$col['field']];
                }
                $width = $pdf->GetStringWidth($text) + ($padding * 2);
                if ($width > $col['max_width']) {
                    $col['max_width'] = $width;
                }
            }
            unset($col);
        }

        // 4. Distribute Flexible Widths
        $tablew = $pdfWidth - (2 * $marginSide); // total table width (A4 landscape in mm minus margins)
        $fixedWidth = 0;
        $flexCols = [];

        foreach ($tcolumns as $col) {
            if ($col['flex'] ?? false) {
                $flexCols[] = $col['id'];
                $fixedWidth += $col['max_width'];
            } else {
                $fixedWidth += $col['max_width'];
            }
        }

        $effTableWidth = $tablew - $fixedWidth;

        if (!empty($flexCols) && $effTableWidth > 0) {
            $flexTotalInitial = 0;
            foreach ($tcolumns as $col) {
                if ($col['flex'] ?? false) $flexTotalInitial += $col['max_width'];
            }

            foreach ($tcolumns as &$col) {
                if ($col['flex'] ?? false) {
                    $col['max_width'] += ($col['max_width'] / $flexTotalInitial) * $effTableWidth;
                }
            }
            unset($col);
        }

        $pdf->columns = $tcolumns;

        $pdf->headerType = 'bigHeader';
        $pdf->AddPage();
        $pdf->headerType = '';

        // After AddPage(), the header has been drawn
        $margin_top = $pdf->headerBottomY;

        // Now adjust your margins if needed
        $pdf->SetMargins($marginSide, $margin_top, $marginSide); // +5 mm padding below header
        $pdf->SetY($margin_top); // Move cursor below header manually

        $pdf->SetFont('', '');
        $rIndex = 0;

        foreach ($singleStartGeraet as $r) {

            $pdf->SetTextColor(0, 0, 0);

            if ($rIndex % 2 == 0) {
                $pdf->SetFillColor(255, 255, 255);
            } else {
                $pdf->SetFillColor(240, 240, 240);
            }

            $rowHeight = 10;

            foreach ($tcolumns as $col) {

                if ($pdf->getY() + $rowHeight > $pdfHeight - $minMarginBottomTable) {
                    $pdf->addPage();
                    $margin_top = $pdf->headerBottomY;
                    $pdf->setY($margin_top);
                }

                $customFontSize = (isset($col['font_size']) && $col['font_size'] != 0);

                if ($customFontSize) {
                    $pdf->SetFont('', '', $col['font_size']);
                }

                $startX = $pdf->GetX();
                $startY = $pdf->GetY();

                $text = strip_tags($r[$col['field']]);

                if ($col['type'] === 'field') {
                    $pdf->MultiCell($col['max_width'], $rowHeight, $text, 'B', $col['align'], true, 0, $startX, $startY, true, 0, false, true, $rowHeight, 'M');
                }

                if ($customFontSize) {
                    $pdf->SetFont('', '', $normalFontSize);
                }
            }

            $pdf->SetY($startY + $rowHeight); // Move Y manually instead of Ln() to account for rowHeight
            $rIndex++;
        }
        $textanzEintaege = (count($singleStartGeraet) > 1) ? 'Einträge': 'Eintrag';

        $pdf->SetFont('', '', 7);

        $pdf->Cell(20, 6, count($singleStartGeraet).' '.$textanzEintaege, 0, 0, 'L');

        $pdf->SetFont('', '', $normalFontSize);
    }
}

$pdf->Output($wkName . "_Protokoll_" . $abt . "_" . $current_year . ".pdf", 'I');
exit;