<?php
// views/kassenwart.php - Treasury and booking management
require_once __DIR__ . '/../auth.php';
require_login();
if (!can_manage_finance()) {
    header("Location: index.php?view=dashboard&error=access_denied");
    exit;
}

// 1. Handle DATEV CSV Export
if (isset($_GET['export']) && $_GET['export'] === 'datev') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=datev_export_' . date('Y-m-d') . '.csv');
    
    // Open stdout for writing
    $output = fopen('php://output', 'w');
    // Add UTF-8 BOM
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // DATEV standard booking headers
    fputcsv($output, [
        'Umsatz (Betrag)', 
        'Soll/Haben-Kennzeichen', 
        'Währung', 
        'Datum', 
        'Konto', 
        'Gegenkonto', 
        'Buchungstext', 
        'Belegfeld 1', 
        'Belegfeld 2'
    ], ';');
    
    $stmt = $pdo->query("SELECT * FROM transactions ORDER BY booking_date ASC");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $amount = number_format($row['amount'], 2, ',', '');
        $sh = $row['type'] === 'income' ? 'S' : 'H';
        
        // Map account: Income usually goes to a revenues account (e.g., 8400 SKR03), Expenses to expense account (e.g., 4900 SKR03)
        // Default cash account in Germany: 1000 (Kasse SKR03)
        $account = $row['type'] === 'income' ? ($row['contra_account'] ?: '8400') : '1000';
        $contra = $row['type'] === 'income' ? '1000' : ($row['contra_account'] ?: '4900');
        
        fputcsv($output, [
            $amount,
            $sh,
            'EUR',
            date('dmy', strtotime($row['booking_date'])),
            $account,
            $contra,
            $row['description'],
            'RE-' . $row['id'],
            $row['category']
        ], ';');
    }
    fclose($output);
    exit;
}

// 2. Handle Elster XML Export
if (isset($_GET['export']) && $_GET['export'] === 'elster') {
    header('Content-Type: application/xml; charset=utf-8');
    header('Content-Disposition: attachment; filename=elster_euer_' . date('Y-m-d') . '.xml');
    
    // Fetch aggregated categories
    $stmt = $pdo->prepare("SELECT type, category, SUM(amount) as total FROM transactions GROUP BY type, category");
    $stmt->execute();
    $aggs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $income_total = 0;
    $expense_total = 0;
    
    $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><ElsterAnmeldung xmlns="http://www.elster.de/euer/v1"/>');
    $euer = $xml->addChild('EinnahmenUeberschussRechnung');
    $euer->addChild('Jahr', date('Y'));
    $euer->addChild('Software', 'Team Mania Pro');
    
    $inc_node = $euer->addChild('Betriebseinnahmen');
    $exp_node = $euer->addChild('Betriebsausgaben');
    
    foreach ($aggs as $a) {
        $clean_cat = preg_replace('/[^a-zA-Z0-9]/', '', $a['category']);
        if ($a['type'] === 'income') {
            $inc_node->addChild($clean_cat, number_format($a['total'], 2, '.', ''));
            $income_total += $a['total'];
        } else {
            $exp_node->addChild($clean_cat, number_format($a['total'], 2, '.', ''));
            $expense_total += $a['total'];
        }
    }
    
    $euer->addChild('Gesamteinnahmen', number_format($income_total, 2, '.', ''));
    $euer->addChild('Gesamtausgaben', number_format($expense_total, 2, '.', ''));
    $euer->addChild('GewinnVerlust', number_format($income_total - $expense_total, 2, '.', ''));
    
    echo $xml->asXML();
    exit;
}

