<?php
/**
 * Admin Sipariş Detay, Kutu Lojistiği, Fatura ve İptal/İade Yönetimi
 * Konum: /magaza/admin/siparisler/detay.php
 */

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

// Proje ana dizinini belirle
$kok_dizin = "/magaza/";

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

adminCheck();

$mesaj = '';

// 1. URL'den Sipariş ID Kontrolü
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: index.php");
    exit;
}
$order_id = (int)$_GET['id'];

// --- YENİ: KARGO FİRMALARINI VERİTABANINDAN ÇEK (Dinamik Selectler İçin) ---
$kargo_firmalari = $db->query("SELECT name FROM shipping_companies WHERE status = 1 ORDER BY name ASC")->fetchAll(PDO::FETCH_COLUMN);

/**
 * --- İPTAL VE İADE TALEBİ KONTROLÜ (Bannerlar için) ---
 */
$iptal_sorgu = $db->prepare("SELECT * FROM order_returns WHERE order_id = ? AND request_type = 'cancellation' AND status = 'pending'");
$iptal_sorgu->execute([$order_id]);
$bekleyen_iptal = $iptal_sorgu->fetch();

$iade_sorgu = $db->prepare("SELECT * FROM order_returns WHERE order_id = ? AND request_type = 'return' AND status != 'completed'");
$iade_sorgu->execute([$order_id]);
$aktif_iade = $iade_sorgu->fetch();

// Bildirimler için Sipariş Sahibinin ID'sini ve Sipariş Numarasını peşinen çekelim
$u_stmt = $db->prepare("SELECT user_id, order_number FROM orders WHERE id = ?");
$u_stmt->execute([$order_id]);
$order_base_info = $u_stmt->fetch();
$current_user_id = $order_base_info['user_id'] ?? 0;
$current_order_no = $order_base_info['order_number'] ?? '';


/**
 * --- İŞLEM -1: E-FATURA YÜKLEME ---
 */
if (isset($_POST['upload_invoice']) && isset($_FILES['invoice_file'])) {
    $dosya = $_FILES['invoice_file'];
    $uzanti = strtolower(pathinfo($dosya['name'], PATHINFO_EXTENSION));
    
    if ($uzanti !== 'pdf') {
        $mesaj .= "<div class='alert alert-danger shadow-sm'>Hata: Sadece PDF formatında fatura yükleyebilirsiniz.</div>";
    } elseif ($dosya['size'] > 5 * 1024 * 1024) { 
        $mesaj .= "<div class='alert alert-danger shadow-sm'>Hata: Fatura dosya boyutu 5MB'dan büyük olamaz.</div>";
    } else {
        $yukleme_dizini = "../../uploads/invoices/";
        if (!is_dir($yukleme_dizini)) mkdir($yukleme_dizini, 0777, true);
        
        $yeni_ad = "fatura_" . $order_id . "_" . time() . ".pdf";
        $hedef_yol = $yukleme_dizini . $yeni_ad;

        if (move_uploaded_file($dosya['tmp_name'], $hedef_yol)) {
            $db_yolu = "uploads/invoices/" . $yeni_ad;
            $db->prepare("UPDATE orders SET invoice_path = ? WHERE id = ?")->execute([$db_yolu, $order_id]);
            $mesaj .= "<div class='alert alert-success shadow-sm'><i class='bi bi-file-earmark-check me-2'></i> Fatura başarıyla sisteme yüklendi.</div>";
            
            // BİLDİRİM TETİKLEYİCİ: E-Fatura Yüklendi
            siteBildirimGonder($current_user_id, "E-Faturanız Hazır", "#{$current_order_no} numaralı siparişinize ait e-fatura sisteme yüklendi.", "siparis-detay.php?id={$order_id}", "bi-receipt");
        }
    }
}

if (isset($_POST['delete_invoice'])) {
    $s_fatura = $db->prepare("SELECT invoice_path FROM orders WHERE id = ?");
    $s_fatura->execute([$order_id]);
    $eski_fatura = $s_fatura->fetchColumn();

    if ($eski_fatura && file_exists("../../" . $eski_fatura)) {
        unlink("../../" . $eski_fatura);
    }
    
    $db->prepare("UPDATE orders SET invoice_path = NULL WHERE id = ?")->execute([$order_id]);
    $mesaj .= "<div class='alert alert-secondary shadow-sm'><i class='bi bi-trash me-2'></i> Mevcut fatura silindi.</div>";
}

/**
 * --- İŞLEM 0: ÖDEME VE DEKONT ONAYI ---
 */
if (isset($_POST['approve_payment'])) {
    try {
        $db->beginTransaction();
        $db->prepare("UPDATE payments SET status = 'approved' WHERE order_id = ?")->execute([$order_id]);
        $db->prepare("UPDATE orders SET status = 'processing' WHERE id = ?")->execute([$order_id]);
        $db->commit();
        $mesaj .= "<div class='alert alert-success shadow-sm'><i class='bi bi-check-all me-2'></i> Ödeme onaylandı ve sipariş hazırlık aşamasına alındı.</div>";
        
        // BİLDİRİM TETİKLEYİCİ: Dekont Onaylandı
        siteBildirimGonder($current_user_id, "Ödeme Onaylandı", "#{$current_order_no} numaralı siparişinize ait havale/EFT ödemesi onaylandı. Siparişiniz hazırlanıyor.", "siparis-detay.php?id={$order_id}", "bi-wallet2");

        $_POST['durum_guncelle'] = true;
        $_POST['order_status'] = 'processing';
    } catch (Exception $e) {
        $db->rollBack();
        $mesaj .= "<div class='alert alert-danger'>Finansal İşlem Hatası: " . $e->getMessage() . "</div>";
    }
}

