<?php
/**
 * Admin Lojistik - Kargo Takvimi ve Depo Operasyon Panosu
 * Konum: /magaza/admin/siparisler/kargo-takvimi.php
 */

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

adminCheck();

// 1. İptal edilmemiş ve iptal talebi OLMAYAN siparişlerin KARGO BEKLEYEN ÖZEL PAKET KUTULARINI çek
$kutu_sorgu = $db->query("
    SELECT od.id as delivery_id, od.order_id, od.delivery_sequence, od.planned_date, 
           o.order_number, u.name, u.surname,
           pkg.name as package_name, pkg.sku, pkg.exam_type, pkg.exam_publication_date,
           GROUP_CONCAT(p.name SEPARATOR '<br>• ') as icerik
    FROM order_deliveries od
    JOIN orders o ON od.order_id = o.id
    JOIN users u ON o.user_id = u.id
    JOIN products pkg ON od.package_id = pkg.id
    JOIN products p ON od.exam_id = p.id
    WHERE od.status = 'pending' 
      AND o.status != 'cancelled' 
      AND o.is_cancel_requested = 0
    GROUP BY od.id
")->fetchAll(PDO::FETCH_ASSOC);

// 2. İptal edilmemiş ve iptal talebi OLMAYAN siparişlerin KARGO BEKLEYEN STANDART ÜRÜNLERİNİ çek
$standart_sorgu = $db->query("
    SELECT oi.id as item_id, oi.order_id, oi.quantity, o.created_at as order_date,
           o.order_number, u.name, u.surname,
           p.name as product_name, p.exam_publication_date, p.type, p.sku, p.exam_type
    FROM order_items oi
    JOIN orders o ON oi.order_id = o.id
    JOIN users u ON o.user_id = u.id
    JOIN products p ON oi.product_id = p.id
    WHERE oi.shipping_status = 'pending' 
      AND p.type NOT IN ('digital', 'exam_package') 
      AND o.status != 'cancelled' 
      AND o.is_cancel_requested = 0
")->fetchAll(PDO::FETCH_ASSOC);

// 3. Son Kargolanan 50 İşlem (Geçmiş Referansı)
$gecmis_kargolar = $db->query("
    (SELECT 'Paket (Kutu)' as tip, od.order_id, od.shipping_company, od.tracking_code, o.order_number, u.name, u.surname, pkg.name as urun_adi, od.status
     FROM order_deliveries od
     JOIN orders o ON od.order_id = o.id
     JOIN users u ON o.user_id = u.id
     JOIN products pkg ON od.package_id = pkg.id
     WHERE od.status IN ('shipped', 'delivered') ORDER BY od.id DESC LIMIT 25)
    UNION ALL
    (SELECT 'Standart Ürün' as tip, oi.order_id, oi.shipping_company, oi.tracking_number as tracking_code, o.order_number, u.name, u.surname, p.name as urun_adi, oi.shipping_status as status
     FROM order_items oi
     JOIN orders o ON oi.order_id = o.id
     JOIN users u ON o.user_id = u.id
     JOIN products p ON oi.product_id = p.id
     WHERE oi.shipping_status IN ('shipped', 'delivered') ORDER BY oi.id DESC LIMIT 25)
    ORDER BY order_number DESC LIMIT 50
")->fetchAll(PDO::FETCH_ASSOC);


// --- BİRLEŞTİRME VE TARİH HESAPLAMA MOTORU ---
$tum_gonderimler = [];
$bugun_obj = new DateTime('midnight');
$bugun_str = $bugun_obj->format('Y-m-d');

// Özel Paketleri Havuza Ekle
foreach($kutu_sorgu as $kutu) {
    $tarih = $kutu['planned_date']; // Örn: 2026-04-14
    if(!$tarih) $tarih = $bugun_str; // Tarih yoksa hemen çıksın
    
    $sku = !empty($kutu['sku']) ? htmlspecialchars($kutu['sku']) : '-';
    $tur = !empty($kutu['exam_type']) ? htmlspecialchars($kutu['exam_type']) : 'Paket';
    $pub_date = !empty($kutu['exam_publication_date']) ? htmlspecialchars($kutu['exam_publication_date']) : '-';

    $icerik_html = "<div class='text-muted mb-2' style='font-size:0.75rem;'><strong>SKU:</strong> {$sku} | <strong>Tür:</strong> {$tur} | <strong>Yayın:</strong> {$pub_date}</div>";
    $icerik_html .= '• ' . $kutu['icerik'];
    
    $tum_gonderimler[] = [
        'tip' => 'Özel Paket',
        'order_id' => $kutu['order_id'],
        'order_number' => $kutu['order_number'],
        'musteri' => $kutu['name'] . ' ' . $kutu['surname'],
        'baslik' => $kutu['package_name'] . ' <span class="badge bg-secondary ms-1">' . $kutu['delivery_sequence'] . '. Kutu</span>',
        'icerik' => $icerik_html,
        'hedef_tarih' => $tarih
    ];
}

// Standart Ürünleri Havuza Ekle (Yayın Tarihi Zekası)
foreach($standart_sorgu as $std) {
    $tarih = $bugun_str; // Varsayılan olarak standart ürün hemen çıkar (Bugün)
    
    if ($std['type'] == 'single_exam' && !empty($std['exam_publication_date'])) {
        $d = DateTime::createFromFormat('d.m.Y', $std['exam_publication_date']);
        if ($d) {
            $d->setTime(0, 0, 0);
            if ($d > $bugun_obj) {
                // Sınav gelecekteyse bir sonraki salıya at
                $d->modify('next tuesday');
                $tarih = $d->format('Y-m-d');
            }
        }
    }

    $sku = !empty($std['sku']) ? htmlspecialchars($std['sku']) : '-';
    $tur = !empty($std['exam_type']) ? htmlspecialchars($std['exam_type']) : '-';
    $pub_date = !empty($std['exam_publication_date']) ? htmlspecialchars($std['exam_publication_date']) : '-';

    $icerik_html = "<div class='text-muted mb-2' style='font-size:0.75rem;'><strong>SKU:</strong> {$sku} | <strong>Tür:</strong> {$tur} | <strong>Yayın:</strong> {$pub_date}</div>";
    $icerik_html .= 'Adet: <strong class="text-dark">' . $std['quantity'] . '</strong>';

    $tum_gonderimler[] = [
        'tip' => 'Standart Ürün',
        'order_id' => $std['order_id'],
        'order_number' => $std['order_number'],
        'musteri' => $std['name'] . ' ' . $std['surname'],
        'baslik' => $std['product_name'],
        'icerik' => $icerik_html,
        'hedef_tarih' => $tarih
    ];
}

// Tarihe Göre Sırala (En eski tarih en üstte)
usort($tum_gonderimler, function($a, $b) {
    return strtotime($a['hedef_tarih']) - strtotime($b['hedef_tarih']);
});

// Kategorize Et
$gecikenler = [];
$bugun = [];
$gelecek = [];

$hafta_sonu_obj = clone $bugun_obj;
$hafta_sonu_obj->modify('+7 days');

foreach($tum_gonderimler as $g) {
    $g_tarih_obj = new DateTime($g['hedef_tarih']);
    
    if ($g_tarih_obj < $bugun_obj) {
        $gecikenler[] = $g;
    } elseif ($g_tarih_obj == $bugun_obj) {
        $bugun[] = $g;
    } else {
        $gelecek[] = $g;
    }
}

$page_title = "Kargo Takvimi ve Depo Panosu";
require_once '../header.php';
?>

<style>
    @media print {
        body { background: #fff; }
        .sidebar, .navbar, .d-print-none { display: none !important; }
        .container, .container-fluid { width: 100% !important; max-width: 100% !important; padding: 0 !important; }
        .card { border: none !important; box-shadow: none !important; margin-bottom: 20px !important; }
        .badge { border: 1px solid #000; color: #000 !important; background: transparent !important; }
        table { width: 100%; border-collapse: collapse; }
        th, td { border: 1px solid #ddd; padding: 8px; font-size: 12px; }
        .table-dark th { background-color: #f8f9fa !important; color: #000 !important; }
        h4, h6 { margin: 0 0 10px 0; }
    }

    /* BEYAZ BUTON SORUNUNU ÇÖZEN CSS KODLARI */
    #kargoTab .nav-link.active {
        background-color: #0d6efd !important; /* Birincil Mavi */
        color: #ffffff !important; /* Beyaz Yazı */
        border-color: #0d6efd !important;
    }
    
    #kargoTab .nav-link {
        background-color: #f8f9fa !important; /* Açık Gri */
        color: #212529 !important; /* Koyu Yazı */
        border: 1px solid #dee2e6 !important;
    }

    #kargoTab .nav-link:hover {
        background-color: #e9ecef !important; /* Hover Durumu */
    }
</style>

<div class="row mb-4 align-items-center d-print-none text-dark">
    <div class="col-md-6">
        <h2 class="fw-bold mb-0"><i class="bi bi-calendar-check text-primary me-2"></i>Kargo Takvimi & Depo Panosu</h2>
        <p class="text-muted small mb-0 mt-1">Gecikenleri, bugün çıkacakları ve planlı paketleri tek ekrandan yönetin.</p>
    </div>
    <div class="col-md-6 text-md-end mt-3 mt-md-0">
        <button onclick="window.print()" class="btn btn-outline-dark fw-bold shadow-sm px-4">
            <i class="bi bi-printer me-2"></i> Listeyi Yazdır (Depo İçin)
        </button>
    </div>
</div>

<ul class="nav nav-pills mb-4 shadow-sm bg-white rounded-pill p-1 border d-print-none gap-2" id="kargoTab" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link active fw-bold rounded-pill px-4" data-bs-toggle="tab" data-bs-target="#bekleyenler" type="button" role="tab">
            <i class="bi bi-box-seam me-1"></i> Gönderim Bekleyenler
            <span class="badge bg-danger ms-1"><?= count($gecikenler) + count($bugun) + count($gelecek) ?></span>
        </button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link fw-bold rounded-pill px-4" data-bs-toggle="tab" data-bs-target="#gecmis" type="button" role="tab">
            <i class="bi bi-truck me-1"></i> Son Kargolananlar
        </button>
    </li>
</ul>

<div class="tab-content" id="kargoTabContent">
    
    <div class="tab-pane fade show active" id="bekleyenler" role="tabpanel">
        
        <?php if(count($gecikenler) > 0): ?>
        <div class="card shadow-sm border-0 mb-4 rounded-4 border-start border-4 border-danger">
            <div class="card-header bg-danger bg-opacity-10 py-3 d-flex justify-content-between align-items-center border-0">
                <h5 class="mb-0 fw-bold text-danger text-uppercase"><i class="bi bi-exclamation-triangle-fill me-2"></i>Gecikmiş & Acil Gönderimler</h5>
                <span class="badge bg-danger rounded-pill"><?= count($gecikenler) ?> Kayıt</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">
                            <tr>
                                <th class="ps-4 py-3">Sipariş / Müşteri</th>
                                <th>İçerik Türü</th>
                                <th>Ürün / Paket Bilgisi</th>
                                <th>Hedef Tarih</th>
                                <th class="text-end pe-4 d-print-none">İşlem</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($gecikenler as $g): ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="fw-bold text-primary">#<?= $g['order_number'] ?></div>
                                    <small class="text-dark fw-bold"><?= $g['musteri'] ?></small>
                                </td>
                                <td><span class="badge bg-light text-dark border"><?= $g['tip'] ?></span></td>
                                <td>
                                    <div class="fw-bold text-dark lh-sm"><?= $g['baslik'] ?></div>
                                    <div class="small text-muted mt-1"><?= $g['icerik'] ?></div>
                                </td>
                                <td><strong class="text-danger"><i class="bi bi-clock-history me-1"></i><?= date('d.m.Y', strtotime($g['hedef_tarih'])) ?></strong></td>
                                <td class="text-end pe-4 d-print-none">
                                    <a href="detay.php?id=<?= $g['order_id'] ?>" class="btn btn-sm btn-danger fw-bold rounded-pill shadow-sm px-3">Kargola <i class="bi bi-chevron-right"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="card shadow-sm border-0 mb-4 rounded-4 border-start border-4 border-warning">
            <div class="card-header bg-warning bg-opacity-10 py-3 d-flex justify-content-between align-items-center border-0">
                <h5 class="mb-0 fw-bold text-dark text-uppercase"><i class="bi bi-calendar2-check-fill text-warning me-2"></i>Bugün Kargolanması Gerekenler</h5>
                <span class="badge bg-warning text-dark rounded-pill"><?= count($bugun) ?> Kayıt</span>
            </div>
            <div class="card-body p-0">
                <?php if(count($bugun) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-4 py-3">Sipariş / Müşteri</th>
                                <th>İçerik Türü</th>
                                <th>Ürün / Paket Bilgisi</th>
                                <th>Durum</th>
                                <th class="text-end pe-4 d-print-none">İşlem</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($bugun as $g): ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="fw-bold text-primary">#<?= $g['order_number'] ?></div>
                                    <small class="text-dark fw-bold"><?= $g['musteri'] ?></small>
                                </td>
                                <td><span class="badge bg-light text-dark border"><?= $g['tip'] ?></span></td>
                                <td>
                                    <div class="fw-bold text-dark lh-sm"><?= $g['baslik'] ?></div>
                                    <div class="small text-muted mt-1"><?= $g['icerik'] ?></div>
                                </td>
                                <td><span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25"><i class="bi bi-box-seam"></i> Hazırlanmalı</span></td>
                                <td class="text-end pe-4 d-print-none">
                                    <a href="detay.php?id=<?= $g['order_id'] ?>" class="btn btn-sm btn-dark fw-bold rounded-pill shadow-sm px-3">Kargola <i class="bi bi-chevron-right"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                    <div class="text-center py-5 text-muted"><i class="bi bi-emoji-smile fs-1 d-block mb-2 text-success opacity-50"></i> Bugün için planlanmış gönderim bulunmuyor.</div>
                <?php endif; ?>
            </div>
        </div>

        <div class="card shadow-sm border-0 mb-4 rounded-4 border-start border-4 border-info">
            <div class="card-header bg-info bg-opacity-10 py-3 d-flex justify-content-between align-items-center border-0">
                <h5 class="mb-0 fw-bold text-dark text-uppercase"><i class="bi bi-calendar3 text-info me-2"></i>Gelecek Planlı Gönderimler</h5>
                <span class="badge bg-info text-dark rounded-pill"><?= count($gelecek) ?> Kayıt</span>
            </div>
            <div class="card-body p-0">
                <?php if(count($gelecek) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-4 py-3">Sipariş / Müşteri</th>
                                <th>İçerik Türü</th>
                                <th>Ürün / Paket Bilgisi</th>
                                <th>Planlanan Kargo Tarihi</th>
                                <th class="text-end pe-4 d-print-none">İşlem</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($gelecek as $g): ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="fw-bold text-primary">#<?= $g['order_number'] ?></div>
                                    <small class="text-dark fw-bold"><?= $g['musteri'] ?></small>
                                </td>
                                <td><span class="badge bg-light text-dark border"><?= $g['tip'] ?></span></td>
                                <td>
                                    <div class="fw-bold text-dark lh-sm"><?= $g['baslik'] ?></div>
                                    <div class="small text-muted mt-1"><?= $g['icerik'] ?></div>
                                </td>
                                <td><strong class="text-info text-dark"><i class="bi bi-calendar-event me-1"></i><?= date('d.m.Y', strtotime($g['hedef_tarih'])) ?></strong></td>
                                <td class="text-end pe-4 d-print-none">
                                    <a href="detay.php?id=<?= $g['order_id'] ?>" class="btn btn-sm btn-outline-secondary fw-bold rounded-pill px-3">İncele</a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                    <div class="text-center py-4 text-muted">İleri tarihli planlanmış bir paket bulunmuyor.</div>
                <?php endif; ?>
            </div>
        </div>

    </div>

    <div class="tab-pane fade d-print-none" id="gecmis" role="tabpanel">
        <div class="card shadow-sm border-0 rounded-4">
            <div class="card-header bg-white py-3 border-bottom">
                <h5 class="mb-0 fw-bold text-uppercase"><i class="bi bi-check-all text-success me-2"></i>Son Kargolanan 50 İşlem</h5>
            </div>
            <div class="card-body p-0">
                <?php if(count($gecmis_kargolar) > 0): ?>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-4 py-3">Sipariş No</th>
                                <th>Müşteri</th>
                                <th>Ürün / Paket</th>
                                <th>Kargo Firması</th>
                                <th>Takip Kodu</th>
                                <th class="text-end pe-4">Siparişe Git</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($gecmis_kargolar as $gk): ?>
                            <tr>
                                <td class="ps-4 fw-bold text-secondary">#<?= $gk['order_number'] ?></td>
                                <td class="fw-bold text-dark"><?= htmlspecialchars($gk['name'].' '.$gk['surname']) ?></td>
                                <td>
                                    <div class="fw-bold text-dark"><?= htmlspecialchars($gk['urun_adi']) ?></div>
                                    <small class="text-muted"><?= $gk['tip'] ?></small>
                                </td>
                                <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($gk['shipping_company'] ?? '-') ?></span></td>
                                <td class="fw-bold user-select-all"><?= htmlspecialchars($gk['tracking_code'] ?? '-') ?></td>
                                <td class="text-end pe-4">
                                    <a href="detay.php?id=<?= $gk['order_id'] ?>" class="btn btn-sm btn-light border shadow-sm"><i class="bi bi-box-arrow-up-right"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                    <div class="text-center py-5 text-muted">Henüz kargolanan bir işlem bulunmuyor.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>

</div>

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