<?php
/**
 * Admin Deneme Paketi - Gönderilenler & Kargo Takip (İki Tarih Filtreli)
 * Konum: /magaza/admin/denemepaket/gonderilenler.php
 */

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

// Güvenlik Kontrolü
adminCheck();

$mesaj = '';

/**
 * --- İŞLEM: KUTUYU "TESLİMATI TAMAMLANDI" OLARAK İŞARETLE ---
 */
if (isset($_POST['mark_delivered'])) {
    $order_id = (int)$_POST['order_id'];
    $seq = (int)$_POST['sequence'];

    $up = $db->prepare("UPDATE order_deliveries SET status = 'delivered' WHERE order_id = ? AND delivery_sequence = ?");
    if ($up->execute([$order_id, $seq])) {
        $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Kutu teslim edildi olarak işaretlendi!</div>";
    }
}

// Varsayılan Tarih Aralığı: Son 30 gün ve önümüzdeki 7 gün (Gecikenleri ve yeni çıkanları kapsamak için)
$baslangic_tarihi = isset($_GET['baslangic']) ? $_GET['baslangic'] : date('Y-m-d', strtotime('-30 days'));
$bitis_tarihi = isset($_GET['bitis']) ? $_GET['bitis'] : date('Y-m-d', strtotime('+7 days'));
$durum_filtre = isset($_GET['durum']) ? $_GET['durum'] : 'shipped'; // Varsayılan sadece 'shipped' (Kargoda olanlar) gelsin

/**
 * --- GÖNDERİLMİŞ (SHIPPED / DELIVERED) KUTULARI ÇEK ---
 */
$where_durum = ($durum_filtre == 'all') ? "IN ('shipped', 'delivered')" : "= '$durum_filtre'";

$sql = "
    SELECT 
        od.order_id, od.delivery_sequence, od.planned_date, od.status as box_status, od.tracking_code, od.shipping_company,
        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(p.name SEPARATOR '<br>• ') as exam_list
    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 $where_durum
      AND od.planned_date >= ? 
      AND od.planned_date <= ?
    GROUP BY od.order_id, od.delivery_sequence
    ORDER BY od.planned_date DESC, o.id DESC
";

$stmt = $db->prepare($sql);
$stmt->execute([$baslangic_tarihi, $bitis_tarihi]);
$gonderilen_kutular = $stmt->fetchAll(PDO::FETCH_ASSOC);

$page_title = "Gönderilen Paketler";
require_once '../header.php';
?>

<div class="row mb-4 align-items-center text-dark">
    <div class="col-md-4">
        <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>
            <i class="bi bi-truck text-info me-2"></i>Gönderilen Paketler
        </h2>
        <p class="text-muted small mt-2">Kargoya verilmiş paketleri takip edin ve teslimatları onaylayın.</p>
    </div>
    
    <div class="col-md-8 text-md-end d-flex justify-content-md-end align-items-center mt-3 mt-md-0">
        <form action="" method="GET" class="d-flex align-items-center bg-white p-2 rounded shadow-sm border">
            <select name="durum" class="form-select form-select-sm fw-bold border-0 bg-light me-2" onchange="this.form.submit()">
                <option value="shipped" <?= $durum_filtre == 'shipped' ? 'selected' : '' ?>>Yolda Olanlar</option>
                <option value="delivered" <?= $durum_filtre == 'delivered' ? 'selected' : '' ?>>Teslim Edilenler</option>
                <option value="all" <?= $durum_filtre == 'all' ? 'selected' : '' ?>>Tümü</option>
            </select>
            <span class="text-muted mx-2">|</span>
            <label class="fw-bold small text-muted me-2 text-nowrap">Planlanan Tarih:</label>
            <input type="date" name="baslangic" class="form-control form-control-sm fw-bold border-0 bg-light me-2" value="<?= $baslangic_tarihi ?>">
            <span class="text-muted small fw-bold me-2">-</span>
            <input type="date" name="bitis" class="form-control form-control-sm fw-bold border-0 bg-light me-2" value="<?= $bitis_tarihi ?>">
            <button type="submit" class="btn btn-sm btn-info text-white fw-bold px-3"><i class="bi bi-search"></i></button>
        </form>
    </div>
</div>

<?= $mesaj; ?>

<div class="card shadow-sm border-0 rounded-4 overflow-hidden">
    <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center border-bottom">
        <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-list-check me-2 text-info"></i>Kargo Listesi</h5>
        <span class="badge bg-secondary rounded-pill"><?= count($gonderilen_kutular) ?> Kayıt Gösteriliyor</span>
    </div>
    <div class="card-body p-0">
        <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">PLANLANAN TARİH</th>
                        <th>MÜŞTERİ / SİPARİŞ</th>
                        <th>PAKET / SIRA</th>
                        <th>KARGO BİLGİSİ</th>
                        <th class="text-end pe-4">DURUM / AKSİYON</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($gonderilen_kutular) > 0): ?>
                        <?php foreach($gonderilen_kutular as $kutu): 
                            $gorsel = ($kutu['main_image'] == 'assets/img/no-image.jpg' && !empty($kutu['brand_logo'])) ? $kutu['brand_logo'] : $kutu['main_image'];
                        ?>
                        <tr>
                            <td class="ps-4 fw-bold text-muted">
                                <?= date('d.m.Y', strtotime($kutu['planned_date'])) ?>
                            </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>
                                        <span class="badge bg-secondary" style="font-size: 10px;"><?= $kutu['delivery_sequence'] ?>. Gönderim</span>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="bg-light p-2 rounded border text-center" style="max-width: 180px;">
                                    <div class="small fw-bold text-dark text-truncate mb-1"><?= htmlspecialchars($kutu['shipping_company']) ?></div>
                                    <span class="badge bg-white text-dark border user-select-all d-block"><?= htmlspecialchars($kutu['tracking_code']) ?></span>
                                </div>
                            </td>
                            <td class="text-end pe-4">
                                <?php if($kutu['box_status'] == 'shipped'): ?>
                                    <div class="d-flex flex-column align-items-end">
                                        <span class="badge bg-primary mb-2"><i class="bi bi-truck me-1"></i> Yolda</span>
                                        <form action="" method="POST">
                                            <input type="hidden" name="order_id" value="<?= $kutu['order_id'] ?>">
                                            <input type="hidden" name="sequence" value="<?= $kutu['delivery_sequence'] ?>">
                                            <button type="submit" name="mark_delivered" class="btn btn-sm btn-success fw-bold rounded-pill px-3 shadow-sm" onclick="return confirm('Müşterinin bu kutuyu teslim aldığını onaylıyor musunuz?')">
                                                Teslim Edildi Yap
                                            </button>
                                        </form>
                                    </div>
                                <?php else: ?>
                                    <span class="badge bg-success px-3 py-2 rounded-pill"><i class="bi bi-check2-all me-1"></i> Teslim Edildi</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <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> Belirtilen tarihler arasında kargolanmış kutu bulunamadı.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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