<?php
/**
 * Admin Sipariş Yönetimi - Ana Liste (Sayfalama ve Gelişmiş Filtreleme)
 * Konum: /magaza/admin/siparisler/index.php
 */

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

/**
 * GÜVENLİK KONTROLÜ
 */
adminCheck();

// --- ARAMA VE FİLTRELEME ---
$where_clauses = [];
$params = [];

// Arama Çubuğu
$arama = isset($_GET['q']) ? trim($_GET['q']) : '';
if ($arama !== '') {
    $where_clauses[] = "(o.order_number LIKE ? OR u.name LIKE ? OR u.surname LIKE ? OR u.email LIKE ?)";
    $params = array_merge($params, ["%$arama%", "%$arama%", "%$arama%", "%$arama%"]);
}

// Durum Filtresi
$durum_filtre = isset($_GET['status']) ? $_GET['status'] : '';
if ($durum_filtre !== '') {
    $where_clauses[] = "o.status = ?";
    $params[] = $durum_filtre;
}

// Tarih Aralığı Filtreleri
$baslangic_tarihi = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$bitis_tarihi = isset($_GET['end_date']) ? $_GET['end_date'] : '';

if ($baslangic_tarihi !== '') {
    $where_clauses[] = "DATE(o.created_at) >= ?";
    $params[] = $baslangic_tarihi;
}
if ($bitis_tarihi !== '') {
    $where_clauses[] = "DATE(o.created_at) <= ?";
    $params[] = $bitis_tarihi;
}

$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(" AND ", $where_clauses) : "";

// --- SAYFALAMA (PAGINATION) AYARLARI ---
$limit = 20; // Her sayfada gösterilecek sipariş sayısı
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;

$offset = ($page - 1) * $limit;

// Toplam Kayıt Sayısını Bul
$count_sql = "SELECT COUNT(o.id) FROM orders o JOIN users u ON o.user_id = u.id $where_sql";
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_records = $count_stmt->fetchColumn();

// Toplam Sayfa Sayısını Hesapla
$total_pages = ceil($total_records / $limit);

// --- SİPARİŞLERİ ÇEKME ---
$sql = "
    SELECT o.*, u.name, u.surname, u.email,
           (SELECT COUNT(id) FROM order_items WHERE order_id = o.id) as urun_cesit_sayisi,
           (SELECT COUNT(id) FROM order_deliveries WHERE order_id = o.id) as toplam_kutu_sayisi,
           (SELECT COUNT(id) FROM order_deliveries WHERE order_id = o.id AND status = 'shipped') as kargolanan_kutu_sayisi,
           (SELECT status FROM order_returns WHERE order_id = o.id AND request_type = 'return' ORDER BY id DESC LIMIT 1) as iade_durumu,
           (SELECT planned_date FROM order_deliveries WHERE order_id = o.id AND status = 'pending' ORDER BY planned_date ASC LIMIT 1) as siradaki_kargo_tarihi,
           (SELECT GROUP_CONCAT(p.exam_publication_date) FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = o.id AND p.type = 'single_exam') as exam_dates
    FROM orders o
    JOIN users u ON o.user_id = u.id
    $where_sql
    ORDER BY o.is_cancel_requested DESC, o.id DESC
    LIMIT $limit OFFSET $offset
";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$siparisler = $stmt->fetchAll();

require_once '../header.php';

/**
 * İngilizce durumları Türkçe ve Görsel Badge'lere çeviren profesyonel fonksiyon
 */
