<?php
/**
 * Admin Deneme Paketi - Müşteri İlerleme ve Kutu Takip Merkezi (Joker Kapaklı)
 * Konum: /magaza/admin/denemepaket/takip.php
 */

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

adminCheck();

// --- ARAMA FİLTRESİ ---
$arama = isset($_GET['q']) ? trim($_GET['q']) : '';
$where_sql = "";
$params = [];

if ($arama !== '') {
    $where_sql = "AND (o.order_number LIKE ? OR u.name LIKE ? OR u.surname LIKE ? OR u.phone LIKE ?)";
    $params = ["%$arama%", "%$arama%", "%$arama%", "%$arama%"];
}

// --- ZEKİ İLERLEME ALGORİTMASI VE JOKER KAPAK ---
$sql = "
    SELECT 
        o.id as order_id, o.order_number, o.created_at, o.status as order_status, o.is_cancel_requested,
        u.id as user_id, u.name, u.surname, u.phone,
        pkg.id as package_id, 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,
        COUNT(DISTINCT od.delivery_sequence) as total_boxes,
        COUNT(DISTINCT CASE WHEN od.status IN ('shipped', 'delivered') THEN od.delivery_sequence END) as shipped_boxes
    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
    WHERE o.status != 'cancelled' $where_sql
    GROUP BY o.id, o.order_number, o.created_at, o.status, o.is_cancel_requested, u.id, u.name, u.surname, u.phone, pkg.id, pkg.name, b.logo, b.default_cover
    ORDER BY o.is_cancel_requested DESC, o.id DESC
";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$paket_siparisleri = $stmt->fetchAll(PDO::FETCH_ASSOC);