// 3. Handle Transaction Entry
$errors = [];
$success_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_transaction') {
    $type = $_POST['type'] ?? 'income';
    $amount = floatval(str_replace(',', '.', $_POST['amount'] ?? '0'));
    $booking_date = $_POST['booking_date'] ?? date('Y-m-d');
    $description = trim($_POST['description'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $contra_account = trim($_POST['contra_account'] ?? '');
    
    if ($amount <= 0 || empty($description) || empty($category)) {
        $errors[] = "Bitte Betrag, Beschreibung und Kategorie korrekt ausfüllen.";
    }
    
    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("INSERT INTO transactions (type, amount, booking_date, description, category, contra_account) VALUES (:type, :amount, :booking_date, :description, :category, :contra)");
            $stmt->execute([
                ':type' => $type,
                ':amount' => $amount,
                ':booking_date' => $booking_date,
                ':description' => $description,
                ':category' => $category,
                ':contra' => $contra_account
            ]);
            $success_msg = "Transaktion erfolgreich gebucht!";
        } catch (PDOException $e) {
            $errors[] = "Buchungsfehler: " . $e->getMessage();
        }
    }
}

// 4. Fetch Financial Stats
$stats = $pdo->query("SELECT 
    SUM(CASE WHEN type = 'income' THEN amount ELSE 0 END) as total_income,
    SUM(CASE WHEN type = 'expense' THEN amount ELSE 0 END) as total_expense
    FROM transactions")->fetch(PDO::FETCH_ASSOC);

$total_income = floatval($stats['total_income'] ?? 0);
$total_expense = floatval($stats['total_expense'] ?? 0);
$balance = $total_income - $total_expense;

// Get transactions for list
$transactions_stmt = $pdo->query("SELECT * FROM transactions ORDER BY booking_date DESC, id DESC LIMIT 50");
$transactions = $transactions_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 10px;">
    <div>
        <h1 style="font-size: 28px; font-weight: 800; color: var(--secondary);">Finanzen & Kassenbuch</h1>
        <p style="color: var(--text-muted); font-size: 14px;">Erfassung, Auswertung und DATEV/Elster-Export für den Kassenwart</p>
    </div>
    
    <div style="display: flex; gap: 10px;">
        <a href="index.php?view=kassenwart&export=datev" class="btn btn-secondary btn-sm">DATEV-Export (.CSV)</a>
        <a href="index.php?view=kassenwart&export=elster" class="btn btn-secondary btn-sm">Elster EÜR (.XML)</a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul>
            <?php foreach ($errors as $err): ?>
                <li><?= htmlspecialchars($err) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (!empty($success_msg)): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success_msg) ?></div>
<?php endif; ?>

<!-- Financial Aggregation Boxes -->
<div class="grid" style="grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));">
    <div class="card" style="border-left: 4px solid var(--success);">
        <span style="font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Gesamteinnahmen</span>
        <h2 style="font-size: 26px; font-weight: 800; color: #065f46; margin-top: 5px;"><?= number_format($total_income, 2, ',', '.') ?> €</h2>
    </div>
    <div class="card" style="border-left: 4px solid var(--danger);">
        <span style="font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Gesamtausgaben</span>
        <h2 style="font-size: 26px; font-weight: 800; color: #991b1b; margin-top: 5px;"><?= number_format($total_expense, 2, ',', '.') ?> €</h2>
    </div>
    <div class="card" style="border-left: 4px solid <?= $balance >= 0 ? 'var(--primary)' : 'var(--danger)' ?>;">
        <span style="font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Kassensaldo</span>
        <h2 style="font-size: 26px; font-weight: 800; color: <?= $balance >= 0 ? '#047857' : '#b91c1c' ?>; margin-top: 5px;"><?= number_format($balance, 2, ',', '.') ?> €</h2>
    </div>
</div>

