<?php
/**
 * Admin Finans - Dashboard ve İstatistik Merkezi
 * Konum: /magaza/admin/finans/index.php
 */

require_once '../../includes/db.php';
require_once '../../includes/functions.php';
adminCheck();

// --- 1. KPI (ÖZET) KARTLARI İÇİN VERİLERİ ÇEK ---

// A. Toplam Ciro (İptal edilenler hariç)
$toplam_ciro = $db->query("SELECT SUM(total_amount) FROM orders WHERE status != 'cancelled'")->fetchColumn() ?: 0;

// B. Bu Ayki Ciro
$aylik_ciro = $db->query("SELECT SUM(total_amount) FROM orders WHERE status != 'cancelled' AND MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())")->fetchColumn() ?: 0;

// C. Bugünkü Ciro
$gunluk_ciro = $db->query("SELECT SUM(total_amount) FROM orders WHERE status != 'cancelled' AND DATE(created_at) = CURDATE()")->fetchColumn() ?: 0;

// D. Onay Bekleyen (Pending) Tahsilat Tutarı (Havale/EFT)
$bekleyen_tahsilat = $db->query("SELECT SUM(amount) FROM payments WHERE status = 'pending'")->fetchColumn() ?: 0;

// E. Toplam Başarılı Sipariş Sayısı
$basarili_siparis = $db->query("SELECT COUNT(id) FROM orders WHERE status IN ('processing', 'shipped', 'delivered')")->fetchColumn() ?: 0;