function siparisDurumBadgeTurkce($status, $cancel_requested = 0) {
    if ($cancel_requested == 1 && $status != 'cancelled') {
        return '<span class="badge bg-danger pulse-red px-3 py-2"><i class="bi bi-exclamation-octagon-fill me-1"></i> İPTAL TALEBİ VAR</span>';
    }

    switch ($status) {
        case 'pending': return '<span class="badge bg-warning text-dark px-3 py-2"><i class="bi bi-hourglass-split me-1"></i> Onay Bekliyor</span>';
        case 'processing': return '<span class="badge bg-info text-dark px-3 py-2"><i class="bi bi-box-seam me-1"></i> Hazırlanıyor</span>';
        case 'shipped': return '<span class="badge bg-primary px-3 py-2"><i class="bi bi-truck me-1"></i> Kargolandı</span>';
        case 'delivered': return '<span class="badge bg-success px-3 py-2"><i class="bi bi-check-circle-fill me-1"></i> Teslim Edildi</span>';
        case 'cancelled': return '<span class="badge bg-danger px-3 py-2"><i class="bi bi-x-circle-fill me-1"></i> İptal Edildi</span>';
        default: return '<span class="badge bg-secondary px-3 py-2">Bilinmiyor</span>';
    }
}

/**
 * Admin İçin Akıllı Kargo Tarihi Belirleyici
 */
function getAdminKargoTarihiRozeti($siparis) {
    if (in_array($siparis['status'], ['shipped', 'delivered', 'cancelled'])) {
        return '';
    }

    if ($siparis['toplam_kutu_sayisi'] > 0 && !empty($siparis['siradaki_kargo_tarihi'])) {
        return '<div class="mt-1 text-primary fw-bold" style="font-size: 0.65rem;"><i class="bi bi-calendar-event me-1"></i>Sıradaki Kutu: ' . date('d.m.Y', strtotime($siparis['siradaki_kargo_tarihi'])) . '</div>';
    }

    if (!empty($siparis['exam_dates'])) {
        $bugun = new DateTime('midnight');
        $tarihler = explode(',', $siparis['exam_dates']);
        $gelecek_tarihler = [];
        $gecmis_var = false;

        foreach ($tarihler as $t) {
            $t = trim($t);
            if (empty($t)) { $gecmis_var = true; continue; }
            $d = DateTime::createFromFormat('d.m.Y', $t);
            if ($d) {
                $d->setTime(0, 0, 0); 
                if ($d < $bugun) { $gecmis_var = true; } else {
                    $d->modify('next tuesday');
                    $gelecek_tarihler[] = $d->getTimestamp();
                }
            } else { $gecmis_var = true; }
        }

        $html = '';
        if (!empty($gelecek_tarihler)) {
            sort($gelecek_tarihler);
            $ilk_kargo = date('d.m.Y', $gelecek_tarihler[0]);
            if ($gecmis_var) {
                $html .= '<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 d-block mt-1 mx-auto" style="font-size: 0.65rem; width: fit-content;"><i class="bi bi-box-seam me-1"></i>Kısmi (Hemen)</span>';
            }
            $html .= '<span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 d-block mt-1 mx-auto" style="font-size: 0.65rem; width: fit-content;"><i class="bi bi-truck me-1"></i>Planlı: ' . $ilk_kargo . ' (Salı)</span>';
            return $html;
        } elseif ($gecmis_var) {
            return '<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 d-block mt-1 mx-auto" style="font-size: 0.65rem; width: fit-content;"><i class="bi bi-box-seam me-1"></i>Hemen Kargoya Hazır</span>';
        }
    }
    return '<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 d-block mt-1 mx-auto" style="font-size: 0.65rem; width: fit-content;"><i class="bi bi-box-seam me-1"></i>Hemen Kargoya Hazır</span>';
}

// Sayfalama linkleri için mevcut GET parametrelerini koruma
$query_string = $_GET;
unset($query_string['page']);
$qs = http_build_query($query_string);
$pagination_url = "index.php?" . ($qs ? $qs . "&" : "") . "page=";
?>

