<?php
/**
 * Aylık Deneme Teslimat Operasyon Merkezi (Gelişmiş)
 * Konum: /magaza/admin/abonelikler/teslimat_merkezi.php
 */

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

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

adminCheck();

// 1. AY FİLTRESİ
$secili_ay = isset($_GET['month']) ? $_GET['month'] : date('Y-m');

$mesaj = '';

/**
 * --- İŞLEM 1: GELİVER API İLE OTOMATİK KARGOLAMA ---
 */
if (isset($_POST['api_kargo_yap'])) {
    $teslimat_id = (int)$_POST['teslimat_id'];

    // Teslimat ve Müşteri detaylarını çek
    $stmt = $db->prepare("
        SELECT sd.*, u.name, u.surname, u.phone, u.email,
               ua.full_address, ua.city, ua.district
        FROM subscription_deliveries sd
        JOIN subscriptions s ON sd.subscription_id = s.id
        JOIN users u ON s.user_id = u.id
        LEFT JOIN user_addresses ua ON u.id = ua.user_id AND ua.is_default = 1
        WHERE sd.id = ?
    ");
    $stmt->execute([$teslimat_id]);
    $t_detay = $stmt->fetch();

    if ($t_detay && function_exists('geliver_kargo_olustur')) {
        $siparis_datasi = [
            'order_number' => "SUB-" . $t_detay['subscription_id'] . "-" . $t_detay['id'],
            'name'         => $t_detay['name'],
            'surname'      => $t_detay['surname'],
            'phone'        => $t_detay['phone'],
            'email'        => $t_detay['email'],
            'address'      => $t_detay['full_address'] ?? 'Adres Yok',
            'city'         => $t_detay['city'] ?? '',
            'district'     => $t_detay['district'] ?? ''
        ];

        $geliver = geliver_kargo_olustur($siparis_datasi);

        if ($geliver['ok']) {
            // DB Güncelle: Takip kodu ve Barkod URL'sini kaydet
            $up = $db->prepare("UPDATE subscription_deliveries SET status = 'shipped', tracking_code = ?, barcode_url = ? WHERE id = ?");
            $up->execute([$geliver['tracking'], $geliver['barcode_url'], $teslimat_id]);
            
            $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-rocket-takeoff-fill me-2'></i> Kargo barkodu başarıyla oluşturuldu!</div>";
        } else {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Geliver Hatası: " . $geliver['message'] . "</div>";
        }
    }
}

/**
 * --- İŞLEM 2: MANUEL DURUM GÜNCELLEME ---
 */
if (isset($_POST['manuel_kargo'])) {
    $teslimat_id = (int)$_POST['teslimat_id'];
    $takip_kodu = trim($_POST['tracking_code']);
    $db->prepare("UPDATE subscription_deliveries SET status = 'shipped', tracking_code = ? WHERE id = ?")->execute([$takip_kodu, $teslimat_id]);
    $mesaj = "<div class='alert alert-success shadow-sm'>Manuel kargo girişi kaydedildi.</div>";
}

// 3. LİSTEYİ ÇEK
$sql = "
    SELECT sd.*, 
           u.name as student_name, u.surname as student_surname, u.phone as student_phone,
           p.name as product_name,
           ua.full_address, ua.city, ua.district
    FROM subscription_deliveries sd
    JOIN subscriptions s ON sd.subscription_id = s.id
    JOIN users u ON s.user_id = u.id
    JOIN products p ON s.product_id = p.id
    LEFT JOIN user_addresses ua ON s.user_id = ua.user_id AND ua.is_default = 1
    WHERE sd.delivery_month = ?
    ORDER BY sd.status ASC, sd.id ASC
";
$stmt = $db->prepare($sql);
$stmt->execute([$secili_ay]);
$teslimatlar = $stmt->fetchAll();

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

<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-truck-flatbed text-success me-2"></i>Aylık Teslimat Merkezi</h2>
        <span class="text-muted small">Geliver API Entegrasyonlu Operasyon Ekranı</span>
    </div>
    <div class="col-md-6 text-md-end">
        <form action="" method="GET" class="d-inline-flex gap-2">
            <input type="month" name="month" class="form-control border-2" value="<?= $secili_ay ?>">
            <button type="submit" class="btn btn-dark fw-bold">Listele</button>
        </form>
    </div>
</div>

<?= $mesaj; ?>

<div class="card shadow-sm border-0 mb-5 overflow-hidden text-dark">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-dark">
                    <tr>
                        <th class="ps-3 py-3">Öğrenci & Adres</th>
                        <th>Paket Bilgisi</th>
                        <th class="text-center">Durum</th>
                        <th class="text-end pe-3">Lojistik İşlemi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($teslimatlar) > 0): ?>
                        <?php foreach ($teslimatlar as $t): ?>
                        <tr>
                            <td class="ps-3">
                                <div class="fw-bold"><?= htmlspecialchars($t['student_name'] . ' ' . $t['student_surname']) ?></div>
                                <div class="small text-muted mb-1"><?= $t['student_phone'] ?></div>
                                <div class="small text-primary" style="max-width: 250px;">
                                    <i class="bi bi-geo-alt-fill"></i> 
                                    <?= $t['full_address'] ? htmlspecialchars($t['full_address'].' '.$t['district'].'/'.$t['city']) : '<span class="text-danger">ADRES EKSİK!</span>' ?>
                                </div>
                            </td>
                            <td>
                                <div class="fw-bold"><?= htmlspecialchars($t['product_name']) ?></div>
                                <span class="badge bg-light text-dark border"><?= $t['delivery_month'] ?> Paketleme</span>
                            </td>
                            <td class="text-center">
                                <?php if($t['status'] == 'pending_shipment'): ?>
                                    <span class="badge bg-warning text-dark rounded-pill px-3">Bekliyor</span>
                                <?php else: ?>
                                    <span class="badge bg-success rounded-pill px-3">Kargolandı</span>
                                    <div class="mt-1 small fw-bold text-primary"><?= $t['tracking_code'] ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="text-end pe-3">
                                <?php if($t['status'] == 'pending_shipment'): ?>
                                    <div class="d-flex justify-content-end gap-2">
                                        <form action="" method="POST">
                                            <input type="hidden" name="teslimat_id" value="<?= $t['id'] ?>">
                                            <button type="submit" name="api_kargo_yap" class="btn btn-sm btn-warning fw-bold shadow-sm" <?= !$t['full_address'] ? 'disabled' : '' ?>>
                                                <i class="bi bi-lightning-fill"></i> Geliver
                                            </button>
                                        </form>
                                        <button type="button" class="btn btn-sm btn-outline-dark fw-bold" data-bs-toggle="modal" data-bs-target="#manuelModal<?= $t['id'] ?>">
                                            Manuel
                                        </button>
                                    </div>

                                    <div class="modal fade" id="manuelModal<?= $t['id'] ?>" tabindex="-1">
                                        <div class="modal-dialog modal-sm">
                                            <form action="" method="POST" class="modal-content text-start">
                                                <div class="modal-header"><h6 class="modal-title fw-bold">Manuel Takip Kodu</h6><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                                                <div class="modal-body">
                                                    <input type="hidden" name="teslimat_id" value="<?= $t['id'] ?>">
                                                    <input type="text" name="tracking_code" class="form-control" placeholder="Takip No Girin" required>
                                                </div>
                                                <div class="modal-footer border-0 p-2"><button type="submit" name="manuel_kargo" class="btn btn-primary btn-sm w-100 fw-bold">Kaydet</button></div>
                                            </form>
                                        </div>
                                    </div>

                                <?php else: ?>
                                    <?php if($t['barcode_url']): ?>
                                        <a href="<?= htmlspecialchars($t['barcode_url']) ?>" target="_blank" class="btn btn-sm btn-outline-danger fw-bold shadow-sm">
                                            <i class="bi bi-printer-fill me-1"></i> Barkod Yazdır
                                        </a>
                                    <?php else: ?>
                                        <button class="btn btn-sm btn-secondary disabled fw-bold">Gönderildi</button>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="4" class="text-center py-5 text-muted fw-bold">Bu ay için teslimat planı bulunmuyor.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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