<?php
/**
 * Admin Abonelik Yönetimi - Genel Liste
 * Konum: /magaza/admin/abonelikler/index.php
 */

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

adminCheck();

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

$arama = isset($_GET['q']) ? trim($_GET['q']) : '';
if ($arama !== '') {
    $where_clauses[] = "(u.name LIKE ? OR u.surname LIKE ? OR p.name LIKE ?)";
    $params = array_merge($params, ["%$arama%", "%$arama%", "%$arama%"]);
}

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

$where_sql = "";
if (count($where_clauses) > 0) {
    $where_sql = "WHERE " . implode(" AND ", $where_clauses);
}

// --- ABONELİKLERİ ÇEKME ---
// SELECT kısmında alt sorgu ile gönderilen kargo sayısını buluyoruz
$sql = "
    SELECT s.*, 
           u.name as user_name, u.surname as user_surname, u.email as user_email,
           p.name as product_name, p.total_deliveries,
           (SELECT COUNT(id) FROM subscription_deliveries WHERE subscription_id = s.id AND status = 'shipped') as sent_count
    FROM subscriptions s
    JOIN users u ON s.user_id = u.id
    JOIN products p ON s.product_id = p.id
    $where_sql
    ORDER BY s.id DESC
";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$abonelikler = $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-calendar-check text-primary me-2"></i>Abonelik Yönetimi</h2>
        <span class="badge bg-secondary shadow-sm"><?= count($abonelikler) ?> Aktif Takip Mevcut</span>
    </div>
    <div class="col-md-6 text-md-end mt-3 mt-md-0">
        <a href="teslimat_merkezi.php" class="btn btn-dark fw-bold shadow-sm">
            <i class="bi bi-truck me-2"></i> Aylık Teslimat Operasyon Merkezi
        </a>
    </div>
</div>

<div class="card shadow-sm border-0 mb-4">
    <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-5">
                <label class="form-label small fw-bold text-muted text-uppercase">Öğrenci Adı veya Paket</label>
                <input type="text" name="q" class="form-control border-2 shadow-none" value="<?= htmlspecialchars($arama) ?>" placeholder="Arama yapın...">
            </div>
            <div class="col-md-4">
                <label class="form-label small fw-bold text-muted text-uppercase">Abonelik Durumu</label>
                <select name="status" class="form-select border-2 shadow-none">
                    <option value="">Tümü</option>
                    <option value="active" <?= ($durum_filtre == 'active') ? 'selected' : '' ?>>Aktif Olanlar</option>
                    <option value="expired" <?= ($durum_filtre == 'expired') ? 'selected' : '' ?>>Süresi Dolanlar</option>
                    <option value="cancelled" <?= ($durum_filtre == 'cancelled') ? 'selected' : '' ?>>İptal Edilenler</option>
                </select>
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-primary w-100 fw-bold shadow-sm py-2">
                    <i class="bi bi-funnel me-1"></i> Filtrele
                </button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0 mb-5 overflow-hidden">
    <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">Öğrenci</th>
                        <th>Satın Alınan Paket</th>
                        <th class="text-center">Teslimat Durumu</th>
                        <th class="text-center">Abonelik Aralığı</th>
                        <th class="text-center">Durum</th>
                        <th class="text-end pe-3">İşlem</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($abonelikler) > 0): ?>
                        <?php foreach ($abonelikler as $a): ?>
                        <tr>
                            <td class="ps-3">
                                <div class="fw-bold"><?= htmlspecialchars($a['user_name'] . ' ' . $a['user_surname']) ?></div>
                                <small class="text-muted"><?= htmlspecialchars($a['user_email']) ?></small>
                            </td>
                            <td>
                                <div class="fw-bold text-primary"><?= htmlspecialchars($a['product_name']) ?></div>
                                <small class="badge bg-light text-dark border"><i class="bi bi-box me-1"></i> <?= $a['total_deliveries'] ?> Aylık Plan</small>
                            </td>
                            <td class="text-center">
                                <?php 
                                    $yuzde = ($a['total_deliveries'] > 0) ? ($a['sent_count'] / $a['total_deliveries']) * 100 : 0;
                                    $renk = ($yuzde == 100) ? 'bg-success' : 'bg-info';
                                ?>
                                <div class="d-flex align-items-center justify-content-center">
                                    <div class="me-2 fw-bold small text-muted"><?= $a['sent_count'] ?> / <?= $a['total_deliveries'] ?></div>
                                    <div class="progress w-50" style="height: 6px;">
                                        <div class="progress-bar <?= $renk ?>" style="width: <?= $yuzde ?>%"></div>
                                    </div>
                                </div>
                            </td>
                            <td class="text-center small">
                                <div class="fw-bold"><?= date('d.m.Y', strtotime($a['start_date'])) ?></div>
                                <div class="text-muted"><?= date('d.m.Y', strtotime($a['end_date'])) ?></div>
                            </td>
                            <td class="text-center">
                                <?= getStatusBadge($a['status'], 'subscription') ?>
                            </td>
                            <td class="text-end pe-3">
                                <a href="teslimat_detay.php?id=<?= $a['id'] ?>" class="btn btn-sm btn-outline-dark shadow-sm px-3 fw-bold">
                                    <i class="bi bi-list-task me-1"></i> Takvim
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="6" class="text-center py-5 text-muted">Kayıtlı abonelik bulunamadı.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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