<?php

declare(strict_types=1);

require __DIR__ . '/dev-db.php';

$email = getenv('DEV_AUTH_EMAIL');
if ($email === false || trim($email) === '') {
    fwrite(STDERR, "Missing environment variable: DEV_AUTH_EMAIL\n");
    exit(1);
}

$pdo = dev_pdo();
dev_apply_schema($pdo);

$email = strtolower(trim((string)$email));
$name = trim((string)(getenv('DEV_AUTH_NAME') ?: 'Test Admin'));

$stmt = $pdo->prepare(
    'INSERT INTO kl_Mitarbeiter (Name, Email, aktiv, admin)
     VALUES (?, ?, 1, 1)
     ON DUPLICATE KEY UPDATE Name = VALUES(Name), aktiv = 1, admin = 1'
);
$stmt->execute([$name, $email]);

$memberId = (int)$pdo->query('SELECT MitarbeiterID FROM kl_Mitarbeiter WHERE Email = ' . $pdo->quote($email))->fetchColumn();

$paymentCount = (int)$pdo->query('SELECT COUNT(*) FROM kl_Einzahlungen WHERE MitarbeiterID = ' . $memberId)->fetchColumn();
if ($paymentCount === 0) {
    $stmt = $pdo->prepare('INSERT INTO kl_Einzahlungen (MitarbeiterID, Betrag, Datum) VALUES (?, ?, NOW())');
    $stmt->execute([$memberId, 10.00]);
}

$consumptionCount = (int)$pdo->query('SELECT COUNT(*) FROM kl_Kaffeeverbrauch WHERE MitarbeiterID = ' . $memberId)->fetchColumn();
if ($consumptionCount === 0) {
    $stmt = $pdo->prepare(
        'INSERT INTO kl_Kaffeeverbrauch (MitarbeiterID, AnzahlStriche, Kosten, KostenproStrich, Datum, Eintragsart)
         VALUES (?, ?, ?, ?, NOW(), ?)'
    );
    $stmt->execute([$memberId, 3, 0.60, 0.20, 2]);
}

$noticeCount = (int)$pdo->query('SELECT COUNT(*) FROM kl_hinweise')->fetchColumn();
if ($noticeCount === 0) {
    $stmt = $pdo->prepare('INSERT INTO kl_hinweise (nachricht, gueltig_bis) VALUES (?, DATE_ADD(NOW(), INTERVAL 30 DAY))');
    $stmt->execute(['Dev-Hinweis: MySQL-Testumgebung aktiv.']);
}

echo "MySQL dev schema is ready for {$email}.\n";