/**
 * --- İŞLEM 1: ANA SİPARİŞ DURUMU GÜNCELLEME ---
 */
if (isset($_POST['durum_guncelle'])) {
    $yeni_durum = $_POST['order_status'];
    $db->prepare("UPDATE orders SET status = ? WHERE id = ?")->execute([$yeni_durum, $order_id]);

    if ($yeni_durum == 'processing') {
        $st_items = $db->prepare("SELECT oi.product_id, p.type, p.duration_days FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = ?");
        $st_items->execute([$order_id]);
        $order_items_list = $st_items->fetchAll();

        foreach ($order_items_list as $item) {
            if ($item['type'] == 'subscription') {
                $check_sub = $db->prepare("SELECT id FROM subscriptions WHERE user_id = ? AND product_id = ? AND status = 'active'");
                $check_sub->execute([$current_user_id, $item['product_id']]);

                if ($check_sub->rowCount() == 0) {
                    $start_date = date('Y-m-d');
                    $days = $item['duration_days'] ?: 30;
                    $end_date = date('Y-m-d', strtotime("+$days days"));

                    $ins_sub = $db->prepare("INSERT INTO subscriptions (user_id, package_id, product_id, status, start_date, end_date) VALUES (?, 0, ?, 'active', ?, ?)");
                    $ins_sub->execute([$current_user_id, $item['product_id'], $start_date, $end_date]);
                    $new_sub_id = $db->lastInsertId();

                    createSubscriptionSchedule($db, $new_sub_id);
                }
            }
        }
    }
    
    $durum_isimleri = [
        'pending' => 'Onay Bekliyor',
        'processing' => 'İşlemde / Parçalı Gönderim Sürecinde',
        'shipped' => 'Tüm Lojistik İşlemleri Tamamlandı',
        'delivered' => 'Tüm Sipariş Teslim Edildi',
        'cancelled' => 'İptal Edildi'
    ];
    $durum_ismi_tr = $durum_isimleri[$yeni_durum] ?? $yeni_durum;

    // BİLDİRİM TETİKLEYİCİ: Ana Sipariş Durumu
    $icon_class = 'bi-info-circle';
    if($yeni_durum == 'shipped') $icon_class = 'bi-truck text-primary';
    elseif($yeni_durum == 'delivered') $icon_class = 'bi-check-circle text-success';
    elseif($yeni_durum == 'cancelled') $icon_class = 'bi-x-circle text-danger';
    elseif($yeni_durum == 'processing') $icon_class = 'bi-box-seam text-info';

    if($yeni_durum != 'pending') { // Onay bekliyor bildirimi atmaya gerek yok, zaten ilk oluştuğunda pending'tir.
        siteBildirimGonder($current_user_id, "Sipariş Durumu Güncellendi", "#{$current_order_no} numaralı siparişinizin durumu '{$durum_ismi_tr}' olarak güncellendi.", "siparis-detay.php?id={$order_id}", $icon_class);
    }

    $mesaj .= "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Sipariş durumu <b>{$durum_ismi_tr}</b> yapıldı.</div>";
}

/**
 * --- İŞLEM 2: KUTU BAZLI KARGO ONAYI (ÖZEL PAKETLER İÇİN) ---
 */
if (isset($_POST['kutu_kargola'])) {
    $seq = (int)$_POST['sequence'];
    $firma = trim($_POST['kutu_firma']);
    $takip = trim($_POST['kutu_takip']);

    if (!empty($firma) && !empty($takip)) {
        $db->prepare("UPDATE order_deliveries SET status = 'shipped', shipping_company = ?, tracking_code = ? WHERE order_id = ? AND delivery_sequence = ?")
           ->execute([$firma, $takip, $order_id, $seq]);
        
        // BİLDİRİM TETİKLEYİCİ: Paket Kutusu Kargolandı
        siteBildirimGonder($current_user_id, "Paketiniz Kargoya Verildi", "#{$current_order_no} numaralı siparişinize ait {$seq}. Gönderim Kutusu {$firma} aracılığıyla kargoya verildi. Takip No: {$takip}", "siparis-detay.php?id={$order_id}", "bi-truck text-primary");

        $mesaj .= "<div class='alert alert-success shadow-sm'><i class='bi bi-box-seam-fill me-2'></i> <b>{$seq}. Gönderim Kutusu</b> başarıyla kargolandı olarak işaretlendi.</div>";
    }
}

/**
 * --- İŞLEM 3: ÜRÜN BAZLI KARGO GİRİŞİ (STANDART ÜRÜNLER İÇİN YENİ) ---
 */
