<?php
/**
 * Teslimat Detay ve Lojistik Yönetim Sayfası
 * Konum: /magaza/admin/abonelikler/teslimat_detay.php
 */

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

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

adminCheck();

// 1. ID KONTROLÜ
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: teslimat_merkezi.php");
    exit;
}

$teslimat_id = (int)$_GET['id'];
$mesaj = '';

/**
 * --- İŞLEM: KARGO DURUMU GÜNCELLEME VEYA API TETİKLEME ---
 */
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['update_tracking'])) {
        $tracking_code = trim($_POST['tracking_code']);
        $status = $_POST['status'];
        
        $up = $db->prepare("UPDATE subscription_deliveries SET tracking_code = ?, status = ? WHERE id = ?");
        if ($up->execute([$tracking_code, $status, $teslimat_id])) {
            $mesaj = "<div class='alert alert-success shadow-sm'>Teslimat bilgileri başarıyla güncellendi.</div>";
        }
    }
}

// 2. TÜM VERİLERİ ÇEK
$sql = "
    SELECT sd.*, 
           u.name as u_name, u.surname as u_surname, u.email as u_email, u.phone as u_phone,
           p.name as p_name, p.type as p_type,
           s.start_date, s.end_date,
           ua.title as addr_title, ua.city, ua.district, ua.full_address
    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 u.id = ua.user_id AND ua.is_default = 1
    WHERE sd.id = ?
";
$stmt = $db->prepare($sql);
$stmt->execute([$teslimat_id]);
$t = $stmt->fetch();

if (!$t) {
    die("Teslimat kaydı bulunamadı.");
}

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

<div class="row mb-4 align-items-center text-dark">
    <div class="col-md-6">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-1">
                <li class="breadcrumb-item"><a href="teslimat_merkezi.php">Teslimat Merkezi</a></li>
                <li class="breadcrumb-item active">Teslimat Detayı</li>
            </ol>
        </nav>
        <h2 class="fw-bold mb-0">#<?= $t['id'] ?> Nolu Teslimat Detayı</h2>
    </div>
    <div class="col-md-6 text-md-end">
        <a href="teslimat_merkezi.php" class="btn btn-outline-secondary fw-bold">
            <i class="bi bi-arrow-left"></i> Listeye Dön
        </a>
    </div>
</div>

<?= $mesaj ?>

<div class="row text-dark">
    <div class="col-lg-8">
        <div class="card shadow-sm border-0 rounded-4 mb-4">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-geo-alt-fill text-danger me-2"></i>Gönderim Adresi</h5>
            </div>
            <div class="card-body p-4">
                <div class="row g-4">
                    <div class="col-md-6">
                        <label class="small text-muted fw-bold d-block mb-1">ALICI AD SOYAD</label>
                        <div class="fs-5 fw-bold"><?= htmlspecialchars($t['u_name'] . ' ' . $t['u_surname']) ?></div>
                        <div class="text-muted small"><?= $t['u_email'] ?></div>
                    </div>
                    <div class="col-md-6">
                        <label class="small text-muted fw-bold d-block mb-1">İLETİŞİM TELEFONU</label>
                        <div class="fs-5 fw-bold"><?= $t['u_phone'] ?></div>
                    </div>
                    <div class="col-12">
                        <hr class="my-2">
                        <label class="small text-muted fw-bold d-block mb-1">TAM ADRES (<?= htmlspecialchars($t['addr_title'] ?? 'Varsayılan') ?>)</label>
                        <?php if($t['full_address']): ?>
                            <div class="fs-6 lh-sm"><?= nl2br(htmlspecialchars($t['full_address'])) ?></div>
                            <div class="fw-bold mt-2"><?= $t['district'] ?> / <?= strtoupper($t['city']) ?></div>
                        <?php else: ?>
                            <div class="alert alert-danger mb-0 mt-2">
                                <i class="bi bi-exclamation-triangle-fill me-2"></i> Öğrencinin kayıtlı bir adresi bulunamadı!
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="card shadow-sm border-0 rounded-4 mb-4">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-box-seam-fill text-primary me-2"></i>Paket İçeriği</h5>
            </div>
            <div class="card-body p-4">
                <div class="d-flex align-items-center p-3 bg-light rounded-3 border">
                    <div class="flex-shrink-0">
                        <i class="bi bi-journal-bookmark-fill fs-1 text-secondary"></i>
                    </div>
                    <div class="ms-4">
                        <div class="fw-bold fs-5"><?= htmlspecialchars($t['p_name']) ?></div>
                        <div class="badge bg-dark">Abonelik Teslimatı</div>
                        <div class="mt-2 small text-muted">
                            Abonelik Dönemi: <?= date('d.m.Y', strtotime($t['start_date'])) ?> - <?= date('d.m.Y', strtotime($t['end_date'])) ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card shadow-sm border-0 rounded-4 mb-4">
            <div class="card-header bg-white py-3 text-center">
                <h5 class="mb-0 fw-bold">Lojistik Durumu</h5>
            </div>
            <div class="card-body p-4">
                <div class="text-center mb-4">
                    <?php if($t['status'] == 'pending_shipment'): ?>
                        <div class="display-6 text-warning"><i class="bi bi-hourglass-split"></i></div>
                        <h4 class="fw-bold text-warning">Bekliyor</h4>
                        <p class="small text-muted"><?= $t['delivery_month'] ?> Ayı Paketi</p>
                    <?php else: ?>
                        <div class="display-6 text-success"><i class="bi bi-truck"></i></div>
                        <h4 class="fw-bold text-success">Kargolandı</h4>
                        <p class="small text-muted">Takip Numarası: <b><?= $t['tracking_code'] ?></b></p>
                    <?php endif; ?>
                </div>

                <form action="" method="POST" class="border-top pt-4">
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Kargo Durumu</label>
                        <select name="status" class="form-select fw-bold">
                            <option value="pending_shipment" <?= $t['status'] == 'pending_shipment' ? 'selected' : '' ?>>Bekliyor</option>
                            <option value="shipped" <?= $t['status'] == 'shipped' ? 'selected' : '' ?>>Kargolandı</option>
                        </select>
                    </div>
                    <div class="mb-4">
                        <label class="form-label small fw-bold">Takip / Barkod Kodu</label>
                        <input type="text" name="tracking_code" class="form-control fw-bold" value="<?= $t['tracking_code'] ?>" placeholder="Henüz girilmedi">
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button type="submit" name="update_tracking" class="btn btn-dark fw-bold">
                            Bilgileri Güncelle
                        </button>
                        
                        <?php if($t['barcode_url']): ?>
                            <a href="<?= $t['barcode_url'] ?>" target="_blank" class="btn btn-danger fw-bold">
                                <i class="bi bi-printer-fill me-2"></i> Barkodu Yazdır
                            </a>
                        <?php endif; ?>
                        
                        <?php if($t['status'] == 'pending_shipment' && $t['full_address']): ?>
                            <button type="button" class="btn btn-warning fw-bold mt-2 shadow-sm">
                                <i class="bi bi-lightning-fill"></i> Geliver API ile Gönder
                            </button>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>

        <div class="alert alert-secondary small border-0 shadow-sm">
            <i class="bi bi-info-circle-fill me-2"></i> Bu işlem, sadece ilgili aya ait teslimatı günceller. Aboneliğin genel durumunu etkilemez.
        </div>
    </div>
</div>

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