<?php
/**
 * Admin Deneme Paketi Lojistik Merkezi (Geliver API, İleri Tarihli Planlar, Tekli Denemeler & Sayfalama)
 * Konum: /magaza/admin/denemepaket/index.php
 */

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

// Geliver API Motorunu dahil ediyoruz
$geliver_yolu = '../../includes/geliver.php';
if(file_exists($geliver_yolu)) require_once $geliver_yolu;

adminCheck();

$bugun = date('Y-m-d');
$mesaj = '';

// --- SAYFALAMA VE SEKME AYARLARI ---
$limit = 20; // Her sayfada gösterilecek kayıt sayısı
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'acil'; // Hangi sekme aktif? (acil veya yaklasan)
$pa = isset($_GET['pa']) ? max(1, (int)$_GET['pa']) : 1; // Acil sekmesi sayfa no
$py = isset($_GET['py']) ? max(1, (int)$_GET['py']) : 1; // Yaklaşan sekmesi sayfa no

$offset_a = ($pa - 1) * $limit;
$offset_y = ($py - 1) * $limit;

$form_action = "?tab={$active_tab}&pa={$pa}&py={$py}";

/**
 * --- İŞLEM 1: GELİVER API İLE KUTU KARGOLAMA ---
 */
if (isset($_POST['api_kargo_yap_kutu'])) {
    $order_id = (int)$_POST['order_id'];
    $seq = (int)$_POST['sequence'];
    $source_type = $_POST['source_type'] ?? 'package';
    $item_id = (int)($_POST['item_id'] ?? 0);

    $stmt = $db->prepare("
        SELECT o.order_number, o.user_id, u.name, u.surname, u.phone, u.email,
               ua.full_address, ua.city, ua.district
        FROM orders o
        JOIN users u ON o.user_id = u.id
        LEFT JOIN user_addresses ua ON o.shipping_address_id = ua.id
        WHERE o.id = ?
    ");
    $stmt->execute([$order_id]);
    $detay = $stmt->fetch();

    if ($detay && function_exists('geliver_kargo_olustur')) {
        
        $kargo_sonek = ($source_type == 'package') ? "-KUTU-" . $seq : "-TEKLI-" . $item_id;

        $siparis_datasi = [
            'order_number' => $detay['order_number'] . $kargo_sonek,
            'name'         => $detay['name'],
            'surname'      => $detay['surname'],
            'phone'        => $detay['phone'],
            'email'        => $detay['email'],
            'address'      => $detay['full_address'] ?? 'Adres Yok',
            'city'         => $detay['city'] ?? '',
            'district'     => $detay['district'] ?? ''
        ];

        $geliver = geliver_kargo_olustur($siparis_datasi);

        if ($geliver['ok']) {
            if ($source_type == 'package') {
                $up = $db->prepare("UPDATE order_deliveries SET status = 'shipped', shipping_company = 'Geliver API', tracking_code = ?, barcode_url = ? WHERE order_id = ? AND delivery_sequence = ?");
                $up->execute([$geliver['tracking'], $geliver['barcode_url'], $order_id, $seq]);
                $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-rocket-takeoff-fill me-2'></i> <b>{$seq}. Kutu</b> için Geliver barkodu oluşturuldu!</div>";
                
                // BİLDİRİM TETİKLEYİCİ: Paket Geliver ile kargolandı
                siteBildirimGonder($detay['user_id'], "Paketiniz Kargoya Verildi", "#{$detay['order_number']} numaralı siparişinize ait {$seq}. Gönderim Kutusu Geliver aracılığıyla yola çıktı. Takip No: {$geliver['tracking']}", "siparis-detay.php?id={$order_id}", "bi-truck text-primary");
            } else {
                $up = $db->prepare("UPDATE order_items SET shipping_status = 'shipped', shipping_company = 'Geliver API', tracking_number = ? WHERE id = ?");
                $up->execute([$geliver['tracking'], $item_id]);
                $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-rocket-takeoff-fill me-2'></i> <b>Tekli Gönderim</b> için Geliver barkodu oluşturuldu!</div>";
                
                // BİLDİRİM TETİKLEYİCİ: Ürün Geliver ile kargolandı
                siteBildirimGonder($detay['user_id'], "Ürününüz Kargoya Verildi", "#{$detay['order_number']} numaralı siparişinizdeki ürün Geliver aracılığıyla yola çıktı. Takip No: {$geliver['tracking']}", "siparis-detay.php?id={$order_id}", "bi-truck text-primary");
            }
        } else {
            $mesaj = "<div class='alert alert-danger'>Geliver Hatası: " . $geliver['message'] . "</div>";
        }
    }
}

/**
 * --- İŞLEM 2: MANUEL KARGO GİRİŞİ ---
 */
if (isset($_POST['manuel_kargo_kutu'])) {
    $order_id = (int)$_POST['order_id'];
    $seq = (int)$_POST['sequence'];
    $firma = trim($_POST['kargo_firma']);
    $takip = trim($_POST['tracking_code']);
    
    $source_type = $_POST['source_type'] ?? 'package';
    $item_id = (int)($_POST['item_id'] ?? 0);

    if ($source_type == 'package') {
        $db->prepare("UPDATE order_deliveries SET status = 'shipped', shipping_company = ?, tracking_code = ? WHERE order_id = ? AND delivery_sequence = ?")
           ->execute([$firma, $takip, $order_id, $seq]);
    } else {
        $db->prepare("UPDATE order_items SET shipping_status = 'shipped', shipping_company = ?, tracking_number = ? WHERE id = ?")
           ->execute([$firma, $takip, $item_id]);
    }
    
    // BİLDİRİM TETİKLEYİCİ: Manuel Kargo
    $u_stmt = $db->prepare("SELECT user_id, order_number FROM orders WHERE id = ?");
    $u_stmt->execute([$order_id]);
    $u_info = $u_stmt->fetch();
    
    if($u_info) {
        $bildirim_metni = ($source_type == 'package') 
            ? "#{$u_info['order_number']} numaralı siparişinize ait {$seq}. Gönderim Kutusu {$firma} ile kargoya verildi. Takip No: {$takip}"
            : "#{$u_info['order_number']} numaralı siparişinize ait ürün {$firma} ile kargoya verildi. Takip No: {$takip}";
            
        siteBildirimGonder($u_info['user_id'], "Kargonuz Yola Çıktı", $bildirim_metni, "siparis-detay.php?id={$order_id}", "bi-truck text-primary");
    }
    
    $mesaj = "<div class='alert alert-success shadow-sm'>Manuel kargo bilgisi kaydedildi.</div>";
}

// --- İSTATİSTİKLER (İleri tarihli tekli ürünler hesaba katıldı) ---
$stat_geciken = $db->query("
    SELECT SUM(c) FROM (
        SELECT COUNT(DISTINCT CONCAT(od.order_id, '-', od.delivery_sequence)) as c FROM order_deliveries od JOIN orders o ON od.order_id = o.id WHERE od.status = 'pending' AND od.planned_date < '$bugun' AND o.is_cancel_requested = 0 AND o.status != 'cancelled'
        UNION ALL
        SELECT COUNT(DISTINCT oi.id) as c FROM order_items oi JOIN orders o ON oi.order_id = o.id JOIN products p ON oi.product_id = p.id WHERE oi.shipping_status = 'pending' AND p.type = 'single_exam' AND COALESCE(STR_TO_DATE(NULLIF(p.exam_publication_date, ''), '%e.%m.%Y'), DATE(o.created_at)) < '$bugun' AND o.is_cancel_requested = 0 AND o.status != 'cancelled'
    ) t
")->fetchColumn();

$stat_bugun = $db->query("
    SELECT SUM(c) FROM (
        SELECT COUNT(DISTINCT CONCAT(od.order_id, '-', od.delivery_sequence)) as c FROM order_deliveries od JOIN orders o ON od.order_id = o.id WHERE od.status = 'pending' AND od.planned_date = '$bugun' AND o.is_cancel_requested = 0 AND o.status != 'cancelled'
        UNION ALL
        SELECT COUNT(DISTINCT oi.id) as c FROM order_items oi JOIN orders o ON oi.order_id = o.id JOIN products p ON oi.product_id = p.id WHERE oi.shipping_status = 'pending' AND p.type = 'single_exam' AND COALESCE(STR_TO_DATE(NULLIF(p.exam_publication_date, ''), '%e.%m.%Y'), DATE(o.created_at)) = '$bugun' AND o.is_cancel_requested = 0 AND o.status != 'cancelled'
    ) t
")->fetchColumn();

$stat_iptal_talep = $db->query("SELECT COUNT(DISTINCT id) FROM orders WHERE is_cancel_requested = 1 AND status != 'cancelled'")->fetchColumn();

$stat_aktif = $db->query("
    SELECT SUM(c) FROM (
        SELECT COUNT(DISTINCT od.order_id) as c FROM order_deliveries od JOIN orders o ON od.order_id = o.id WHERE od.status = 'pending' AND o.status != 'cancelled'
        UNION ALL
        SELECT COUNT(DISTINCT oi.order_id) as c FROM order_items oi JOIN orders o ON oi.order_id = o.id JOIN products p ON oi.product_id = p.id WHERE oi.shipping_status = 'pending' AND p.type = 'single_exam' AND o.status != 'cancelled'
    ) t
")->fetchColumn();


// --- ANA SORGULAR VE SAYFALAMA MOTORU (Sıralama: ASC - Yakın tarihten uzağa) ---
// GÜNCELLEME: GROUP_CONCAT ve normal seçimlere Yayın Tarihi eklendi.
$sql_core = "
    SELECT 
        od.order_id, od.delivery_sequence, od.planned_date, od.status as box_status, od.tracking_code, od.barcode_url,
        o.order_number, o.is_cancel_requested,
        u.name as user_name, u.surname as user_surname,
        pkg.name as package_name, b.logo as brand_logo,
        COALESCE(
            (SELECT image_path FROM product_images WHERE product_id = pkg.id AND is_main = 1 LIMIT 1),
            b.default_cover,
            'assets/img/no-image.jpg'
        ) as main_image,
        GROUP_CONCAT(CONCAT(p.name, ' <span class=\"badge bg-danger ms-1\">[Yayın: ', COALESCE(NULLIF(p.exam_publication_date, ''), 'Belirtilmemiş'), ']</span>') SEPARATOR '<br>• ') as exam_list,
        'package' as source_type,
        0 as item_id
    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
    LEFT JOIN brands b ON pkg.brand_id = b.id
    JOIN products p ON od.exam_id = p.id
    WHERE od.status = 'pending' AND o.status != 'cancelled'
    GROUP BY od.order_id, od.delivery_sequence
    
    UNION ALL
    
    SELECT 
        oi.order_id, 1 as delivery_sequence, 
        COALESCE(STR_TO_DATE(NULLIF(p.exam_publication_date, ''), '%e.%m.%Y'), DATE(o.created_at)) as planned_date, 
        oi.shipping_status as box_status, oi.tracking_number as tracking_code, NULL as barcode_url,
        o.order_number, o.is_cancel_requested,
        u.name as user_name, u.surname as user_surname,
        'Tekli Satış' as package_name, b.logo as brand_logo,
        COALESCE(
            (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1),
            b.default_cover,
            'assets/img/no-image.jpg'
        ) as main_image,
        CONCAT(p.name, ' (', oi.quantity, ' Adet)', ' <span class=\"badge bg-danger ms-1\">[Yayın: ', COALESCE(NULLIF(p.exam_publication_date, ''), 'Belirtilmemiş'), ']</span>') as exam_list,
        'single' as source_type,
        oi.id as item_id
    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
    LEFT JOIN brands b ON p.brand_id = b.id
    WHERE oi.shipping_status = 'pending' AND p.type = 'single_exam' AND o.status != 'cancelled'
";

// 1. Acil ve Bugün İçin Sayfalama (Sıralama: planned_date ASC)
$acil_count = $db->query("SELECT COUNT(*) FROM ($sql_core) as t WHERE planned_date <= '$bugun'")->fetchColumn();
$acil_pages = ceil($acil_count / $limit);
$acil_kutular = $db->query("SELECT * FROM ($sql_core) as t WHERE planned_date <= '$bugun' ORDER BY is_cancel_requested DESC, planned_date ASC LIMIT $limit OFFSET $offset_a")->fetchAll(PDO::FETCH_ASSOC);

// 2. İleri Tarihli Planlamalar İçin Sayfalama (Sıralama: planned_date ASC)
$yaklasan_count = $db->query("SELECT COUNT(*) FROM ($sql_core) as t WHERE planned_date > '$bugun'")->fetchColumn();
$yaklasan_pages = ceil($yaklasan_count / $limit);
$yaklasan_kutular = $db->query("SELECT * FROM ($sql_core) as t WHERE planned_date > '$bugun' ORDER BY planned_date ASC LIMIT $limit OFFSET $offset_y")->fetchAll(PDO::FETCH_ASSOC);

require_once '../header.php';

// Ortak Tablo Yazdırma Fonksiyonu
function kutuSatirlariYazdir($kutular, $bugun, $form_action) {
    if(count($kutular) == 0) {
        echo '<tr><td colspan="5" class="text-center py-5 text-muted fw-bold"><i class="bi bi-inbox fs-1 d-block mb-3 opacity-25"></i> Bu kategoride hazırlanacak kargo bulunmuyor.</td></tr>';
        return;
    }
    
    foreach($kutular as $kutu) {
        // Tarih Farkı Hesaplama
        $planlanan_zaman = strtotime($kutu['planned_date']);
        $bugun_zaman = strtotime($bugun);
        $gun_farki = ($planlanan_zaman - $bugun_zaman) / (60 * 60 * 24);
        
        $has_cancel = ($kutu['is_cancel_requested'] == 1);
        $gorsel = ($kutu['main_image'] == 'assets/img/no-image.jpg' && !empty($kutu['brand_logo'])) ? $kutu['brand_logo'] : $kutu['main_image'];
        
        $modal_id = $kutu['source_type'] . '_' . $kutu['order_id'] . '_' . ($kutu['source_type'] == 'package' ? $kutu['delivery_sequence'] : $kutu['item_id']);
        ?>
        <tr class="<?= $has_cancel ? 'pulse-cancel' : '' ?>">
            <td class="ps-4">
                <?php if($has_cancel): ?>
                    <span class="badge bg-danger px-2 py-1 mb-2 small"><i class="bi bi-slash-circle me-1"></i> İPTAL İSTENİYOR</span><br>
                <?php endif; ?>
                
                <div class="small text-muted mb-1 fw-bold text-uppercase" style="font-size: 10px;">Kargo Çıkış Tarihi</div>
                <?php if($gun_farki < 0): ?>
                    <span class="badge bg-danger fs-6 rounded-pill px-3 shadow-sm border border-danger"><i class="bi bi-calendar-event me-1"></i> <?= date('d.m.Y', $planlanan_zaman) ?></span>
                    <div class="text-danger small mt-1 fw-bold"><i class="bi bi-clock-history me-1"></i>Gecikmiş Kargo!</div>
                <?php elseif($gun_farki == 0): ?>
                    <span class="badge bg-warning text-dark fs-6 rounded-pill px-3 shadow-sm border border-warning"><i class="bi bi-calendar-event me-1"></i> <?= date('d.m.Y', $planlanan_zaman) ?></span>
                    <div class="text-warning small mt-1 fw-bold" style="color: #d39e00 !important;"><i class="bi bi-exclamation-triangle me-1"></i>Bugün Çıkmalı</div>
                <?php else: ?>
                    <span class="badge bg-primary fs-6 rounded-pill px-3 shadow-sm border border-primary"><i class="bi bi-calendar-event me-1"></i> <?= date('d.m.Y', $planlanan_zaman) ?></span>
                    <div class="text-primary small mt-1 fw-bold"><i class="bi bi-hourglass-split me-1"></i><?= $gun_farki ?> Gün Sonra</div>
                <?php endif; ?>
            </td>
            <td>
                <div class="fw-bold text-dark"><?= htmlspecialchars($kutu['user_name'].' '.$kutu['user_surname']) ?></div>
                <a href="../siparisler/detay.php?id=<?= $kutu['order_id'] ?>" class="small text-decoration-none">#<?= $kutu['order_number'] ?></a>
            </td>
            <td>
                <div class="d-flex align-items-center">
                    <img src="../../<?= htmlspecialchars($gorsel) ?>" class="rounded bg-light border shadow-sm me-3" style="width: 40px; height: 50px; object-fit: contain;">
                    <div>
                        <div class="small fw-bold text-dark text-truncate" style="max-width: 150px;"><?= htmlspecialchars($kutu['package_name']) ?></div>
                        
                        <?php if($kutu['source_type'] == 'package'): ?>
                            <span class="badge bg-secondary" style="font-size: 10px;"><?= $kutu['delivery_sequence'] ?>. Gönderim</span>
                        <?php else: ?>
                            <span class="badge bg-info text-dark border border-info" style="font-size: 10px;"><i class="bi bi-box-seam me-1"></i>Tekli Gönderim</span>
                        <?php endif; ?>

                    </div>
                </div>
            </td>
            <td class="small text-secondary lh-lg" style="font-size: 11.5px;">• <?= $kutu['exam_list'] ?></td>
            <td class="text-end pe-4">
                <?php if($has_cancel): ?>
                    <a href="../siparisler/iptaller.php" class="btn btn-danger btn-sm fw-bold rounded-pill px-3 shadow-sm">Talebi İncele</a>
                <?php else: ?>
                    <div class="btn-group shadow-sm">
                        <form action="<?= $form_action ?>" method="POST" class="d-inline">
                            <input type="hidden" name="order_id" value="<?= $kutu['order_id'] ?>">
                            <input type="hidden" name="sequence" value="<?= $kutu['delivery_sequence'] ?>">
                            <input type="hidden" name="source_type" value="<?= $kutu['source_type'] ?>">
                            <input type="hidden" name="item_id" value="<?= $kutu['item_id'] ?>">
                            <button type="submit" name="api_kargo_yap_kutu" class="btn btn-sm btn-warning fw-bold border-end" onclick="return confirm('Geliver üzerinden barkod oluşturulsun mu?')"><i class="bi bi-lightning-fill"></i> Geliver</button>
                        </form>
                        <button type="button" class="btn btn-sm btn-dark fw-bold" data-bs-toggle="modal" data-bs-target="#manuelModal<?= $modal_id ?>">Manuel Kargo</button>
                    </div>

                    <div class="modal fade" id="manuelModal<?= $modal_id ?>" tabindex="-1">
                        <div class="modal-dialog modal-sm modal-dialog-centered">
                            <form action="<?= $form_action ?>" method="POST" class="modal-content text-start shadow-lg border-0 rounded-4">
                                <div class="modal-header bg-dark text-white py-2"><h6 class="modal-title fw-bold">Manuel Kargo Girişi</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
                                <div class="modal-body p-4">
                                    <input type="hidden" name="order_id" value="<?= $kutu['order_id'] ?>">
                                    <input type="hidden" name="sequence" value="<?= $kutu['delivery_sequence'] ?>">
                                    <input type="hidden" name="source_type" value="<?= $kutu['source_type'] ?>">
                                    <input type="hidden" name="item_id" value="<?= $kutu['item_id'] ?>">
                                    <div class="mb-3">
                                        <label class="small fw-bold text-muted mb-1">Kargo Firması</label>
                                        <select name="kargo_firma" class="form-select form-select-sm border-2 fw-bold" required>
                                            <option value="Yurtiçi Kargo">Yurtiçi Kargo</option>
                                            <option value="MNG Kargo">MNG Kargo</option>
                                            <option value="Aras Kargo">Aras Kargo</option>
                                            <option value="PTT Kargo">PTT Kargo</option>
                                        </select>
                                    </div>
                                    <div class="mb-1">
                                        <label class="small fw-bold text-muted mb-1">Takip Kodu</label>
                                        <input type="text" name="tracking_code" class="form-control form-control-sm border-2 fw-bold" placeholder="Kod girin" required>
                                    </div>
                                </div>
                                <div class="modal-footer bg-light p-2"><button type="submit" name="manuel_kargo_kutu" class="btn btn-primary btn-sm w-100 fw-bold rounded-pill shadow-sm">Kargoyu Kaydet</button></div>
                            </form>
                        </div>
                    </div>
                <?php endif; ?>
            </td>
        </tr>
        <?php
    }
}
?>

<style>
    @keyframes pulse-red-bg { 0% { background-color: rgba(220, 53, 69, 0.1); } 50% { background-color: rgba(220, 53, 69, 0.25); } 100% { background-color: rgba(220, 53, 69, 0.1); } }
    .pulse-cancel { animation: pulse-red-bg 2s infinite; }
    
    #kutuTab .nav-link {
        color: #6c757d !important;
        font-weight: 700;
        margin-right: 10px;
        border: 1px solid #dee2e6;
        transition: all 0.3s ease;
        background-color: #fff;
    }
    #kutuTab .nav-link:hover:not(.active) {
        background-color: #e9ecef;
        color: #212529 !important;
    }
    #kutuTab .nav-link.active.btn-danger {
        color: #fff !important;
        background-color: #dc3545 !important;
        border-color: #dc3545 !important;
        box-shadow: 0 4px 10px rgba(220, 53, 69, 0.3);
    }
    #kutuTab .nav-link.active.btn-primary {
        color: #fff !important;
        background-color: #0d6efd !important;
        border-color: #0d6efd !important;
        box-shadow: 0 4px 10px rgba(13, 110, 253, 0.3);
    }
    .pagination .page-link { color: #212529; font-weight: bold; border-radius: 5px; margin: 0 3px; border: 1px solid #dee2e6; }
    .pagination .active .page-link { background-color: #212529; border-color: #212529; color: #fff; }
</style>

<div class="row mb-4 align-items-center text-dark">
    <div class="col-md-6">
        <h2 class="fw-bold mb-0"><i class="bi bi-boxes text-primary me-2"></i>Paket Lojistik Merkezi</h2>
        <p class="text-muted small mt-1">API destekli kutu hazırlama ve gönderim merkezi.</p>
    </div>
    <div class="col-md-6 text-md-end">
        <a href="gonderilenler.php" class="btn btn-info text-white fw-bold shadow-sm rounded-pill px-3 py-2 me-2">
            <i class="bi bi-truck me-1"></i>Gönderilenler
        </a>
        <a href="toplama-listesi.php" class="btn btn-warning fw-bold shadow-sm rounded-pill px-4 py-2">
            <i class="bi bi-clipboard2-check-fill me-2"></i>Toplama Listesi
        </a>
    </div>
</div>

<div class="row g-3 mb-4 text-dark">
    <div class="col-md-3">
        <div class="card border-0 border-bottom border-danger border-4 shadow-sm bg-white">
            <div class="card-body d-flex align-items-center">
                <div class="bg-danger bg-opacity-10 p-3 rounded-3 me-3 text-danger"><i class="bi bi-exclamation-octagon-fill fs-3"></i></div>
                <div><h6 class="text-muted small fw-bold mb-1 text-uppercase">İptal İstekleri</h6><h3 class="fw-bold mb-0"><?= $stat_iptal_talep ?></h3></div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 border-bottom border-warning border-4 shadow-sm bg-white">
            <div class="card-body d-flex align-items-center">
                <div class="bg-warning bg-opacity-10 p-3 rounded-3 me-3 text-warning"><i class="bi bi-clock-history fs-3"></i></div>
                <div><h6 class="text-muted small fw-bold mb-1 text-uppercase">Geciken</h6><h3 class="fw-bold mb-0"><?= $stat_geciken ?></h3></div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 border-bottom border-primary border-4 shadow-sm bg-white">
            <div class="card-body d-flex align-items-center">
                <div class="bg-primary bg-opacity-10 p-3 rounded-3 me-3 text-primary"><i class="bi bi-box-seam-fill fs-3"></i></div>
                <div><h6 class="text-muted small fw-bold mb-1 text-uppercase">Bugün Çıkacak</h6><h3 class="fw-bold mb-0"><?= $stat_bugun ?></h3></div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 border-bottom border-success border-4 shadow-sm bg-white">
            <div class="card-body d-flex align-items-center">
                <div class="bg-success bg-opacity-10 p-3 rounded-3 me-3 text-success"><i class="bi bi-people-fill fs-3"></i></div>
                <div><h6 class="text-muted small fw-bold mb-1 text-uppercase">Aktif Lojistik</h6><h3 class="fw-bold mb-0"><?= $stat_aktif ?></h3></div>
            </div>
        </div>
    </div>
</div>

<?= $mesaj; ?>

<ul class="nav nav-pills mb-4" id="kutuTab" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link <?= $active_tab == 'acil' ? 'active' : '' ?> btn-danger rounded-pill px-4" data-bs-toggle="pill" data-bs-target="#acil" type="button" role="tab" onclick="history.replaceState(null, null, '?tab=acil&pa=<?= $pa ?>&py=<?= $py ?>');">
            <i class="bi bi-exclamation-circle-fill me-1"></i> Acil & Bugün (<?= $acil_count ?>)
        </button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link <?= $active_tab == 'yaklasan' ? 'active' : '' ?> btn-primary rounded-pill px-4" data-bs-toggle="pill" data-bs-target="#yaklasan" type="button" role="tab" onclick="history.replaceState(null, null, '?tab=yaklasan&pa=<?= $pa ?>&py=<?= $py ?>');">
            <i class="bi bi-calendar-range-fill me-1"></i> Yaklaşan Planlamalar (<?= $yaklasan_count ?>)
        </button>
    </li>
</ul>

<div class="card shadow-sm border-0 rounded-4 mb-5 overflow-hidden">
    <div class="card-body p-0">
        <div class="tab-content">
            
            <div class="tab-pane fade <?= $active_tab == 'acil' ? 'show active' : '' ?>" id="acil">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0 text-dark">
                        <thead class="table-light text-muted small">
                            <tr>
                                <th class="ps-4 py-3">TARİH / DURUM</th>
                                <th>MÜŞTERİ / SİPARİŞ</th>
                                <th>PAKET / SIRA</th>
                                <th>İÇERİK</th>
                                <th class="text-end pe-4">LOJİSTİK AKSİYON</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php kutuSatirlariYazdir($acil_kutular, $bugun, $form_action); ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if ($acil_pages > 1): ?>
                <div class="p-3 bg-light border-top d-flex justify-content-center">
                    <nav>
                        <ul class="pagination pagination-sm m-0">
                            <?php for($i=1; $i<=$acil_pages; $i++): ?>
                                <li class="page-item <?= ($i == $pa) ? 'active' : '' ?>">
                                    <a class="page-link shadow-sm" href="?tab=acil&pa=<?= $i ?>&py=<?= $py ?>"><?= $i ?></a>
                                </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                </div>
                <?php endif; ?>
            </div>

            <div class="tab-pane fade <?= $active_tab == 'yaklasan' ? 'show active' : '' ?>" id="yaklasan">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0 text-dark">
                        <thead class="table-light text-muted small">
                            <tr>
                                <th class="ps-4 py-3">TARİH / DURUM</th>
                                <th>MÜŞTERİ / SİPARİŞ</th>
                                <th>PAKET / SIRA</th>
                                <th>İÇERİK</th>
                                <th class="text-end pe-4">LOJİSTİK AKSİYON</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php kutuSatirlariYazdir($yaklasan_kutular, $bugun, $form_action); ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($yaklasan_pages > 1): ?>
                <div class="p-3 bg-light border-top d-flex justify-content-center">
                    <nav>
                        <ul class="pagination pagination-sm m-0">
                            <?php for($i=1; $i<=$yaklasan_pages; $i++): ?>
                                <li class="page-item <?= ($i == $py) ? 'active' : '' ?>">
                                    <a class="page-link shadow-sm" href="?tab=yaklasan&pa=<?= $pa ?>&py=<?= $i ?>"><?= $i ?></a>
                                </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                </div>
                <?php endif; ?>
            </div>

        </div>
    </div>
</div>

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