// --- 2. GRAFİK İÇİN SON 30 GÜNÜN SATIŞ TRENDİ ---
$grafik_sorgu = $db->query("
    SELECT DATE(created_at) as order_date, SUM(total_amount) as daily_total
    FROM orders
    WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND status != 'cancelled'
    GROUP BY DATE(created_at)
    ORDER BY DATE(created_at) ASC
")->fetchAll(PDO::FETCH_ASSOC);

$grafik_tarihler = [];
$grafik_tutarlar = [];
foreach ($grafik_sorgu as $g) {
    $grafik_tarihler[] = date('d.m', strtotime($g['order_date']));
    $grafik_tutarlar[] = (float)$g['daily_total'];
}


// --- 3. EN ÇOK KAZANDIRAN ÜRÜNLER (TOP 5) ---
$top_urunler = $db->query("
    SELECT p.name, p.type, SUM(oi.quantity) as total_qty, SUM(oi.quantity * oi.unit_price) as total_revenue
    FROM order_items oi
    JOIN orders o ON oi.order_id = o.id
    JOIN products p ON oi.product_id = p.id
    WHERE o.status != 'cancelled'
    GROUP BY p.id
    ORDER BY total_revenue DESC
    LIMIT 5
")->fetchAll();

require_once '../header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0 text-dark"><i class="bi bi-wallet2 text-success me-2"></i>Finansal Dashboard</h2>
    <div class="text-muted small fw-bold">
        <i class="bi bi-clock"></i> Son Güncelleme: <?= date('d.m.Y H:i') ?>
    </div>
</div>

<div class="row g-4 mb-4 text-dark">
    <div class="col-sm-6 col-lg-3">
        <div class="card shadow-sm border-0 rounded-4 h-100 bg-white">
            <div class="card-body p-4 position-relative overflow-hidden">
                <i class="bi bi-calendar-day text-primary position-absolute top-50 end-0 translate-middle-y me-n3 opacity-25" style="font-size: 5rem;"></i>
                <h6 class="text-muted fw-bold text-uppercase mb-2">Bugünkü Ciro</h6>
                <h3 class="fw-bold text-primary mb-0"><?= number_format($gunluk_ciro, 2, ',', '.') ?> ₺</h3>
            </div>
        </div>
    </div>
    
    <div class="col-sm-6 col-lg-3">
        <div class="card shadow-sm border-0 rounded-4 h-100 bg-white">
            <div class="card-body p-4 position-relative overflow-hidden">
                <i class="bi bi-calendar-month text-success position-absolute top-50 end-0 translate-middle-y me-n3 opacity-25" style="font-size: 5rem;"></i>
                <h6 class="text-muted fw-bold text-uppercase mb-2">Bu Ayki Ciro</h6>
                <h3 class="fw-bold text-success mb-0"><?= number_format($aylik_ciro, 2, ',', '.') ?> ₺</h3>
            </div>
        </div>
    </div>

    <div class="col-sm-6 col-lg-3">
        <div class="card shadow-sm border-0 rounded-4 h-100 bg-white">
            <div class="card-body p-4 position-relative overflow-hidden">
                <i class="bi bi-hourglass-split text-warning position-absolute top-50 end-0 translate-middle-y me-n3 opacity-25" style="font-size: 5rem;"></i>
                <h6 class="text-muted fw-bold text-uppercase mb-2">Bekleyen Havale</h6>
                <h3 class="fw-bold text-warning mb-0"><?= number_format($bekleyen_tahsilat, 2, ',', '.') ?> ₺</h3>
            </div>
        </div>
    </div>

    <div class="col-sm-6 col-lg-3">
        <div class="card shadow-sm border-0 rounded-4 h-100 bg-dark text-white">
            <div class="card-body p-4 position-relative overflow-hidden">
                <i class="bi bi-box-seam text-white position-absolute top-50 end-0 translate-middle-y me-n3 opacity-25" style="font-size: 5rem;"></i>
                <h6 class="text-light fw-bold text-uppercase mb-2">Başarılı Sipariş</h6>
                <h3 class="fw-bold mb-0"><?= $basarili_siparis ?> <small class="fs-6 fw-normal">Adet</small></h3>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 text-dark mb-4">
    <div class="col-lg-8">
        <div class="card shadow-sm border-0 rounded-4 h-100">
            <div class="card-header bg-white py-3 border-bottom-0">
                <h6 class="mb-0 fw-bold"><i class="bi bi-graph-up-arrow text-primary me-2"></i>Son 30 Günlük Satış Trendi</h6>
            </div>
            <div class="card-body p-4">
                <canvas id="salesChart" height="100"></canvas>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card shadow-sm border-0 rounded-4 h-100">
            <div class="card-header bg-white py-3 border-bottom-0">
                <h6 class="mb-0 fw-bold"><i class="bi bi-trophy-fill text-warning me-2"></i>En Çok Kazandıranlar</h6>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush rounded-bottom">
                    <?php if (count($top_urunler) > 0): ?>
                        <?php foreach($top_urunler as $index => $urun): ?>
                            <li class="list-group-item p-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div class="me-3">
                                        <span class="badge bg-light text-dark border me-2"><?= $index + 1 ?></span>
                                        <span class="fw-bold text-dark"><?= htmlspecialchars($urun['name']) ?></span>
                                        <small class="d-block text-muted mt-1">Tür: <?= $urun['type'] == 'subscription' ? 'Abonelik' : 'Fiziksel' ?> | Satış: <?= $urun['total_qty'] ?> Adet</small>
                                    </div>
                                    <div class="text-end fw-bold text-success fs-6">
                                        <?= number_format($urun['total_revenue'], 2, ',', '.') ?> ₺
                                    </div>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <li class="list-group-item p-4 text-center text-muted">Henüz onaylanmış satış verisi yok.</li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

<div class="row text-dark">
    <div class="col-12">
        <div class="card shadow-sm border-0 rounded-4">
            <div class="card-body p-4 text-center">
                <h6 class="fw-bold mb-4 text-uppercase text-muted">Finansal Operasyon Kısayolları</h6>
                <div class="d-flex justify-content-center gap-3 flex-wrap">
                    <a href="dekontlar.php" class="btn btn-warning fw-bold px-4 py-2 rounded-pill shadow-sm">
                        <i class="bi bi-bank me-2"></i> Dekont Bekleyenleri Yönet
                    </a>
                    <a href="faturalar.php" class="btn btn-info text-white fw-bold px-4 py-2 rounded-pill shadow-sm">
                        <i class="bi bi-file-earmark-pdf me-2"></i> E-Fatura Kesilecekler
                    </a>
                    <a href="satislar.php" class="btn btn-dark fw-bold px-4 py-2 rounded-pill shadow-sm">
                        <i class="bi bi-list-columns-reverse me-2"></i> Tüm Satış Dökümü
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    const ctx = document.getElementById('salesChart').getContext('2d');
    
    // PHP'den Gelen Dinamik Veriler
    const chartLabels = <?= json_encode($grafik_tarihler) ?>;
    const chartData = <?= json_encode($grafik_tutarlar) ?>;

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: chartLabels.length > 0 ? chartLabels : ['Veri Yok'],
            datasets: [{
                label: 'Günlük Ciro (₺)',
                data: chartData.length > 0 ? chartData : [0],
                borderColor: '#0d6efd',
                backgroundColor: 'rgba(13, 110, 253, 0.1)',
                borderWidth: 3,
                pointBackgroundColor: '#0d6efd',
                pointBorderColor: '#fff',
                pointHoverBackgroundColor: '#fff',
                pointHoverBorderColor: '#0d6efd',
                fill: true,
                tension: 0.4 // Çizgiyi yumuşatır (Kıvrımlı yapar)
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return context.parsed.y.toLocaleString('tr-TR', { minimumFractionDigits: 2 }) + ' ₺';
                        }
                    }
                }
            },
            scales: {
                y: { 
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) { return value + ' ₺'; }
                    }
                }
            }
        }
    });
</script>

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