<?php
require_once 'includes/header.php';

$secili_yil = isset($_GET['yil']) ? (int)$_GET['yil'] : date('Y');
$aylar = ['01'=>'Ocak','02'=>'Şubat','03'=>'Mart','04'=>'Nisan','05'=>'Mayıs','06'=>'Haziran','07'=>'Temmuz','08'=>'Ağustos','09'=>'Eylül','10'=>'Ekim','11'=>'Kasım','12'=>'Aralık'];

$aylik_veriler = [];

try {
    // Hem seyahatlerden aylık toplamları hem de aylik_raporlar'dan ödeme durumlarını çek
    $stmt = $conn->prepare("
        SELECT 
            m.ay,
            COALESCE(SUM(s.ucret), 0) as toplam_masraf,
            MAX(ar.odendi_mi) as odendi_mi,     -- MAX() eklendi
            MAX(ar.odeme_tarihi) as odeme_tarihi -- MAX() eklendi
        FROM (
            SELECT 1 as ay UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL
            SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL
            SELECT 11 UNION ALL SELECT 12
        ) m
        LEFT JOIN seyahatler s ON MONTH(s.tarih) = m.ay AND YEAR(s.tarih) = :yil
        LEFT JOIN aylik_raporlar ar ON ar.yil_ay = CONCAT(:yil, '-', LPAD(m.ay, 2, '0'))
        GROUP BY m.ay
        ORDER BY m.ay ASC
    ");
    $stmt->execute([':yil' => $secili_yil]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($results as $row) {
        $ay_str = str_pad($row['ay'], 2, '0', STR_PAD_LEFT);
        $aylik_veriler[$ay_str] = [
            'toplam_masraf' => $row['toplam_masraf'],
            'odendi_mi' => $row['odendi_mi'] ?? 0,
            'odeme_tarihi' => $row['odeme_tarihi'] ?? null
        ];
    }
} catch (PDOException $e) {
    die("Hata: Aylık veriler çekilemedi. " . $e->getMessage());
}

$toplam_yillik_masraf = array_sum(array_column($aylik_veriler, 'toplam_masraf'));
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h1>Dashboard (<?php echo $secili_yil; ?>)</h1>
</div>

<div class="card mb-4">
    <div class="card-body py-2"><form action="dashboard.php" method="GET" class="row g-3 justify-content-center align-items-end"><div class="col-md-6 col-12"><label for="yil" class="form-label">Yıl</label><select name="yil" id="yil" class="form-select"><?php for ($y = 2026; $y >= 2024; $y--): ?><option value="<?php echo $y; ?>" <?php echo ($y == $secili_yil) ? 'selected' : ''; ?>><?php echo $y; ?></option><?php endfor; ?></select></div><div class="col-md-3 col-12"><button type="submit" class="btn btn-secondary w-100">Göster</button></div></form></div>
</div>

<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4 row-cols-xl-6 g-3 mb-4" id="monthly-summary-cards">
    <?php foreach ($aylar as $ay_num => $ay_adi): ?>
        <?php
        $veri = $aylik_veriler[$ay_num];
        $toplam = $veri['toplam_masraf'];
        $odendi_mi = $veri['odendi_mi'];
        $odeme_tarihi = $veri['odeme_tarihi'];

        $card_class = $odendi_mi ? 'border-success' : 'border-warning';
        $bg_class = $odendi_mi ? 'bg-success-subtle' : ''; // Yeşil arka plan için
        ?>
        <div class="col">
            <div class="card h-100 <?php echo $card_class; ?> <?php echo $bg_class; ?> dashboard-month-card">
                <div class="card-body d-flex flex-column">
                    <h5 class="card-title text-center mb-3"><?php echo $ay_adi . ' ' . $secili_yil; ?></h5>
                    <p class="card-text fs-4 text-center fw-bold flex-grow-1 d-flex align-items-center justify-content-center">
                        <?php echo number_format($toplam, 2, ',', '.'); ?> TL
                    </p>
                    <div class="d-flex justify-content-between align-items-center mt-3">
                        <span>Durum: <?php echo $odendi_mi ? '<span class="badge bg-success">Ödendi</span>' : '<span class="badge bg-warning text-dark">Bekliyor</span>'; ?></span>
                        <div class="form-check form-switch">
                            <input class="form-check-input odendi-check" type="checkbox" role="switch" id="paidSwitch-<?php echo $ay_num; ?>"
                                   data-year="<?php echo $secili_yil; ?>" data-month="<?php echo $ay_num; ?>"
                                   <?php echo $odendi_mi ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="paidSwitch-<?php echo $ay_num; ?>">Ödendi</label>
                        </div>
                    </div>
                    <?php if ($odendi_mi && $odeme_tarihi): ?>
                        <small class="text-muted text-end mt-2">Ödeme Tarihi: <?php echo date("d.m.Y", strtotime($odeme_tarihi)); ?></small>
                    <?php endif; ?>
                    <?php if ($toplam > 0): ?>
                        <a href="api_generate_pdf.php?yil=<?php echo $secili_yil; ?>&ay=<?php echo $ay_num; ?>"
                           class="btn btn-sm btn-danger w-100 mt-2" target="_blank">
                            <i class="bi bi-file-pdf"></i> PDF İndir
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<div class="card">
    <div class="card-body text-center bg-dark text-white rounded">
        <h5 class="card-title mb-2">YILLIK TOPLAM MASRAF</h5>
        <p class="card-text fs-3 fw-bold"><?php echo number_format($toplam_yillik_masraf, 2, ',', '.'); ?> TL</p>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>