if (isset($_POST['standart_kutu_kargola'])) {
    $oi_id = (int)$_POST['order_item_id'];
    $firma = trim($_POST['kutu_firma']);
    $takip = trim($_POST['kutu_takip']);

    if (!empty($firma) && !empty($takip)) {
        try {
            $db->prepare("UPDATE order_items SET shipping_status = 'shipped', shipping_company = ?, tracking_number = ? WHERE id = ?")
               ->execute([$firma, $takip, $oi_id]);
            
            $db->prepare("UPDATE orders SET is_manual_shipping = 1 WHERE id = ?")->execute([$order_id]);

            // Ürünün adını bulalım bildirime yazmak için
            $urun_ad_stmt = $db->prepare("SELECT p.name FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.id = ?");
            $urun_ad_stmt->execute([$oi_id]);
            $urun_adi = $urun_ad_stmt->fetchColumn() ?: 'Ürününüz';

            // BİLDİRİM TETİKLEYİCİ: Standart Ürün Kargolandı
            siteBildirimGonder($current_user_id, "Ürününüz Kargoya Verildi", "#{$current_order_no} numaralı siparişinizdeki '{$urun_adi}' {$firma} firmasına teslim edildi. Takip No: {$takip}", "siparis-detay.php?id={$order_id}", "bi-truck text-primary");

            $mesaj .= "<div class='alert alert-success shadow-sm'><i class='bi bi-truck me-2'></i> <b>Standart Ürün</b> başarıyla kargolandı.</div>";
        } catch (PDOException $e) {
            $mesaj .= "<div class='alert alert-danger shadow-sm'><b>Veritabanı Hatası:</b> Lütfen order_items tablosuna shipping_company, tracking_number ve shipping_status sütunlarını eklediğinizden emin olun!</div>";
        }
    }
}

