<?php

declare(strict_types=1);

require __DIR__ . '/dev-db.php';
require __DIR__ . '/golden-master-data.php';

$pdo = dev_pdo();
$expected = gm_expected_summaries();
$members = gm_members();
$emails = array_keys($expected);
$failures = [];
$passes = 0;

function gm_assert_equal(string $label, mixed $expected, mixed $actual, array &$failures, int &$passes): void
{
    if ($expected === $actual) {
        $passes++;
        echo "PASS {$label}\n";
        return;
    }

    $failures[] = "{$label}: expected " . var_export($expected, true) . ', got ' . var_export($actual, true);
    echo "FAIL {$label}\n";
}

function gm_fetch_member_summaries(PDO $pdo, array $emails): array
{
    $placeholders = implode(',', array_fill(0, count($emails), '?'));
    $year = gm_current_year();
    $sql = "
        SELECT
            m.Email AS email,
            COALESCE(p.total_payments, 0) AS total_payments,
            COALESCE(c.total_costs, 0) AS total_costs,
            COALESCE(c.total_marks, 0) AS total_marks,
            COALESCE(p.total_payments, 0) - COALESCE(c.total_costs, 0) AS balance,
            COALESCE(yp.year_payments, 0) AS year_payments,
            COALESCE(yc.year_costs, 0) AS year_costs,
            COALESCE(yc.year_marks, 0) AS year_marks
        FROM kl_Mitarbeiter m
        LEFT JOIN (
            SELECT MitarbeiterID, SUM(Betrag) AS total_payments
            FROM kl_Einzahlungen
            GROUP BY MitarbeiterID
        ) p ON p.MitarbeiterID = m.MitarbeiterID
        LEFT JOIN (
            SELECT MitarbeiterID, SUM(Kosten) AS total_costs, SUM(AnzahlStriche) AS total_marks
            FROM kl_Kaffeeverbrauch
            GROUP BY MitarbeiterID
        ) c ON c.MitarbeiterID = m.MitarbeiterID
        LEFT JOIN (
            SELECT MitarbeiterID, SUM(Betrag) AS year_payments
            FROM kl_Einzahlungen
            WHERE YEAR(Datum) = ?
            GROUP BY MitarbeiterID
        ) yp ON yp.MitarbeiterID = m.MitarbeiterID
        LEFT JOIN (
            SELECT MitarbeiterID, SUM(Kosten) AS year_costs, SUM(AnzahlStriche) AS year_marks
            FROM kl_Kaffeeverbrauch
            WHERE YEAR(Datum) = ?
            GROUP BY MitarbeiterID
        ) yc ON yc.MitarbeiterID = m.MitarbeiterID
        WHERE m.Email IN ({$placeholders})
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute(array_merge([$year, $year], $emails));

    $actual = [];
    while ($row = $stmt->fetch()) {
        $actual[$row['email']] = [
            'total_payments' => gm_decimal_to_cents($row['total_payments']),
            'total_costs' => gm_decimal_to_cents($row['total_costs']),
            'total_marks' => (int)$row['total_marks'],
            'balance' => gm_decimal_to_cents($row['balance']),
            'year_payments' => gm_decimal_to_cents($row['year_payments']),
            'year_costs' => gm_decimal_to_cents($row['year_costs']),
            'year_marks' => (int)$row['year_marks'],
        ];
    }

    return $actual;
}

function gm_fetch_sheet_emails(PDO $pdo, array $emails, string $mode): array
{
    $placeholders = implode(',', array_fill(0, count($emails), '?'));
    $stmt = $pdo->prepare(
        "SELECT MAX(DATE(v.Datum))
         FROM kl_Kaffeeverbrauch v
         JOIN kl_Mitarbeiter m ON m.MitarbeiterID = v.MitarbeiterID
         WHERE m.Email IN ({$placeholders})
           AND DATE(v.Datum) < CURDATE()"
    );
    $stmt->execute($emails);
    $referenceDate = $stmt->fetchColumn() ?: date('Y-m-d');

    $operator = $mode === 'front' ? '>=' : '<';
    $sql = "
        SELECT m.Email AS email
        FROM kl_Mitarbeiter m
        LEFT JOIN kl_Kaffeeverbrauch v
          ON m.MitarbeiterID = v.MitarbeiterID
         AND v.Datum >= DATE_ADD(?, INTERVAL -100 DAY)
        WHERE m.aktiv = 1
          AND m.Email IN ({$placeholders})
        GROUP BY m.MitarbeiterID, m.Email
        HAVING COALESCE(SUM(v.AnzahlStriche), 0) {$operator} 10
        ORDER BY m.Email
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array_merge([$referenceDate], $emails));

    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

