<?php
/**
 * Admin Abonelik Ekleme - Manuel Paket Tanımlama
 * Konum: /magaza/admin/abonelikler/ekle.php
 */

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

adminCheck();

$mesaj = '';

// --- KAYIT İŞLEMİ ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['abonelik_ekle'])) {
    $user_id    = (int)$_POST['user_id'];
    $package_id = (int)$_POST['package_id'];
    $start_date = $_POST['start_date'];
    $end_date   = $_POST['end_date'];
    $status     = $_POST['status'];

    if ($user_id > 0 && $package_id > 0 && !empty($start_date) && !empty($end_date)) {
        try {
            $sql = "INSERT INTO subscriptions (user_id, package_id, start_date, end_date, status) VALUES (?, ?, ?, ?, ?)";
            $stmt = $db->prepare($sql);
            $stmt->execute([$user_id, $package_id, $start_date, $end_date, $status]);
            
            $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Abonelik başarıyla tanımlandı. <a href='index.php' class='fw-bold text-decoration-none'>Listeye Dön</a></div>";
        } catch (Exception $e) {
            $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: " . $e->getMessage() . "</div>";
        }
    } else {
        $mesaj = "<div class='alert alert-warning shadow-sm'>Lütfen tüm alanları doldurun.</div>";
    }
}

// Seçenekler için verileri çek
$musteriler = $db->query("SELECT id, name, surname, email FROM users WHERE role = 'customer' ORDER BY name ASC")->fetchAll();
$paketler   = $db->query("SELECT id, package_name, duration_days FROM packages WHERE status = 1 ORDER BY package_name ASC")->fetchAll();

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

<div class="row mb-4 align-items-center">
    <div class="col-md-6">
        <h2 class="fw-bold mb-0 text-dark"><i class="bi bi-plus-circle-fill text-primary me-2"></i>Yeni Abonelik Tanımla</h2>
    </div>
    <div class="col-md-6 text-md-end">
        <a href="index.php" class="btn btn-outline-secondary fw-bold shadow-sm"><i class="bi bi-arrow-left"></i> Geri Dön</a>
    </div>
</div>

<?= $mesaj; ?>

<div class="row">
    <div class="col-lg-8">
        <div class="card shadow-sm border-0">
            <div class="card-body p-4 text-dark">
                <form action="ekle.php" method="POST" id="subForm">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-uppercase text-muted">Müşteri / Öğrenci Seçin *</label>
                            <select name="user_id" class="form-select border-2" required>
                                <option value="">--- Müşteri Seçin ---</option>
                                <?php foreach($musteriler as $m): ?>
                                    <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['name'].' '.$m['surname'].' ('.$m['email'].')') ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-uppercase text-muted">Eğitim Paketi Seçin *</label>
                            <select name="package_id" id="packageSelect" class="form-select border-2" required>
                                <option value="">--- Paket Seçin ---</option>
                                <?php foreach($paketler as $p): ?>
                                    <option value="<?= $p['id'] ?>" data-days="<?= $p['duration_days'] ?>"><?= htmlspecialchars($p['package_name'].' ('.$p['duration_days'].' Gün)') ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-uppercase text-muted">Başlangıç Tarihi</label>
                            <input type="date" name="start_date" id="startDate" class="form-control border-2" value="<?= date('Y-m-d') ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-uppercase text-muted">Bitiş Tarihi (Otomatik Hesaplanır)</label>
                            <input type="date" name="end_date" id="endDate" class="form-control border-2" required>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold small text-uppercase text-muted">Abonelik Durumu</label>
                        <select name="status" class="form-select border-2 fw-bold text-success">
                            <option value="active">AKTİF (Erişime Açık)</option>
                            <option value="passive">PASİF (Erişime Kapalı)</option>
                        </select>
                    </div>

                    <hr>
                    <div class="d-grid">
                        <button type="submit" name="abonelik_ekle" class="btn btn-primary btn-lg fw-bold shadow">
                            <i class="bi bi-save me-2"></i> ABONELİĞİ BAŞLAT
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-lg-4">
        <div class="card bg-light border-0 shadow-sm">
            <div class="card-body p-4 text-dark">
                <h5 class="fw-bold mb-3"><i class="bi bi-info-circle me-2"></i> İpucu</h5>
                <p class="small text-muted">Öğrenciye bir paket tanımladığınızda, öğrenci paneline giriş yaptığı andan itibaren seçtiğiniz bitiş tarihine kadar içeriğe erişebilir.</p>
                <p class="small text-muted mb-0">Paket seçtiğinizde, sistem otomatik olarak bugünün tarihine paketin gün sayısını ekleyerek bitiş tarihini önerir.</p>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('packageSelect').addEventListener('change', calculateEndDate);
document.getElementById('startDate').addEventListener('change', calculateEndDate);

function calculateEndDate() {
    const pkg = document.getElementById('packageSelect');
    const start = document.getElementById('startDate').value;
    const endInput = document.getElementById('endDate');
    
    if (pkg.value && start) {
        const days = parseInt(pkg.options[pkg.selectedIndex].getAttribute('data-days'));
        let result = new Date(start);
        result.setDate(result.getDate() + days);
        endInput.value = result.toISOString().split('T')[0];
    }
}
</script>

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