// --- VERİLERİ ÇEK ---
$stmt = $db->prepare("
    SELECT o.*, o.invoice_path, 
           u.name, u.surname, u.email, u.phone,
           s_addr.full_address as s_full_address, s_addr.city as s_city, s_addr.district as s_district,
           b_addr.title as b_title, b_addr.full_address as b_full_address, b_addr.city as b_city, b_addr.district as b_district,
           p.payment_method, p.status as payment_status, p.receipt_file_path
    FROM orders o 
    JOIN users u ON o.user_id = u.id 
    LEFT JOIN user_addresses s_addr ON o.shipping_address_id = s_addr.id 
    LEFT JOIN user_addresses b_addr ON o.billing_address_id = b_addr.id 
    JOIN payments p ON o.id = p.order_id
    WHERE o.id = ?
");
$stmt->execute([$order_id]);
$order = $stmt->fetch();

if (!$order) die("<div class='alert alert-danger m-5 text-center fw-bold shadow'>Sipariş sistemde bulunamadı!</div>");

// Sipariş Kalemlerini Çek (GÜNCELLEME: exam_publication_date, sku ve exam_type SÜTUNLARI EKLENDİ)
try {
    $items_stmt = $db->prepare("SELECT oi.*, p.name as product_name, p.type, p.exam_publication_date, p.sku, p.exam_type FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = ?");
    $items_stmt->execute([$order_id]);
    $items = $items_stmt->fetchAll();
} catch (PDOException $e) {
    die("<div class='alert alert-danger m-5 p-4 text-center fw-bold shadow'><h4>Veritabanı Eksikliği</h4>Lütfen Adım 1'deki SQL sorgusunu phpMyAdmin'de çalıştırarak `order_items` tablosunu güncelleyin.</div>");
}

// Ürünleri Standart ve Paket olarak ikiye ayıralım
$standart_urunler = [];
$paket_urunler = [];

foreach($items as $item) {
    if($item['type'] == 'exam_package') {
        $paket_urunler[] = $item;
    } else if($item['type'] != 'digital') { // Sadece kargo gerektirenler standart lojistiğe girer
        $standart_urunler[] = $item;
    }
}

// Kutu Bazlı Lojistik Verilerini Çek
$kutu_planlari = [];
$gonderilmemis_kutu_var_mi = false; // Akıllı uyarı sistemi için

if(count($paket_urunler) > 0) {
    $del_stmt = $db->prepare("
        SELECT od.*, p.name as exam_name, pkg.name as package_name
        FROM order_deliveries od
        JOIN products p ON od.exam_id = p.id
        JOIN products pkg ON od.package_id = pkg.id
        WHERE od.order_id = ?
        ORDER BY od.delivery_sequence ASC
    ");
    $del_stmt->execute([$order_id]);
    $raw_deliveries = $del_stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach($raw_deliveries as $d) {
        $seq = $d['delivery_sequence'];
        if(!isset($kutu_planlari[$seq])) {
            $kutu_planlari[$seq] = [
                'planned_date' => $d['planned_date'],
                'status' => $d['status'],
                'tracking_code' => $d['tracking_code'],
                'shipping_company' => $d['shipping_company'],
                'package_name' => $d['package_name'],
                'exams' => []
            ];
            
            if($d['status'] != 'shipped' && $d['status'] != 'delivered') {
                $gonderilmemis_kutu_var_mi = true;
            }
        }
        $kutu_planlari[$seq]['exams'][] = $d['exam_name'];
    }
}

/**
 * GÜNCELLEME: Admin Standart Ürün Kargo Tarihi Hesaplama Fonksiyonu
 */
function getAdminItemKargoTarihi($urun) {
    if ($urun['type'] == 'single_exam' && !empty($urun['exam_publication_date'])) {
        $bugun = new DateTime('midnight');
        $d = DateTime::createFromFormat('d.m.Y', $urun['exam_publication_date']);
        if ($d) {
            $d->setTime(0, 0, 0);
            if ($d < $bugun) {
                return '<div class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 px-2 py-2 mb-2 w-100" style="font-size:0.75rem;"><i class="bi bi-box-seam me-1"></i>Hemen Kargolanmalı</div>';
            } else {
                $d->modify('next tuesday');
                return '<div class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 px-2 py-2 mb-2 w-100" style="font-size:0.75rem;"><i class="bi bi-calendar-event me-1"></i>Planlı Kargo: ' . $d->format('d.m.Y') . ' (Salı)</div>';
            }
        }
    }
    return '<div class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 px-2 py-2 mb-2 w-100" style="font-size:0.75rem;"><i class="bi bi-box-seam me-1"></i>Hemen Kargolanmalı</div>';
}

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

<style>
    .address-box { background: #f8f9fa; border-radius: 12px; padding: 15px; border: 1px solid #eee; height: 100%; }
    .box-card { border-left: 4px solid #0d6efd; transition: 0.3s; }
    .box-card:hover { box-shadow: 0 10px 15px rgba(0,0,0,0.1); }
    .std-card { border-left: 4px solid #198754; transition: 0.3s; }
    .std-card:hover { box-shadow: 0 10px 15px rgba(0,0,0,0.1); }
    
    @keyframes pulse-red {
        0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7); }
        70% { transform: scale(1.02); box-shadow: 0 0 0 10px rgba(220, 53, 69, 0); }
        100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0); }
    }
    .pulse-warning { animation: pulse-red 2s infinite; }
</style>

<div class="row mb-4 align-items-center text-dark">
    <div class="col-md-6">
        <h2 class="fw-bold mb-0">
            <a href="index.php" class="btn btn-sm btn-outline-secondary me-3 shadow-sm border-2"><i class="bi bi-arrow-left"></i> Geri</a>
            Sipariş: <span class="text-primary">#<?= htmlspecialchars($order['order_number']) ?></span>
        </h2>
    </div>
    <div class="col-md-6 text-md-end mt-3 mt-md-0">
        <a href="../musteri/detay.php?id=<?= $order['user_id'] ?>" class="btn btn-dark fw-bold shadow-sm px-4">
            <i class="bi bi-person-lines-fill me-2"></i> Müşteri Kartı
        </a>
    </div>
</div>

<?= $mesaj; ?>

<?php if ($order['is_cancel_requested'] == 1 && $order['status'] != 'cancelled'): ?>
<div class="alert alert-danger shadow border-0 rounded-4 p-4 mb-4 pulse-warning">
    <div class="row align-items-center">
        <div class="col-md-1 text-center">
            <i class="bi bi-exclamation-triangle-fill display-4"></i>
        </div>
        <div class="col-md-8">
            <h4 class="fw-bold mb-1">DİKKAT: İptal Talebi Alındı!</h4>
            <p class="mb-0">Müşteri siparişi henüz kargolanmadığı için iptal etmek istiyor. Lütfen depoya kargolanıp kargolanmadığını teyit etmeden işlem yapmayın.</p>
        </div>
        <div class="col-md-3 text-md-end mt-3 mt-md-0">
            <a href="iptaller.php" class="btn btn-light btn-lg fw-bold rounded-pill px-4 shadow-sm text-danger">Talebi İncele</a>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if ($aktif_iade): ?>
<div class="alert alert-info shadow-sm border-0 rounded-4 p-3 mb-4">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <i class="bi bi-arrow-counterclockwise fs-4 me-2"></i>
            <span class="fw-bold">Bu sipariş için aktif bir <b>İADE SÜRECİ</b> (Kargo Sonrası) bulunmaktadır.</span>
        </div>
        <a href="iadeler.php" class="btn btn-info text-white btn-sm fw-bold rounded-pill px-3 shadow-sm">İadeleri Yönet</a>
    </div>
</div>
<?php endif; ?>

<div class="row text-dark">
    <div class="col-lg-8">
        
        <div class="card shadow-sm border-0 mb-4 overflow-hidden rounded-4">
            <div class="card-header bg-white py-3 border-bottom">
                <h6 class="mb-0 fw-bold text-uppercase"><i class="bi bi-geo-alt-fill text-primary me-2"></i>Müşteri ve Adres Detayları</h6>
            </div>
            <div class="card-body">
                <div class="row g-4">
                    <div class="col-12 border-bottom pb-3">
                        <div class="row">
                            <div class="col-md-6">
                                <small class="text-muted d-block fw-bold mb-1 text-uppercase">MÜŞTERİ</small>
                                <div class="fw-bold fs-5"><?= htmlspecialchars($order['name'].' '.$order['surname']) ?></div>
                            </div>
                            <div class="col-md-6 text-md-end">
                                <span class="badge bg-light text-dark border p-2 me-2"><i class="bi bi-envelope me-1"></i><?= $order['email'] ?></span>
                                <span class="badge bg-light text-dark border p-2"><i class="bi bi-telephone me-1"></i><?= $order['phone'] ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="address-box">
                            <small class="text-muted d-block fw-bold mb-2 text-uppercase text-success"><i class="bi bi-truck me-1"></i> TESLİMAT ADRESİ</small>
                            <?php if($order['shipping_address_id']): ?>
                                <div class="small lh-sm mb-2 fw-bold text-dark"><?= nl2br(htmlspecialchars($order['s_full_address'])) ?></div>
                                <div class="mt-2"><span class="badge bg-white text-primary border border-primary"><?= htmlspecialchars($order['s_district'] . ' / ' . $order['s_city']) ?></span></div>
                            <?php else: ?>
                                <div class="text-danger small fw-bold"><i class="bi bi-exclamation-triangle"></i> Fiziksel adres kaydı bulunmuyor.</div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="address-box">
                            <small class="text-muted d-block fw-bold mb-2 text-uppercase text-warning"><i class="bi bi-receipt me-1"></i> FATURA ADRESİ</small>
                            <?php if($order['billing_address_id']): ?>
                                <div class="fw-bold small mb-1 text-dark"><?= htmlspecialchars($order['b_title']) ?></div>
                                <div class="small lh-sm text-muted mb-2"><?= nl2br(htmlspecialchars($order['b_full_address'])) ?></div>
                                <div class="mt-2"><span class="badge bg-white text-dark border"><?= htmlspecialchars($order['b_district'] . ' / ' . $order['b_city']) ?></span></div>
                            <?php else: ?>
                                <div class="text-muted small italic">Teslimat adresiyle aynı bilgiler kullanılacak.</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if(count($standart_urunler) > 0): ?>
        <div class="card shadow-sm border-0 mb-4 rounded-4 overflow-hidden <?= ($order['is_cancel_requested']) ? 'opacity-50' : '' ?>">
            <div class="card-header bg-success text-white py-3 d-flex justify-content-between align-items-center">
                <h6 class="mb-0 fw-bold text-uppercase"><i class="bi bi-box-seam me-2"></i>Standart Ürünler Lojistiği</h6>
                <span class="badge bg-white text-success rounded-pill"><?= count($standart_urunler) ?> Ürün</span>
            </div>
            <div class="card-body p-4 bg-light">
                <div class="row row-cols-1 row-cols-md-2 g-3">
                    <?php foreach($standart_urunler as $s_urun): 
                        // Veritabanından gelen veriler
                        $s_status = isset($s_urun['shipping_status']) ? $s_urun['shipping_status'] : 'pending';
                        $s_company = isset($s_urun['shipping_company']) ? $s_urun['shipping_company'] : '';
                        $s_tracking = isset($s_urun['tracking_number']) ? $s_urun['tracking_number'] : '';
                    ?>
                    <div class="col">
                        <div class="card std-card shadow-sm border-0 h-100">
                            <div class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                                <div class="fw-bold text-dark text-truncate" title="<?= htmlspecialchars($s_urun['product_name']) ?>" style="max-width: 70%;">
                                    <i class="bi bi-check2-square me-1 text-success"></i> <?= htmlspecialchars($s_urun['product_name']) ?>
                                </div>
                                <div>
                                    <?php if($s_status == 'shipped'): ?>
                                        <span class="badge bg-success"><i class="bi bi-check-all"></i> Kargolandı</span>
                                    <?php else: ?>
                                        <span class="badge bg-warning text-dark"><i class="bi bi-hourglass-split"></i> Bekliyor</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="small text-muted mb-2 pb-2 border-bottom">
                                    <div class="mb-1" style="font-size:0.75rem;">
                                        <strong>SKU:</strong> <?= !empty($s_urun['sku']) ? htmlspecialchars($s_urun['sku']) : '-' ?> | 
                                        <strong>Tür:</strong> <?= !empty($s_urun['exam_type']) ? htmlspecialchars($s_urun['exam_type']) : '-' ?> | 
                                        <strong>Yayın Tarihi:</strong> <?= !empty($s_urun['exam_publication_date']) ? htmlspecialchars($s_urun['exam_publication_date']) : '-' ?>
                                    </div>
                                    Miktar: <strong class="text-dark"><?= $s_urun['quantity'] ?> Adet</strong>
                                </div>
                                
                                <?php if($s_status == 'pending'): ?>
                                    <?= getAdminItemKargoTarihi($s_urun) ?>
                                    
                                    <form action="" method="POST" class="bg-light p-2 rounded border mt-2">
                                        <input type="hidden" name="order_item_id" value="<?= $s_urun['id'] ?>">
                                        <select name="kutu_firma" class="form-select form-select-sm mb-2 border-2" required <?= $order['is_cancel_requested'] ? 'disabled' : '' ?>>
                                            <option value="">Kargo Firması Seçin</option>
                                            <?php foreach($kargo_firmalari as $f): ?>
                                                <option value="<?= htmlspecialchars($f) ?>"><?= htmlspecialchars($f) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <input type="text" name="kutu_takip" class="form-control form-control-sm mb-2 border-2" placeholder="Takip Kodu Girin" required <?= $order['is_cancel_requested'] ? 'disabled' : '' ?>>
                                        <button type="submit" name="standart_kutu_kargola" class="btn btn-sm btn-success w-100 fw-bold" <?= $order['is_cancel_requested'] ? 'disabled' : '' ?>>Kargoya Ver</button>
                                    </form>
                                <?php else: ?>
                                    <div class="bg-success bg-opacity-10 p-2 rounded border border-success border-opacity-25 text-center mt-2">
                                        <span class="d-block fw-bold text-dark mb-1" style="font-size: 0.8rem;"><?= htmlspecialchars($s_company) ?></span>
                                        <a href="<?= getKargoTakipLink($s_company, $s_tracking) ?>" target="_blank" class="badge bg-white text-primary border user-select-all fs-6 text-decoration-none" title="Kargoyu İzle">
                                            <?= htmlspecialchars($s_tracking) ?> <i class="bi bi-box-arrow-up-right ms-1"></i>
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="alert alert-success bg-opacity-10 border-success border-opacity-25 p-2 mt-3 mb-0 small">
                    <i class="bi bi-info-circle-fill text-success me-1"></i> Eğer bu ürünleri <b>aynı poşete (kargoya)</b> koyacaksanız, hepsi için <b>aynı takip kodunu</b> girebilirsiniz.
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (count($kutu_planlari) > 0): ?>
        <div class="card shadow border-0 mb-4 rounded-4 bg-light border-primary border-opacity-25 <?= ($order['is_cancel_requested']) ? 'opacity-50' : '' ?>">
            <div class="card-header bg-primary text-white py-3 border-bottom-0 d-flex justify-content-between align-items-center">
                <h6 class="mb-0 fw-bold text-uppercase"><i class="bi bi-calendar3 me-2"></i>Paket Lojistiği Planı</h6>
                <span class="badge bg-white text-primary rounded-pill"><?= count($kutu_planlari) ?> Kutu Planlandı</span>
            </div>
            <div class="card-body p-4">
                <?php if($order['is_cancel_requested']): ?>
                    <div class="alert alert-danger fw-bold text-center"><i class="bi bi-slash-circle me-2"></i> İPTAL TALEBİ NEDENİYLE KARGOLAMA DURDURULDU</div>
                <?php endif; ?>

                <?php foreach($kutu_planlari as $seq => $kutu): ?>
                    <div class="card box-card mb-4 shadow-sm border-0">
                        <div class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                            <div class="fw-bold fs-5 text-dark"><i class="bi bi-box-seam me-2 text-primary"></i> <?= $seq ?>. Gönderim Kutusu</div>
                            <div>
                                <?php if($kutu['status'] == 'shipped'): ?>
                                    <span class="badge bg-success px-3 py-2"><i class="bi bi-check-all me-1"></i> Kargolandı</span>
                                <?php else: ?>
                                    <span class="badge bg-warning text-dark px-3 py-2"><i class="bi bi-hourglass-split me-1"></i> Bekliyor</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="card-body bg-white row">
                            <div class="col-md-6 border-end">
                                <span class="d-block small text-muted fw-bold mb-2 text-uppercase">Kutunun İçine Konulacaklar:</span>
                                <ul class="list-group list-group-flush small mb-0">
                                    <?php foreach($kutu['exams'] as $exam_name): ?>
                                        <li class="list-group-item px-0 py-1 border-0 text-dark"><i class="bi bi-dot text-primary fs-5"></i> <?= htmlspecialchars($exam_name) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                            <div class="col-md-6 ps-md-4">
                                <span class="d-block small text-muted fw-bold mb-2 text-uppercase">Kargo Bilgisi:</span>
                                <div class="d-flex align-items-center mb-3 text-dark">
                                    <i class="bi bi-calendar-event fs-4 text-warning me-2"></i> 
                                    <div>
                                        <small class="d-block text-muted" style="font-size:0.7rem;">Kargolanması Gereken Tarih</small>
                                        <span class="fw-bold"><?= $kutu['planned_date'] ? date('d.m.Y', strtotime($kutu['planned_date'])) : 'Tarih Yok' ?></span>
                                    </div>
                                </div>
                                
                                <?php if($kutu['status'] == 'pending'): ?>
                                    <form action="" method="POST" class="bg-light p-2 rounded border">
                                        <input type="hidden" name="sequence" value="<?= $seq ?>">
                                        <select name="kutu_firma" class="form-select form-select-sm mb-2 border-2" required <?= $order['is_cancel_requested'] ? 'disabled' : '' ?>>
                                            <option value="">Kargo Firması Seçin</option>
                                            <?php foreach($kargo_firmalari as $f): ?>
                                                <option value="<?= htmlspecialchars($f) ?>"><?= htmlspecialchars($f) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <input type="text" name="kutu_takip" class="form-control form-control-sm mb-2 border-2" placeholder="Takip Kodu Girin" required <?= $order['is_cancel_requested'] ? 'disabled' : '' ?>>
                                        <button type="submit" name="kutu_kargola" class="btn btn-sm btn-primary w-100 fw-bold" <?= $order['is_cancel_requested'] ? 'disabled' : '' ?>>Bu Paketi Kargola</button>
                                    </form>
                                <?php else: ?>
                                    <div class="bg-primary bg-opacity-10 p-3 rounded border border-primary border-opacity-25 text-center">
                                        <span class="d-block fw-bold text-dark mb-1"><?= htmlspecialchars($kutu['shipping_company']) ?></span>
                                        <a href="<?= getKargoTakipLink($kutu['shipping_company'], $kutu['tracking_code']) ?>" target="_blank" class="badge bg-white text-primary border user-select-all fs-6 text-decoration-none" title="Kargoyu İzle">
                                            <?= htmlspecialchars($kutu['tracking_code']) ?> <i class="bi bi-box-arrow-up-right ms-1"></i>
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="card shadow-sm border-0 mb-4 rounded-4">
            <div class="card-header bg-white py-3 border-bottom">
                <h6 class="mb-0 fw-bold text-uppercase"><i class="bi bi-cart-check-fill text-dark me-2"></i>Satın Alınan Ürünler (Fatura Kalemleri)</h6>
            </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">Ürün Adı</th>
                                <th class="text-center">Miktar</th>
                                <th class="text-end">Birim Fiyat</th>
                                <th class="text-end pe-4">Toplam</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($items as $item): ?>
                            <tr>
                                <td class="ps-4 fw-bold text-primary">
                                    <?= htmlspecialchars($item['product_name']) ?>
                                    <?php if($item['type'] == 'exam_package'): ?>
                                        <br><span class="badge bg-warning text-dark" style="font-size:0.6rem;">Özel Paket</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center"><span class="badge bg-secondary px-3"><?= $item['quantity'] ?> Adet</span></td>
                                <td class="text-end text-muted small"><?= formatPrice($item['unit_price']) ?></td>
                                <td class="text-end pe-4 fw-bold text-dark"><?= formatPrice($item['unit_price'] * $item['quantity']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot class="table-light border-top">
                            <?php if($order['shipping_amount'] > 0): ?>
                            <tr><td colspan="3" class="text-end text-muted small py-1">Kargo Ücreti:</td><td class="text-end pe-4 text-muted small py-1">+ <?= formatPrice($order['shipping_amount']) ?></td></tr>
                            <?php endif; ?>
                            <tr>
                                <td colspan="3" class="text-end fw-bold py-3 text-uppercase">Ödenen Toplam:</td>
                                <td class="text-end pe-4 fw-bold text-success fs-5 py-3"><?= formatPrice($order['total_amount']) ?></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        
        <div class="card shadow-sm border-0 rounded-4 mb-4 border-info">
            <div class="card-header bg-info text-white py-3">
                <h6 class="mb-0 fw-bold text-uppercase"><i class="bi bi-file-earmark-pdf-fill me-2"></i>Fatura Yönetimi</h6>
            </div>
            <div class="card-body p-4">
                <?php if($order['invoice_path'] && file_exists("../../" . $order['invoice_path'])): ?>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <a href="<?= $kok_dizin ?><?= $order['invoice_path'] ?>" target="_blank" class="btn btn-outline-info fw-bold w-75 me-2">
                            <i class="bi bi-eye"></i> Faturayı Görüntüle
                        </a>
                        <form action="" method="POST" class="w-25">
                            <button type="submit" name="delete_invoice" class="btn btn-danger w-100" title="Faturayı Sil" onclick="return confirm('Silmek istediğinize emin misiniz?')"><i class="bi bi-trash"></i></button>
                        </form>
                    </div>
                <?php endif; ?>
                <form action="" method="POST" enctype="multipart/form-data">
                    <label class="form-label small fw-bold text-muted mb-2">YENİ FATURA (PDF) YÜKLE</label>
                    <input type="file" name="invoice_file" class="form-control mb-3 border-2" accept=".pdf" required>
                    <button type="submit" name="upload_invoice" class="btn btn-info w-100 fw-bold text-white shadow-sm py-2"><i class="bi bi-cloud-arrow-up me-1"></i> FATURAYI İŞLE</button>
                </form>
            </div>
        </div>

        <div class="card shadow-sm border-0 rounded-4 mb-4">
            <div class="card-header bg-white py-3 border-bottom">
                <h6 class="mb-0 fw-bold text-uppercase"><i class="bi bi-cash-stack text-success me-2"></i>Ödeme Kontrolü</h6>
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between mb-2">
                    <span class="small fw-bold text-muted">Yöntem:</span>
                    <span class="small fw-bold text-dark"><?= $order['payment_method'] == 'bank_transfer' ? 'Havale/EFT' : 'Kredi Kartı' ?></span>
                </div>
                <div class="d-flex justify-content-between mb-3">
                    <span class="small fw-bold text-muted">Durum:</span>
                    <?php if($order['payment_status'] == 'pending'): ?>
                        <span class="badge bg-warning text-dark rounded-pill px-3">Onay Bekliyor</span>
                    <?php else: ?>
                        <span class="badge bg-success rounded-pill px-3">Ödeme Onaylı</span>
                    <?php endif; ?>
                </div>

                <?php if($order['payment_method'] == 'bank_transfer'): ?>
                    <div class="bg-light p-3 rounded-3 border mb-3">
                        <small class="fw-bold d-block mb-2 text-primary text-uppercase">Dekont Dosyası</small>
                        <?php if($order['receipt_file_path']): ?>
                            <a href="<?= $kok_dizin ?><?= $order['receipt_file_path'] ?>" target="_blank" class="btn btn-sm btn-outline-primary w-100 fw-bold shadow-sm"><i class="bi bi-eye"></i> Dekontu İncele</a>
                        <?php else: ?>
                            <div class="text-muted small fst-italic">Dekont yüklenmemiş.</div>
                        <?php endif; ?>
                    </div>
                    <?php if($order['payment_status'] == 'pending'): ?>
                        <form action="" method="POST">
                            <button type="submit" name="approve_payment" class="btn btn-success w-100 fw-bold shadow-sm py-2" onclick="return confirm('Ödemeyi onayladığınızda sipariş işlemeye alınacaktır. Devam?')">ÖDEMEYİ ONAYLA</button>
                        </form>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="card shadow-sm border-0 mb-4 rounded-4 bg-white">
            <div class="card-header bg-white py-3 border-bottom">
                <h6 class="mb-0 fw-bold text-uppercase"><i class="bi bi-activity text-info me-2"></i>Sipariş Genel Durumu</h6>
            </div>
            <div class="card-body text-center p-4">
                <div class="mb-4 fs-5">
                    <?php if ($order['is_cancel_requested'] == 1 && $order['status'] != 'cancelled'): ?>
                        <span class="badge bg-danger pulse-warning px-4 py-3"><i class="bi bi-exclamation-octagon-fill"></i> İPTAL TALEBİ VAR</span>
                    <?php else: ?>
                        <?php 
                        $b_class = 'bg-secondary';
                        $b_text = 'Bilinmiyor';
                        switch($order['status']){
                            case 'pending': $b_class = 'bg-warning text-dark'; $b_text = 'Onay Bekliyor'; break;
                            case 'processing': $b_class = 'bg-info text-dark'; $b_text = 'İşlemde / Parçalı Gönderim Sürecinde'; break;
                            case 'shipped': $b_class = 'bg-primary'; $b_text = 'Tüm Lojistik Tamamlandı'; break;
                            case 'delivered': $b_class = 'bg-success'; $b_text = 'Teslim Edildi'; break;
                            case 'cancelled': $b_class = 'bg-danger'; $b_text = 'İptal Edildi'; break;
                        }
                        echo "<span class='badge {$b_class} px-3 py-2'>{$b_text}</span>";
                        ?>
                    <?php endif; ?>
                </div>
                
                <form action="" method="POST" class="d-grid gap-2">
                    <select name="order_status" class="form-select border-2 fw-bold text-center mb-2" <?= $order['is_cancel_requested'] ? 'disabled' : '' ?>>
                        <option value="pending" <?= $order['status']=='pending'?'selected':'' ?>>Onay Bekliyor</option>
                        <option value="processing" <?= $order['status']=='processing'?'selected':'' ?>>İşlemde / Parçalı Gönderim Sürecinde</option>
                        <option value="shipped" <?= $order['status']=='shipped'?'selected':'' ?>>Tüm Lojistik İşlemleri Tamamlandı</option>
                        <option value="delivered" <?= $order['status']=='delivered'?'selected':'' ?>>Tüm Sipariş Teslim Edildi</option>
                        <option value="cancelled" <?= $order['status']=='cancelled'?'selected':'' ?>>Siparişi İptal Et</option>
                    </select>
                    <?php if($order['is_cancel_requested']): ?>
                         <div class="text-danger small fw-bold mb-2">Müşteri iptal talep ettiği için durum değişikliği kilitlendi.</div>
                    <?php endif; ?>
                    <button type="submit" name="durum_guncelle" class="btn btn-dark fw-bold shadow-sm" <?= $order['is_cancel_requested'] ? 'disabled' : '' ?>><i class="bi bi-arrow-repeat me-1"></i> Durumu Güncelle</button>
                </form>
                
                <div class="text-start mt-3 small text-muted">
                    <?php if(count($kutu_planlari) > 0 || count($standart_urunler) > 0): ?>
                        <div class="alert alert-primary bg-opacity-10 border-primary border-opacity-25 p-2 mb-0" style="font-size: 0.8rem;">
                            <i class="bi bi-lightbulb-fill text-primary"></i> <b>Senior Notu:</b> Parçalı kargo sistemini kullanıyorsanız; son kargo çıkana kadar siparişin genel durumunu <b>"İşlemde / Parçalı Gönderim Sürecinde"</b> olarak bırakmanız tavsiye edilir.
                            <?php if($gonderilmemis_kutu_var_mi): ?>
                                <br><span class="text-danger fw-bold mt-1 d-block"><i class="bi bi-exclamation-triangle"></i> Dikkat: Henüz kargolanmamış paket kutuları var!</span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>

            </div>
        </div>

    </div>
</div>

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