<?php
/**
 * Sınav Koçu - Admin Paneli Ana Sayfa (Gelişmiş Operasyon ve Kriz Merkezi)
 * Konum: /magaza/admin/index.php
 */

require_once '../includes/db.php';
require_once '../includes/functions.php';

// Güvenlik: Sadece admin girebilir
adminCheck();

/**
 * Dinamik Selamlama Mesajı
 */
$saat = (int)date('H');
if ($saat >= 6 && $saat < 12) $selamlama = "Günaydın";
elseif ($saat >= 12 && $saat < 18) $selamlama = "İyi Günler";
elseif ($saat >= 18 && $saat < 23) $selamlama = "İyi Akşamlar";
else $selamlama = "İyi Geceler";

/**
 * ============================================================================
 * 1. KPI (TEMEL PERFORMANS GÖSTERGELERİ) VERİLERİNİ ÇEKME
 * ============================================================================
 */

// A. Bu Ayın Toplam Cirosu (Sadece işleme alınmış ve tamamlanmış siparişler)
$ciro_stmt = $db->query("
    SELECT SUM(total_amount) 
    FROM orders 
    WHERE status IN ('processing', 'shipped', 'delivered') 
    AND MONTH(created_at) = MONTH(CURRENT_DATE()) 
    AND YEAR(created_at) = YEAR(CURRENT_DATE())
");
$aylik_ciro = $ciro_stmt->fetchColumn() ?: 0;

// B. Bekleyen Sipariş Sayısı (Yeni düşen, ödeme/onay bekleyenler)
$bekleyen_stmt = $db->query("SELECT COUNT(id) FROM orders WHERE status = 'pending'");
$bekleyen_siparis = $bekleyen_stmt->fetchColumn() ?: 0;

// C. Bekleyen İptal ve İade Talepleri (Acil Müdahale Gerektirenler)
$talep_stmt = $db->query("SELECT COUNT(id) FROM order_returns WHERE status = 'pending'");
$bekleyen_talep = $talep_stmt->fetchColumn() ?: 0;

// D. GÜNCELLEME: Tüm Lojistik (Bugün veya geçmişte kargolanması gereken Özel Kutular + Standart Ürünler)
$bugun = date('Y-m-d');

// 1. Özel Paket Kutuları
$kutu_stmt = $db->prepare("
    SELECT COUNT(DISTINCT CONCAT(od.order_id, '-', od.delivery_sequence)) 
    FROM order_deliveries od
    JOIN orders o ON od.order_id = o.id
    WHERE od.status = 'pending' AND od.planned_date <= ? AND o.is_cancel_requested = 0 AND o.status != 'cancelled'
");
$kutu_stmt->execute([$bugun]);
$bekleyen_kutu = $kutu_stmt->fetchColumn() ?: 0;

// 2. Standart Ürünler (Yayın tarihi geçmiş veya bugün olanlar)
$std_stmt = $db->prepare("
    SELECT COUNT(oi.id)
    FROM order_items oi
    JOIN products p ON oi.product_id = p.id
    JOIN orders o ON oi.order_id = o.id
    WHERE oi.shipping_status = 'pending' 
    AND p.type NOT IN ('digital', 'exam_package')
    AND o.status != 'cancelled' 
    AND o.is_cancel_requested = 0
    AND (p.exam_publication_date IS NULL OR p.exam_publication_date = '' OR STR_TO_DATE(p.exam_publication_date, '%d.%m.%Y') <= ?)
");
$std_stmt->execute([$bugun]);
$bekleyen_std = $std_stmt->fetchColumn() ?: 0;

$toplam_kargolanacak = $bekleyen_kutu + $bekleyen_std;

/**
 * ============================================================================
 * 2. GRAFİK İÇİN SON 7 GÜNÜN SATIŞ VERİLERİ (CHART.JS) - TÜRKÇE
 * ============================================================================
 */
$grafik_tarihler = [];
$grafik_satislar = [];

// Türkçe aylar için manuel eşleştirme (Sunucu dil ayarlarından bağımsız garanti çözüm)
$aylar_tr_kisa = [
    '01' => 'Oca', '02' => 'Şub', '03' => 'Mar', '04' => 'Nis',
    '05' => 'May', '06' => 'Haz', '07' => 'Tem', '08' => 'Ağu',
    '09' => 'Eyl', '10' => 'Eki', '11' => 'Kas', '12' => 'Ara'
];

for ($i = 6; $i >= 0; $i--) {
    $tarih = date('Y-m-d', strtotime("-$i days"));
    $gun = date('d', strtotime("-$i days"));
    $ay = date('m', strtotime("-$i days"));
    
    $gosterim_tarihi = $gun . ' ' . $aylar_tr_kisa[$ay]; // Örn: 15 Mar, 02 Nis
    
    // O günün net cirosunu çek
    $gunluk_stmt = $db->prepare("
        SELECT SUM(total_amount) 
        FROM orders 
        WHERE DATE(created_at) = ? AND status IN ('processing', 'shipped', 'delivered')
    ");
    $gunluk_stmt->execute([$tarih]);
    $gunluk_ciro = $gunluk_stmt->fetchColumn() ?: 0;
    
    $grafik_tarihler[] = $gosterim_tarihi;
    $grafik_satislar[] = (float)$gunluk_ciro;
}

/**
 * ============================================================================
 * 3. HIZLI AKSİYON VE KRİZ YÖNETİMİ LİSTELERİ
 * ============================================================================
 */

// Acil İptal ve İade Talepleri Tablosu İçin Veri
$son_talepler = $db->query("
    SELECT r.*, o.order_number, u.name, u.surname 
    FROM order_returns r 
    JOIN orders o ON r.order_id = o.id 
    JOIN users u ON r.user_id = u.id 
    WHERE r.status = 'pending' 
    ORDER BY r.created_at ASC LIMIT 5
")->fetchAll();

// Son Siparişler (İptal/İade Zekasıyla Birlikte)
$son_siparisler = $db->query("
    SELECT o.id, o.order_number, o.total_amount, o.status, o.created_at, o.is_cancel_requested, u.name, u.surname,
           (SELECT status FROM order_returns WHERE order_id = o.id AND request_type = 'return' ORDER BY id DESC LIMIT 1) as iade_durumu
    FROM orders o 
    JOIN users u ON o.user_id = u.id 
    ORDER BY o.is_cancel_requested DESC, o.id DESC LIMIT 6
")->fetchAll();

// Son Kayıt Olan Öğrenciler
$son_uyeler = $db->query("
    SELECT id, name, surname, email, created_at 
    FROM users 
    WHERE role = 'customer' 
    ORDER BY id DESC LIMIT 5
")->fetchAll();

/**
 * İngilizce durumları Türkçe ve Görsel Badge'lere çeviren fonksiyon
 */
function adminSiparisDurumCevir($status) {
    switch ($status) {
        case 'pending': return '<span class="badge bg-warning text-dark rounded-pill px-3 py-2"><i class="bi bi-hourglass-split"></i> Onay Bekliyor</span>';
        case 'processing': return '<span class="badge bg-info text-dark rounded-pill px-3 py-2"><i class="bi bi-box-seam"></i> Hazırlanıyor</span>';
        case 'shipped': return '<span class="badge bg-primary rounded-pill px-3 py-2"><i class="bi bi-truck"></i> Kargolandı</span>';
        case 'delivered': return '<span class="badge bg-success rounded-pill px-3 py-2"><i class="bi bi-check-circle"></i> Teslim Edildi</span>';
        case 'cancelled': return '<span class="badge bg-danger rounded-pill px-3 py-2"><i class="bi bi-x-circle"></i> İptal Edildi</span>';
        default: return '<span class="badge bg-secondary rounded-pill px-3 py-2">Bilinmiyor</span>';
    }
}

// Header Çağrısı
require_once 'header.php';
?>

<style>
    /* Kriz Masası İçin Animasyonlar */
    @keyframes pulse-danger {
        0% { box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7); }
        70% { box-shadow: 0 0 0 10px rgba(220, 53, 69, 0); }
        100% { box-shadow: 0 0 0 0 rgba(220, 53, 69, 0); }
    }
    .card-pulse-danger { animation: pulse-danger 2s infinite; border: 2px solid #dc3545 !important; }
    .table-danger-soft { background-color: rgba(220, 53, 69, 0.05) !important; }
</style>

<div class="row mb-4 align-items-center">
    <div class="col-12">
        <h2 class="fw-bold text-dark mb-0">
            <i class="bi bi-speedometer2 text-primary me-2"></i> Yönetim Paneli Özeti
        </h2>
        <p class="text-muted small mt-1 mb-0"><?= $selamlama ?> Yönetici! Operasyonel durum ve acil talepler aşağıdadır.</p>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-xl-3 col-md-6">
        <div class="card border-0 shadow-sm bg-primary text-white h-100 rounded-4">
            <div class="card-body p-4">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="fw-bold text-uppercase mb-0 opacity-75">Bu Ayki Ciro</h6>
                    <i class="bi bi-wallet2 fs-2 opacity-50"></i>
                </div>
                <h3 class="fw-bold mb-0"><?= formatPrice($aylik_ciro) ?></h3>
                <small class="opacity-75">Onaylanan siparişler baz alınmıştır.</small>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card shadow-sm text-dark h-100 rounded-4 <?= $bekleyen_talep > 0 ? 'bg-white card-pulse-danger' : 'border-0 bg-danger text-white' ?>">
            <div class="card-body p-4">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="fw-bold text-uppercase mb-0 <?= $bekleyen_talep > 0 ? 'text-danger' : 'opacity-75' ?>">Bekleyen Talepler</h6>
                    <i class="bi bi-exclamation-octagon-fill fs-2 <?= $bekleyen_talep > 0 ? 'text-danger' : 'opacity-50' ?>"></i>
                </div>
                <h3 class="fw-bold mb-0 <?= $bekleyen_talep > 0 ? 'text-danger' : '' ?>"><?= $bekleyen_talep ?> Talep</h3>
                <small class="<?= $bekleyen_talep > 0 ? 'text-muted fw-bold' : 'opacity-75' ?>">İptal ve iade onayları.</small>
                <?php if($bekleyen_talep > 0): ?>
                    <a href="siparisler/iptaller.php" class="stretched-link"></a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card border-0 shadow-sm bg-warning text-dark h-100 rounded-4">
            <div class="card-body p-4">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="fw-bold text-uppercase mb-0 opacity-75">Bekleyen Sipariş</h6>
                    <i class="bi bi-cart-dash fs-2 opacity-50"></i>
                </div>
                <h3 class="fw-bold mb-0"><?= $bekleyen_siparis ?> Adet</h3>
                <small class="opacity-75">Ödeme veya onay bekleyenler.</small>
                <?php if($bekleyen_siparis > 0): ?>
                    <a href="siparisler/index.php?status=pending" class="stretched-link"></a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
        <div class="card border-0 shadow-sm bg-dark text-white h-100 rounded-4">
            <div class="card-body p-4">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="fw-bold text-uppercase mb-0 opacity-75">Kargolanacak Paket</h6>
                    <i class="bi bi-boxes fs-2 opacity-50"></i>
                </div>
                <h3 class="fw-bold mb-0 text-info"><?= $toplam_kargolanacak ?> Paket</h3>
                <small class="opacity-75">Bugün ve öncesine ait gönderimler.</small>
                <a href="siparisler/kargo-takvimi.php" class="stretched-link"></a>
            </div>
        </div>
    </div>
</div>

<?php if (count($son_talepler) > 0): ?>
<div class="row mb-4">
    <div class="col-12">
        <div class="card border-0 shadow-sm rounded-4 overflow-hidden border-danger border-opacity-50" style="border-width: 2px !important;">
            <div class="card-header bg-danger bg-opacity-10 pt-3 pb-3 px-4 d-flex justify-content-between align-items-center border-bottom border-danger border-opacity-25">
                <h6 class="fw-bold text-uppercase text-danger mb-0"><i class="bi bi-shield-exclamation me-2"></i>Müdahale Bekleyen İptal/İade Talepleri</h6>
                <span class="badge bg-danger rounded-pill px-3 py-2">Acil İşlem Gerektirir</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light text-muted small">
                            <tr>
                                <th class="ps-4">Tarih</th>
                                <th>Tür</th>
                                <th>Sipariş / Müşteri</th>
                                <th>Talep Nedeni</th>
                                <th class="text-end pe-4">İşlem</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($son_talepler as $talep): ?>
                            <tr>
                                <td class="ps-4 small fw-bold text-dark"><?= date('d.m.Y H:i', strtotime($talep['created_at'])) ?></td>
                                <td>
                                    <span class="badge bg-<?= $talep['request_type'] == 'cancellation' ? 'danger' : 'info text-dark' ?> px-3 py-1 rounded-pill">
                                        <?= $talep['request_type'] == 'cancellation' ? 'İPTAL İSTEĞİ' : 'İADE İSTEĞİ' ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="fw-bold text-primary">#<?= $talep['order_number'] ?></div>
                                    <div class="small text-muted"><?= htmlspecialchars($talep['name'].' '.$talep['surname']) ?></div>
                                </td>
                                <td class="small text-truncate" style="max-width: 250px;">
                                    <b><?= htmlspecialchars($talep['reason']) ?></b><br>
                                    <span class="text-muted fst-italic"><?= htmlspecialchars($talep['customer_note']) ?></span>
                                </td>
                                <td class="text-end pe-4">
                                    <a href="siparisler/<?= $talep['request_type'] == 'cancellation' ? 'iptaller.php' : 'iadeler.php' ?>" class="btn btn-sm btn-dark rounded-pill fw-bold px-3">
                                        Yanıtla <i class="bi bi-arrow-right ms-1"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="row mb-4">
    <div class="col-12">
        <div class="card border-0 shadow-sm rounded-4">
            <div class="card-header bg-white border-bottom-0 pt-4 pb-0 px-4">
                <h6 class="fw-bold text-uppercase text-muted"><i class="bi bi-graph-up-arrow text-primary me-2"></i>Son 7 Günlük Satış Trendi</h6>
            </div>
            <div class="card-body p-4">
                <canvas id="salesChart" height="60"></canvas>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 mb-5">
    
    <div class="col-lg-7">
        <div class="card border-0 shadow-sm rounded-4 h-100">
            <div class="card-header bg-white border-bottom-0 pt-4 pb-2 px-4 d-flex justify-content-between align-items-center">
                <h6 class="fw-bold text-uppercase text-muted mb-0"><i class="bi bi-cart-check-fill text-warning me-2"></i>Son Gelen Siparişler</h6>
                <a href="siparisler/index.php" class="btn btn-sm btn-outline-dark fw-bold rounded-pill px-3">Tümünü Gör</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-4">Müşteri</th>
                                <th>Tutar</th>
                                <th class="text-center">Durum</th>
                                <th class="text-end pe-4">İncele</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($son_siparisler): foreach($son_siparisler as $s): ?>
                            <tr class="<?= $s['is_cancel_requested'] ? 'table-danger-soft' : '' ?>">
                                <td class="ps-4">
                                    <div class="fw-bold text-dark"><?= htmlspecialchars($s['name'].' '.$s['surname']) ?></div>
                                    <small class="text-muted">#<?= $s['order_number'] ?></small>
                                </td>
                                <td class="fw-bold text-success"><?= formatPrice($s['total_amount']) ?></td>
                                <td class="text-center">
                                    <?php if($s['is_cancel_requested']): ?>
                                        <span class="badge bg-danger rounded-pill px-3 py-2"><i class="bi bi-slash-circle"></i> İPTAL TALEBİ</span>
                                    <?php elseif($s['iade_durumu'] && $s['iade_durumu'] != 'completed'): ?>
                                        <span class="badge bg-info text-dark rounded-pill px-3 py-2"><i class="bi bi-arrow-counterclockwise"></i> İADE SÜRECİ</span>
                                    <?php else: ?>
                                        <?= adminSiparisDurumCevir($s['status']) ?>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end pe-4">
                                    <a href="siparisler/detay.php?id=<?= $s['id'] ?>" class="btn btn-sm btn-light border shadow-sm rounded-circle"><i class="bi bi-chevron-right"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; else: ?>
                            <tr><td colspan="4" class="text-center text-muted py-4">Henüz sipariş kaydı yok.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-lg-5">
        <div class="card border-0 shadow-sm rounded-4 h-100">
            <div class="card-header bg-white border-bottom-0 pt-4 pb-2 px-4 d-flex justify-content-between align-items-center">
                <h6 class="fw-bold text-uppercase text-muted mb-0"><i class="bi bi-person-plus-fill text-success me-2"></i>Yeni Müşteriler</h6>
                <a href="musteri/index.php" class="btn btn-sm btn-outline-dark fw-bold rounded-pill px-3">Tümünü Gör</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-4">Müşteri Profili</th>
                                <th class="text-end pe-4">Kayıt Tarihi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($son_uyeler): foreach($son_uyeler as $u): ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="d-flex align-items-center">
                                        <div class="bg-primary text-white rounded-circle d-flex justify-content-center align-items-center fw-bold shadow-sm me-3" style="width: 40px; height: 40px;">
                                            <?= mb_substr($u['name'],0,1).mb_substr($u['surname'],0,1) ?>
                                        </div>
                                        <div>
                                            <div class="fw-bold text-dark mb-0 lh-sm"><?= htmlspecialchars($u['name'].' '.$u['surname']) ?></div>
                                            <a href="mailto:<?= htmlspecialchars($u['email']) ?>" class="small text-muted text-decoration-none"><?= htmlspecialchars($u['email']) ?></a>
                                        </div>
                                    </div>
                                </td>
                                <td class="text-end pe-4 text-muted small fw-bold">
                                    <?= date('d.m.Y', strtotime($u['created_at'])) ?>
                                </td>
                            </tr>
                            <?php endforeach; else: ?>
                            <tr><td colspan="2" class="text-center text-muted py-4">Henüz üye kaydı yok.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </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 JS'e verileri güvenli aktarım
    const chartLabels = <?= json_encode($grafik_tarihler) ?>;
    const chartData = <?= json_encode($grafik_satislar) ?>;
    
    const salesChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: chartLabels,
            datasets: [{
                label: 'Günlük Ciro (₺)',
                data: chartData,
                borderColor: '#0d6efd',
                backgroundColor: 'rgba(13, 110, 253, 0.1)',
                borderWidth: 3,
                pointBackgroundColor: '#fff',
                pointBorderColor: '#0d6efd',
                pointBorderWidth: 2,
                pointRadius: 4,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let value = context.parsed.y;
                            return value.toLocaleString('tr-TR', { style: 'currency', currency: 'TRY' });
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) { return '₺' + value; }
                    }
                }
            }
        }
    });
</script>

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