$detay_stmt = $db->query("
    SELECT order_id, delivery_sequence, MIN(planned_date) as planned_date, MAX(status) as status, MAX(shipping_company) as shipping_company, MAX(tracking_code) as tracking_code 
    FROM order_deliveries 
    GROUP BY order_id, delivery_sequence 
    ORDER BY delivery_sequence ASC
");
$tum_detaylar = $detay_stmt->fetchAll(PDO::FETCH_ASSOC);

$kutu_detaylari = [];
foreach($tum_detaylar as $d) {
    $kutu_detaylari[$d['order_id']][] = $d;
}

$page_title = "Müşteri Kutu Takip Merkezi";
require_once '../header.php';
?>

<style>
    @keyframes pulse-red-border { 0% { border-color: #dee2e6; } 50% { border-color: #dc3545; box-shadow: 0 0 10px rgba(220, 53, 69, 0.2); } 100% { border-color: #dee2e6; } }
    .card-cancel-requested { border: 2px solid #dc3545 !important; animation: pulse-red-border 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></a>
            <i class="bi bi-person-lines-fill text-info me-2"></i>Müşteri Paket Takibi
        </h2>
        <p class="text-muted small mt-2">Tüm paketlerin teslimat yolculuğunu ve güncel durumlarını buradan izleyin.</p>
    </div>
    <div class="col-md-6">
        <form action="" method="GET">
            <div class="input-group shadow-sm rounded-pill overflow-hidden border border-2 border-info">
                <span class="input-group-text bg-white border-0"><i class="bi bi-search text-info fw-bold"></i></span>
                <input type="text" name="q" class="form-control border-0 shadow-none py-2 fw-bold" placeholder="Müşteri ara (İsim, Telefon, Sipariş #)" value="<?= htmlspecialchars($arama) ?>">
                <button class="btn btn-info text-white fw-bold px-4" type="submit">Ara</button>
            </div>
        </form>
    </div>
</div>

<div class="row g-4">
    <?php if(count($paket_siparisleri) > 0): ?>
        <?php foreach($paket_siparisleri as $siparis): 
            $yuzde = ($siparis['total_boxes'] > 0) ? round(($siparis['shipped_boxes'] / $siparis['total_boxes']) * 100) : 0;
            $is_late_request = ($siparis['is_cancel_requested'] == 1);
            $tamamlandi_mi = ($yuzde == 100);
            
            $renk = $tamamlandi_mi ? "success" : "primary";
            if ($is_late_request) $renk = "danger";

            $gorsel = ($siparis['main_image'] == 'assets/img/no-image.jpg' && !empty($siparis['brand_logo'])) ? $siparis['brand_logo'] : $siparis['main_image'];
        ?>
        <div class="col-12">
            <div class="card shadow-sm border-0 rounded-4 overflow-hidden <?= $is_late_request ? 'card-cancel-requested' : '' ?>">
                <div class="card-body p-0">
                    <div class="row g-0 align-items-center">
                        
                        <div class="col-md-4 p-4 border-end bg-light h-100">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <span class="badge bg-dark rounded-pill">#<?= $siparis['order_number'] ?></span>
                                <small class="text-muted fw-bold"><?= date('d.m.Y', strtotime($siparis['created_at'])) ?></small>
                            </div>
                            <h5 class="fw-bold text-dark mb-1"><?= htmlspecialchars($siparis['name'] . ' ' . $siparis['surname']) ?></h5>
                            <div class="text-muted small mb-3"><i class="bi bi-telephone-fill me-1"></i> <?= htmlspecialchars($siparis['phone']) ?></div>
                            
                            <div class="d-flex align-items-center bg-white p-2 rounded shadow-sm border">
                                <img src="../../<?= htmlspecialchars($gorsel) ?>" class="rounded bg-light border me-2" style="width: 40px; height: 50px; object-fit: contain;">
                                <div class="fw-bold text-info small" style="line-height: 1.2;">
                                    <?= htmlspecialchars($siparis['package_name']) ?>
                                </div>
                            </div>

                            <?php if($is_late_request): ?>
                                <div class="alert alert-danger py-1 px-2 mt-3 small fw-bold mb-0 text-center">
                                    <i class="bi bi-exclamation-triangle-fill"></i> İPTAL TALEBİ VAR
                                </div>
                            <?php endif; ?>

                            <a href="../siparisler/detay.php?id=<?= $siparis['order_id'] ?>" class="btn btn-sm btn-outline-dark w-100 mt-3 fw-bold rounded-pill shadow-sm">
                                Kaydı İncele <i class="bi bi-arrow-right ms-1"></i>
                            </a>
                        </div>

                        <div class="col-md-8 p-4">
                            <div class="d-flex justify-content-between align-items-end mb-2">
                                <span class="fw-bold text-dark small text-uppercase">TESLİMAT SÜRECİ</span>
                                <span class="badge bg-<?= $renk ?> fs-6 py-1 px-3 rounded-pill"><?= $siparis['shipped_boxes'] ?> / <?= $siparis['total_boxes'] ?> Kutu</span>
                            </div>
                            
                            <div class="progress mb-4" style="height: 12px; background-color: #e9ecef; border-radius: 10px;">
                                <div class="progress-bar progress-bar-striped <?= (!$tamamlandi_mi && !$is_late_request) ? 'progress-bar-animated' : '' ?> bg-<?= $renk ?>" style="width: <?= $yuzde ?>%"></div>
                            </div>

                            <div class="row row-cols-2 row-cols-md-4 g-2">
                                <?php 
                                $detaylar = $kutu_detaylari[$siparis['order_id']] ?? [];
                                foreach($detaylar as $kutu): 
                                    $kargolandi = in_array($kutu['status'], ['shipped', 'delivered']);
                                ?>
                                    <div class="col">
                                        <div class="p-2 border rounded-3 text-center h-100 <?= $kargolandi ? 'bg-success bg-opacity-10 border-success' : ($is_late_request ? 'bg-danger bg-opacity-10' : 'bg-white') ?>">
                                            <div class="fw-bold" style="font-size: 11px;"><?= $kutu['delivery_sequence'] ?>. Kutu</div>
                                            <?php if($kargolandi): ?>
                                                <i class="bi bi-check-circle-fill text-success fs-5 d-block"></i>
                                                <small class="fw-bold text-dark d-block text-truncate"><?= htmlspecialchars($kutu['shipping_company']) ?></small>
                                            <?php else: ?>
                                                <i class="bi bi-clock-history text-muted fs-5 d-block"></i>
                                                <small class="text-muted" style="font-size: 10px;">
                                                    <?= $is_late_request ? 'Durduruldu' : ($kutu['planned_date'] ? date('d.m', strtotime($kutu['planned_date'])) : 'Bekliyor') ?>
                                                </small>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="col-12 text-center py-5">
            <i class="bi bi-inbox text-muted opacity-25" style="font-size: 5rem;"></i>
            <h4 class="fw-bold mt-3">Sistemde aktif paket kaydı bulunamadı.</h4>
            <a href="index.php" class="btn btn-primary rounded-pill px-4 mt-2 shadow-sm">Operasyon Paneline Dön</a>
        </div>
    <?php endif; ?>
</div>

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