<style>
/* İptal Talebi İçin Yanıp Sönen Kırmızı Efekt */
@keyframes pulse-red-animation {
    0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7); }
    70% { transform: scale(1.05); 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-red { animation: pulse-red-animation 2s infinite; }
.table-danger-light { background-color: rgba(220, 53, 69, 0.05) !important; }
</style>

<div class="row mb-4 align-items-center">
    <div class="col-md-6">
        <h2 class="fw-bold mb-0 text-dark"><i class="bi bi-cart-check-fill text-success me-2"></i>Sipariş Yönetimi</h2>
        <span class="badge bg-secondary shadow-sm">Toplam <?= $total_records ?> Kayıt Bulundu</span>
    </div>
</div>

<div class="card shadow-sm mb-4 border-0">
    <div class="card-body bg-light rounded-3 p-4">
        <form action="index.php" method="GET" class="row g-3 align-items-end">
            <div class="col-md-3">
                <label class="form-label text-muted small fw-bold text-uppercase">Arama</label>
                <div class="input-group">
                    <span class="input-group-text bg-white border-end-0 border-2"><i class="bi bi-search text-muted"></i></span>
                    <input type="text" name="q" class="form-control border-start-0 ps-0 border-2 shadow-none" value="<?= htmlspecialchars($arama) ?>" placeholder="Sipariş No, İsim vb.">
                </div>
            </div>
            
            <div class="col-md-2">
                <label class="form-label text-muted small fw-bold text-uppercase">Durum</label>
                <select name="status" class="form-select border-2 shadow-none">
                    <option value="">Tümü</option>
                    <option value="pending" <?= ($durum_filtre == 'pending') ? 'selected' : '' ?>>Onay Bekleyenler</option>
                    <option value="processing" <?= ($durum_filtre == 'processing') ? 'selected' : '' ?>>Hazırlananlar</option>
                    <option value="shipped" <?= ($durum_filtre == 'shipped') ? 'selected' : '' ?>>Kargolananlar</option>
                    <option value="delivered" <?= ($durum_filtre == 'delivered') ? 'selected' : '' ?>>Teslim Edilenler</option>
                    <option value="cancelled" <?= ($durum_filtre == 'cancelled') ? 'selected' : '' ?>>İptal Edilenler</option>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label text-muted small fw-bold text-uppercase">Başlangıç Tarihi</label>
                <input type="date" name="start_date" class="form-control border-2 shadow-none" value="<?= htmlspecialchars($baslangic_tarihi) ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label text-muted small fw-bold text-uppercase">Bitiş Tarihi</label>
                <input type="date" name="end_date" class="form-control border-2 shadow-none" value="<?= htmlspecialchars($bitis_tarihi) ?>">
            </div>

            <div class="col-md-3">
                <div class="d-flex gap-2">
                    <a href="index.php" class="btn btn-outline-secondary w-25 fw-bold py-2 shadow-sm" title="Filtreleri Temizle">
                        <i class="bi bi-x-lg"></i>
                    </a>
                    <button type="submit" class="btn btn-dark w-75 fw-bold py-2 shadow">
                        <i class="bi bi-funnel-fill me-1"></i> Filtrele
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0 mb-4">
    <div class="card-body p-0">
        <div class="table-responsive text-dark">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-dark">
                    <tr>
                        <th class="ps-3 py-3">Sipariş No</th>
                        <th>Müşteri Bilgisi</th>
                        <th>Tarih</th>
                        <th class="text-center">İçerik & Lojistik</th>
                        <th class="text-end">Tutar</th>
                        <th class="text-center">Durum / Aksiyon</th>
                        <th class="text-end pe-3">İşlemler</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($siparisler) > 0): ?>
                        <?php foreach ($siparisler as $siparis): ?>
                        <tr class="<?= $siparis['is_cancel_requested'] ? 'table-danger-light' : '' ?>">
                            <td class="ps-3 fw-bold text-primary">#<?= htmlspecialchars($siparis['order_number']) ?></td>
                            <td>
                                <div class="fw-bold"><?= htmlspecialchars($siparis['name'] . ' ' . $siparis['surname']) ?></div>
                                <div class="text-muted small"><?= htmlspecialchars($siparis['email']) ?></div>
                                <?php if($siparis['iade_durumu'] && $siparis['iade_durumu'] != 'completed'): ?>
                                    <span class="badge bg-info text-dark mt-1" style="font-size: 10px;"><i class="bi bi-arrow-counterclockwise"></i> İADE SÜRECİNDE</span>
                                <?php endif; ?>
                            </td>
                            <td class="small">
                                <div class="fw-bold text-dark"><?= date('d.m.Y', strtotime($siparis['created_at'])) ?></div>
                                <span class="text-muted"><?= date('H:i', strtotime($siparis['created_at'])) ?></span>
                            </td>
                            <td class="text-center">
                                <span class="badge bg-light text-dark border px-2 py-1 mb-1 d-inline-block"><?= $siparis['urun_cesit_sayisi'] ?> Kalem Ürün</span>
                                
                                <?php if ($siparis['toplam_kutu_sayisi'] > 0): ?>
                                    <div class="mt-1">
                                        <?php if ($siparis['toplam_kutu_sayisi'] == $siparis['kargolanan_kutu_sayisi']): ?>
                                            <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25" style="font-size: 0.7rem;">
                                                <i class="bi bi-boxes"></i> Kargo Tamam (<?= $siparis['toplam_kutu_sayisi'] ?>/<?= $siparis['toplam_kutu_sayisi'] ?>)
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-info bg-opacity-10 text-info border border-info border-opacity-25" style="font-size: 0.7rem;">
                                                <i class="bi bi-boxes"></i> Planlı Kutu (<?= $siparis['kargolanan_kutu_sayisi'] ?>/<?= $siparis['toplam_kutu_sayisi'] ?>)
                                            </span>
                                            <?= getAdminKargoTarihiRozeti($siparis) ?>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <?= getAdminKargoTarihiRozeti($siparis) ?>
                                <?php endif; ?>
                            </td>
                            <td class="text-end fw-bold text-success fs-6">
                                <?= number_format($siparis['total_amount'], 2, ',', '.') ?> ₺
                            </td>
                            <td class="text-center">
                                <?= siparisDurumBadgeTurkce($siparis['status'], $siparis['is_cancel_requested']) ?>
                                <?php if($siparis['status'] == 'shipped' || $siparis['status'] == 'delivered'): ?>
                                    <small class="text-muted d-block mt-1" style="font-size: 0.7rem;"><i class="bi bi-truck me-1"></i><?= htmlspecialchars($siparis['shipping_company'] ?? 'Kargo') ?></small>
                                <?php endif; ?>
                            </td>
                            <td class="text-end pe-3">
                                <?php if($siparis['is_cancel_requested']): ?>
                                    <a href="iptaller.php" class="btn btn-sm btn-danger shadow-sm px-3 fw-bold">
                                        Talebi Yönet
                                    </a>
                                <?php else: ?>
                                    <a href="detay.php?id=<?= $siparis['id'] ?>" class="btn btn-sm btn-outline-dark shadow-sm px-3 fw-bold">
                                        <i class="bi bi-gear-fill me-1"></i> Yönet
                                    </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="text-center py-5 text-muted">
                                <i class="bi bi-inbox fs-1 d-block mb-3 text-secondary"></i>
                                <h5>Kriterlere uygun sipariş bulunamadı.</h5>
                                <p class="small mb-0">Filtreleri değiştirerek veya farklı bir sayfaya bakarak yeniden deneyebilirsiniz.</p>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if ($total_pages > 1): ?>
<nav aria-label="Sipariş Sayfalama" class="mb-5">
    <ul class="pagination justify-content-center">
        
        <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
            <a class="page-link" href="<?= $pagination_url . ($page - 1) ?>">Önceki</a>
        </li>

        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
            <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                <a class="page-link" href="<?= $pagination_url . $i ?>"><?= $i ?></a>
            </li>
        <?php endfor; ?>

        <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
            <a class="page-link" href="<?= $pagination_url . ($page + 1) ?>">Sonraki</a>
        </li>
        
    </ul>
</nav>
<?php endif; ?>

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