<?php

include "functions.php";
require_once __DIR__ . "/app/ledger.php";

$pdo = app_db_pdo();
$saasUser = saas_current_user($pdo);
$tenantId = 0;
$hasAccess = false;

if ($saasUser !== null && saas_user_has_role(['owner', 'admin', 'treasurer'], $saasUser)) {
	$tenantId = (int)$saasUser['tenant_id'];
	$hasAccess = true;
}

if (!$hasAccess && $saasUser === null && checkKaffeelisteAdmin($conn, $mailadress)) {
	$tenant = ledger_fetch_default_tenant($pdo);
	if ($tenant !== null) {
		$tenantId = (int)$tenant['id'];
		$hasAccess = true;
	}
}

if (!$hasAccess) {
	http_response_code(403);
	exit('Kein Zugriff.');
}

$settings = saas_fetch_tenant_settings($pdo, $tenantId);
$windowDays = $settings['sheet_window_days'] ?? 100;
$markPrice = number_format(($settings['mark_price_cents'] ?? 20) / 100, 2, ',', '.');

$vieltrinker = ledger_fetch_participants_by_window_marks($pdo, $tenantId, $windowDays, true);
$wenigtrinker = ledger_fetch_participants_by_window_marks($pdo, $tenantId, $windowDays, false);

// TCPDF-Bibliothek einbinden
require_once(__DIR__ . '/TCPDF/tcpdf.php');

class MyCustomPDFWithWatermark extends TCPDF {
    public function Header() {
        $bMargin = $this->getBreakMargin();
        $auto_page_break = $this->AutoPageBreak;
        $this->SetAutoPageBreak(false, 0);

        $img_file = __DIR__ . '/watermark.jpg';
        $this->SetAlpha(0.35);
        $this->Image($img_file, 0, 0, 223, 280, '', '', '', false, 300, '', false, false, 0);
        $this->SetAlpha(1);

        $this->SetAutoPageBreak($auto_page_break, $bMargin);
        $this->setPageMark();
    }
}

/**
 * Rendert eine Teilnehmerseite (Vieltrinker/Wenigtrinker) als HTML-Tabelle
 * fuer TCPDF, inklusive Fuellzeilen bis zur Mindesthoehe.
 *
 * @param list<array> $teilnehmer
 */
function export_render_page_html(array $teilnehmer, string $titel, string $hinweisText, string $markPrice, int $minRows, string $rueckseitenHinweis): string
{
    $html = '
    <table border="1" style="white-space:nowrap;">
        <tr style="height: 25px;' . $hinweisText . '" valign="bottom">
            <th style="width:30%;font-size: 13px;" colspan="2"><b>' . $titel . '</b></th>
            <th style="width:70%;" valign="bottom">1 Strich = ' . $markPrice . '€. Bitte bezahlen bei 10 € zahlen. ' . date("d.m.Y H:s") . '</th>
        </tr>
        <tr>
            <td style="width:20%"><b>Name</b></td>
            <td style="width:10%"><b>Guthaben</b></td>
            <td><b>Striche</b></td>
        </tr>';

    $rowCount = 0;
    foreach ($teilnehmer as $person) {
        $rowCount++;
        $name = saas_html($person['display_name']);
        $balanceCents = (int)$person['balance_cents'];
        $balance = number_format($balanceCents / 100, 2, ',', '.');

        $html .= '<tr style="height: 16px;">';
        $html .= "<td>{$name}</td>";
        if ($balanceCents < -1000) {
            $html .= '<td style="background-color: rgb(204, 0, 0); color: rgb(255, 255, 255);">' . $balance . ' €</td>';
        } elseif ($balanceCents > 500) {
            $html .= '<td style="background-color: rgb(0, 102, 0); color: rgb(255, 255, 255);">' . $balance . ' €</td>';
        } else {
            $html .= "<td>{$balance} €</td>";
        }
        $html .= "<td></td>";
        $html .= "</tr>";
    }

    for ($i = $rowCount; $i < $minRows; $i++) {
        $html .= '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
    }
    $html .= '<tr><td>&nbsp;</td><td>&nbsp;</td><td style="background-color: rgb(255, 255, 0);text-align: right;"><b>' . $rueckseitenHinweis . '</b></td></tr>';
    $html .= '</table>';

    return $html;
}

$pdf = new MyCustomPDFWithWatermark(PDF_PAGE_ORIENTATION, 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetHeaderData("", 0, "Kaffeestrichliste", "");
$pdf->SetPrintFooter(false);
$pdf->SetMargins('5', '5', '5');
$pdf->SetAutoPageBreak(true, 5);
$pdf->SetFont('helvetica', '', 9.5);

$pdf->AddPage();
$pdf->writeHTML(
    export_render_page_html($vieltrinker, 'Kaffeeliste - Vieltrinker', 'background-color: rgb(0, 94, 63);color: rgb(255, 255, 255);', $markPrice, 63, 'Rückseite beachten!'),
    true, false, true, false, ''
);

$pdf->AddPage();
$pdf->writeHTML(
    export_render_page_html($wenigtrinker, 'Kaffeeliste - Wenigtrinker', 'background-color: rgb(91, 209, 215);color: rgb(0, 0, 0);', $markPrice, 64, 'Vorderseite beachten!'),
    true, false, true, false, ''
);

$pdf->Output('Kaffeestrichliste.pdf', 'D');