<div class="grid" style="grid-template-columns: 2fr 1fr; gap: 24px; margin-top: 24px;">
    <!-- Booking Form & Ledger -->
    <div class="card">
        <h3 class="card-title">📖 Letzte Buchungen (max. 50)</h3>
        
        <div class="table-responsive" style="margin-top: 15px;">
            <table>
                <thead>
                    <tr>
                        <th>Datum</th>
                        <th>Kategorie</th>
                        <th>Beschreibung</th>
                        <th>DATEV-Konto</th>
                        <th style="text-align: right;">Betrag</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($transactions)): ?>
                        <?php foreach ($transactions as $t): ?>
                            <tr>
                                <td><?= date('d.m.Y', strtotime($t['booking_date'])) ?></td>
                                <td><span style="padding: 4px 8px; font-size: 11px; font-weight: 600; background: #e2e8f0; border-radius: 4px;"><?= htmlspecialchars($t['category']) ?></span></td>
                                <td><?= htmlspecialchars($t['description']) ?></td>
                                <td style="font-family: monospace; font-size: 13px;">
                                    <?= $t['type'] === 'income' ? ($t['contra_account'] ?: '8400') : '1000' ?> &rarr; 
                                    <?= $t['type'] === 'income' ? '1000' : ($t['contra_account'] ?: '4900') ?>
                                </td>
                                <td style="text-align: right; font-weight: 600; color: <?= $t['type'] === 'income' ? 'var(--success)' : 'var(--danger)' ?>;">
                                    <?= $t['type'] === 'income' ? '+' : '-' ?><?= number_format($t['amount'], 2, ',', '.') ?> €
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" style="text-align: center; color: var(--text-muted); padding: 30px;">Keine Buchungen erfasst.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Quick Booking Creator -->
    <div>
        <div class="card" style="margin-bottom: 24px;">
            <h3 class="card-title">✍️ Neue Buchung erfassen</h3>
            <form method="POST" action="" style="margin-top: 15px;">
                <input type="hidden" name="action" value="add_transaction">
                
                <div class="form-group">
                    <label for="type">Buchungsart</label>
                    <select id="type" name="type">
                        <option value="income">Einnahme (+)</option>
                        <option value="expense">Ausgabe (-)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="amount">Betrag (€)</label>
                    <input type="text" id="amount" name="amount" placeholder="0,00" required>
                </div>

                <div class="form-group">
                    <label for="booking_date">Buchungsdatum</label>
                    <input type="date" id="booking_date" name="booking_date" value="<?= date('Y-m-d') ?>" required>
                </div>

                <div class="form-group">
                    <label for="category">Kategorie / Steuerkonto</label>
                    <select id="category" name="category">
                        <option value="Mitgliedsbeiträge">Mitgliedsbeiträge</option>
                        <option value="Sponsoring">Sponsoring</option>
                        <option value="Materialbeschaffung">Materialbeschaffung</option>
                        <option value="Platzmiete">Platzmiete / Instandhaltung</option>
                        <option value="Kleidung">Kleidung & Merchandising</option>
                        <option value="Sonstiges">Sonstiges</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="contra_account">Gegenkonto (DATEV - Optional)</label>
                    <input type="text" id="contra_account" name="contra_account" placeholder="z. B. 8400 bei Einnahmen, 4900 bei Ausgaben">
                </div>

                <div class="form-group">
                    <label for="description">Verwendungszweck / Belegtext</label>
                    <input type="text" id="description" name="description" placeholder="z. B. Mitgliedsbeitrag Max Mustermann" required>
                </div>

                <button type="submit" class="btn btn-primary" style="width: 100%; margin-top: 10px;">Buchen</button>
            </form>
        </div>

        <!-- Pure CSS visual distribution chart -->
        <div class="card">
            <h3 class="card-title">📊 Budgetverteilung</h3>
            <?php 
            $tot = $total_income + $total_expense;
            $inc_pct = $tot > 0 ? round(($total_income / $tot) * 100) : 50;
            $exp_pct = $tot > 0 ? round(($total_expense / $tot) * 100) : 50;
            ?>
            <div style="margin-top: 15px;">
                <div style="display: flex; justify-content: space-between; font-size: 13px; font-weight: 500; margin-bottom: 5px;">
                    <span>Einnahmen (<?= $inc_pct ?>%)</span>
                    <span>Ausgaben (<?= $exp_pct ?>%)</span>
                </div>
                <div style="display: flex; height: 16px; border-radius: 8px; overflow: hidden; background: #e2e8f0;">
                    <div style="width: <?= $inc_pct ?>%; background: var(--success);"></div>
                    <div style="width: <?= $exp_pct ?>%; background: var(--danger);"></div>
                </div>
                <p style="font-size: 12px; color: var(--text-muted); margin-top: 10px; line-height: 1.4; text-align: center;">Die Auswertung visualisiert das Verhältnis zwischen Einnahmen und Ausgaben des laufenden Geschäftsjahrs.</p>
            </div>
        </div>
    </div>
</div>