$actualSummaries = gm_fetch_member_summaries($pdo, $emails);
gm_assert_equal('member summary count', count($expected), count($actualSummaries), $failures, $passes);

foreach ($expected as $email => $summary) {
    gm_assert_equal("summary exists {$email}", true, isset($actualSummaries[$email]), $failures, $passes);
    if (!isset($actualSummaries[$email])) {
        continue;
    }

    foreach ($summary as $key => $expectedValue) {
        gm_assert_equal("{$email} {$key}", $expectedValue, $actualSummaries[$email][$key], $failures, $passes);
    }
}

$stmt = $pdo->prepare('SELECT Email, aktiv, admin, paypalname FROM kl_Mitarbeiter WHERE Email IN (' . implode(',', array_fill(0, count($emails), '?')) . ')');
$stmt->execute($emails);
$memberRows = [];
while ($row = $stmt->fetch()) {
    $memberRows[$row['Email']] = $row;
}
foreach ($members as $member) {
    $row = $memberRows[$member['email']] ?? null;
    gm_assert_equal("member flags exist {$member['email']}", true, $row !== null, $failures, $passes);
    if ($row === null) {
        continue;
    }
    gm_assert_equal("{$member['email']} active", $member['active'], (int)$row['aktiv'], $failures, $passes);
    gm_assert_equal("{$member['email']} admin", $member['admin'], (int)$row['admin'], $failures, $passes);
    gm_assert_equal("{$member['email']} paypalname", $member['paypalname'], $row['paypalname'], $failures, $passes);
}

$front = gm_fetch_sheet_emails($pdo, $emails, 'front');
$back = gm_fetch_sheet_emails($pdo, $emails, 'back');
gm_assert_equal('front sheet emails', gm_expected_front_sheet_emails(), $front, $failures, $passes);
gm_assert_equal('back sheet emails', gm_expected_back_sheet_emails(), $back, $failures, $passes);

$stmt = $pdo->prepare('SELECT MitarbeiterID FROM kl_Mitarbeiter WHERE Name = ? OR paypalname = ?');
$stmt->execute(['GM PayPal Alias', 'GM PayPal Alias']);
$paypalId = $stmt->fetchColumn();
gm_assert_equal('csv paypalname lookup finds participant', true, $paypalId !== false, $failures, $passes);

$stmt = $pdo->prepare(
    'SELECT COUNT(*)
     FROM kl_Einzahlungen
     WHERE MitarbeiterID = ?
       AND Betrag = ?
       AND DATE(Datum) = DATE(?)'
);
$stmt->execute([$paypalId ?: 0, gm_cents_to_decimal(750), gm_dates()['recent']]);
gm_assert_equal('csv duplicate basis exists', 1, (int)$stmt->fetchColumn(), $failures, $passes);

$stmt = $pdo->prepare('SELECT COUNT(*) FROM kl_Mitarbeiter WHERE Name = ? OR paypalname = ?');
$stmt->execute(['GM Unbekannt', 'GM Unbekannt']);
gm_assert_equal('csv unknown lookup misses participant', 0, (int)$stmt->fetchColumn(), $failures, $passes);

$activeNoticeCount = (int)$pdo
    ->query("SELECT COUNT(*) FROM kl_hinweise WHERE nachricht LIKE '[GM]%' AND gueltig_bis >= NOW()")
    ->fetchColumn();
$expiredNoticeCount = (int)$pdo
    ->query("SELECT COUNT(*) FROM kl_hinweise WHERE nachricht LIKE '[GM]%' AND gueltig_bis < NOW()")
    ->fetchColumn();
gm_assert_equal('active GM notice count', 1, $activeNoticeCount, $failures, $passes);
gm_assert_equal('expired GM notice count', 1, $expiredNoticeCount, $failures, $passes);

if ($failures !== []) {
    echo "\nGolden master check failed with " . count($failures) . " failure(s):\n";
    foreach ($failures as $failure) {
        echo "- {$failure}\n";
    }
    exit(1);
}

echo "\nGolden master check passed with {$passes} assertions.\n";

