<?php
/**
 * SMM Paket Satış Scripti - Kupon Yönetimi
 * @version 1.0.3
 */

// Config dahil et (header.php'den önce)
if (!defined('SITE_VERSION')) {
    require_once __DIR__ . '/../config.php';
}

// Admin kontrolü
if (!isLoggedIn() || !isAdmin()) {
    setFlash('error', 'Bu sayfaya erişim yetkiniz yok.');
    redirect(SITE_URL . '/giris.php');
    exit;
}

// İşlemler - HEADER'DAN ÖNCE YAPILMALI
$action = $_GET['action'] ?? 'list';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Kupon Silme
if ($action === 'delete' && $id > 0) {
    try {
        $stmt = $db->prepare("DELETE FROM coupons WHERE id = ?");
        $stmt->execute([$id]);
        setFlash('success', 'Kupon başarıyla silindi.');
    } catch (PDOException $e) {
        setFlash('error', 'Kupon silinirken hata oluştu.');
    }
    redirect(SITE_URL . '/admin/kuponlar.php');
    exit;
}

// Kupon Durumu Değiştirme
if ($action === 'toggle' && $id > 0) {
    try {
        $stmt = $db->prepare("UPDATE coupons SET is_active = NOT is_active WHERE id = ?");
        $stmt->execute([$id]);
        setFlash('success', 'Kupon durumu güncellendi.');
    } catch (PDOException $e) {
        setFlash('error', 'Durum güncellenirken hata oluştu.');
    }
    redirect(SITE_URL . '/admin/kuponlar.php');
    exit;
}

// Form verileri için varsayılan değerler
$formData = [
    'code' => '',
    'description' => '',
    'discount_type' => 'percent',
    'discount_value' => '',
    'min_amount' => '',
    'max_amount' => '',
    'max_discount' => '',
    'usage_limit' => '',
    'usage_limit_per_ip' => 1,
    'starts_at' => '',
    'expires_at' => '',
    'is_active' => 1
];
$editId = 0;

// Düzenleme için kupon bilgisi - POST'tan önce yükle
$editCoupon = null;
if ($action === 'edit' && $id > 0) {
    $stmt = $db->prepare("SELECT * FROM coupons WHERE id = ?");
    $stmt->execute([$id]);
    $editCoupon = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$editCoupon) {
        setFlash('error', 'Kupon bulunamadı.');
        redirect(SITE_URL . '/admin/kuponlar.php');
        exit;
    }
    
    // Düzenleme modunda form verilerini doldur
    $formData = [
        'code' => $editCoupon['code'],
        'description' => $editCoupon['description'] ?? '',
        'discount_type' => $editCoupon['discount_type'],
        'discount_value' => $editCoupon['discount_value'],
        'min_amount' => $editCoupon['min_amount'],
        'max_amount' => $editCoupon['max_amount'],
        'max_discount' => $editCoupon['max_discount'],
        'usage_limit' => $editCoupon['usage_limit'],
        'usage_limit_per_ip' => $editCoupon['usage_limit_per_ip'] ?? 1,
        'starts_at' => $editCoupon['starts_at'],
        'expires_at' => $editCoupon['expires_at'],
        'is_active' => $editCoupon['is_active']
    ];
    $editId = $editCoupon['id'];
}

// Kupon Ekleme/Düzenleme
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Form verilerini al ve sakla
    $formData = [
        'code' => strtoupper(trim($_POST['code'] ?? '')),
        'description' => trim($_POST['description'] ?? ''),
        'discount_type' => $_POST['discount_type'] ?? 'percent',
        'discount_value' => $_POST['discount_value'] ?? '',
        'min_amount' => $_POST['min_amount'] ?? '',
        'max_amount' => $_POST['max_amount'] ?? '',
        'max_discount' => $_POST['max_discount'] ?? '',
        'usage_limit' => $_POST['usage_limit'] ?? '',
        'usage_limit_per_ip' => $_POST['usage_limit_per_ip'] ?? 1,
        'starts_at' => $_POST['starts_at'] ?? '',
        'expires_at' => $_POST['expires_at'] ?? '',
        'is_active' => isset($_POST['is_active']) ? 1 : 0
    ];
    $editId = (int)($_POST['edit_id'] ?? 0);
    
    // Veritabanı için değerleri hazırla
    $code = $formData['code'];
    $discountType = $formData['discount_type'];
    $discountValue = floatval($formData['discount_value']);
    $minAmount = !empty($formData['min_amount']) ? floatval($formData['min_amount']) : null;
    $maxAmount = !empty($formData['max_amount']) ? floatval($formData['max_amount']) : null;
    $maxDiscount = !empty($formData['max_discount']) ? floatval($formData['max_discount']) : null;
    $usageLimit = !empty($formData['usage_limit']) ? (int)$formData['usage_limit'] : null;
    $usageLimitPerIp = !empty($formData['usage_limit_per_ip']) ? (int)$formData['usage_limit_per_ip'] : 1;
    $startsAt = !empty($formData['starts_at']) ? $formData['starts_at'] : null;
    $expiresAt = !empty($formData['expires_at']) ? $formData['expires_at'] : null;
    $isActive = $formData['is_active'];
    $description = $formData['description'];
    
    $errors = [];
    
    if (empty($code)) {
        $errors[] = 'Kupon kodu zorunludur.';
    } elseif (strlen($code) < 3 || strlen($code) > 50) {
        $errors[] = 'Kupon kodu 3-50 karakter arasında olmalıdır.';
    }
    
    if ($discountValue <= 0) {
        $errors[] = 'İndirim değeri 0\'dan büyük olmalıdır.';
    }
    
    if ($discountType === 'percent' && $discountValue > 100) {
        $errors[] = 'Yüzde indirim 100\'den büyük olamaz.';
    }
    
    if (empty($errors)) {
        $checkSql = "SELECT id FROM coupons WHERE code = ?";
        $checkParams = [$code];
        
        if ($editId > 0) {
            $checkSql .= " AND id != ?";
            $checkParams[] = $editId;
        }
        
        $checkStmt = $db->prepare($checkSql);
        $checkStmt->execute($checkParams);
        
        if ($checkStmt->fetch()) {
            $errors[] = 'Bu kupon kodu zaten kullanılıyor.';
        }
    }
    
    if (empty($errors)) {
        try {
            if ($editId > 0) {
                $stmt = $db->prepare("
                    UPDATE coupons SET 
                        code = ?, discount_type = ?, discount_value = ?, min_amount = ?, max_amount = ?,
                        max_discount = ?, usage_limit = ?, usage_limit_per_ip = ?, starts_at = ?, 
                        expires_at = ?, is_active = ?, description = ?
                    WHERE id = ?
                ");
                $stmt->execute([
                    $code, $discountType, $discountValue, $minAmount, $maxAmount,
                    $maxDiscount, $usageLimit, $usageLimitPerIp, $startsAt,
                    $expiresAt, $isActive, $description, $editId
                ]);
                setFlash('success', 'Kupon başarıyla güncellendi.');
            } else {
                $stmt = $db->prepare("
                    INSERT INTO coupons (code, discount_type, discount_value, min_amount, max_amount, 
                        max_discount, usage_limit, usage_limit_per_ip, starts_at, expires_at, is_active, description)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $code, $discountType, $discountValue, $minAmount, $maxAmount,
                    $maxDiscount, $usageLimit, $usageLimitPerIp, $startsAt,
                    $expiresAt, $isActive, $description
                ]);
                setFlash('success', 'Kupon başarıyla eklendi.');
            }
            redirect(SITE_URL . '/admin/kuponlar.php');
            exit;
        } catch (PDOException $e) {
            setFlash('error', 'Veritabanı hatası: ' . $e->getMessage());
        }
    } else {
        setFlash('error', implode('<br>', $errors));
    }
}

// Kuponları listele
try {
    $coupons = $db->query("
        SELECT c.*, 
               (SELECT COUNT(*) FROM coupon_usage WHERE coupon_id = c.id) as total_usage
        FROM coupons c 
        ORDER BY c.created_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $coupons = [];
}

function generateCouponCode($length = 8) {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $code;
}

// Yeni kupon için kod üret (sadece ekleme modunda)
$newCode = empty($formData['code']) ? generateCouponCode() : $formData['code'];

$adminPageTitle = 'Kupon Kodları';
require_once __DIR__ . '/header.php';

// İstatistikler
$totalCoupons = count($coupons);
$activeCouponsCount = count(array_filter($coupons, fn($c) => $c['is_active'] == 1));
$expiredCoupons = count(array_filter($coupons, fn($c) => $c['expires_at'] && strtotime($c['expires_at']) < time()));
$totalUsage = array_sum(array_column($coupons, 'usage_count'));
?>

<style>
/* ==================== KUPON SAYFA STİLLERİ ==================== */

/* İstatistik Kartları */
.cp-stats {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 24px;
}

.cp-stat-card {
    background: #1e293b;
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 14px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 16px;
}

.cp-stat-icon {
    width: 52px;
    height: 52px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    flex-shrink: 0;
}

.cp-stat-icon.purple { background: rgba(139, 92, 246, 0.2); color: #a78bfa; }
.cp-stat-icon.green { background: rgba(16, 185, 129, 0.2); color: #34d399; }
.cp-stat-icon.yellow { background: rgba(245, 158, 11, 0.2); color: #fbbf24; }
.cp-stat-icon.blue { background: rgba(59, 130, 246, 0.2); color: #60a5fa; }

.cp-stat-info h3 {
    font-size: 26px;
    font-weight: 800;
    margin: 0 0 2px;
    color: #f1f5f9;
}

.cp-stat-info span {
    font-size: 13px;
    color: #94a3b8;
}

/* Ana Grid */
.cp-grid {
    display: grid;
    grid-template-columns: 420px 1fr;
    gap: 24px;
    align-items: start;
}

/* Kart Stilleri */
.cp-card {
    background: #1e293b;
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 16px;
    overflow: hidden;
}

.cp-card-header {
    padding: 18px 22px;
    border-bottom: 1px solid rgba(255,255,255,0.08);
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: rgba(0,0,0,0.2);
}

.cp-card-title {
    font-size: 16px;
    font-weight: 700;
    margin: 0;
    color: #f1f5f9;
    display: flex;
    align-items: center;
    gap: 10px;
}

.cp-card-title i {
    color: #a78bfa;
}

.cp-card-badge {
    font-size: 13px;
    color: #94a3b8;
}

.cp-card-body {
    padding: 22px;
}

/* Form Bölümleri */
.cp-form-section {
    background: rgba(0,0,0,0.25);
    border: 1px solid rgba(255,255,255,0.06);
    border-radius: 12px;
    padding: 18px;
    margin-bottom: 18px;
}

.cp-form-section:last-of-type {
    margin-bottom: 0;
}

.cp-form-title {
    font-size: 13px;
    font-weight: 700;
    color: #e2e8f0;
    margin-bottom: 14px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.cp-form-title i {
    color: #a78bfa;
    font-size: 14px;
}

.cp-form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 14px;
}

.cp-form-group {
    margin-bottom: 14px;
}

.cp-form-group:last-child {
    margin-bottom: 0;
}

.cp-form-label {
    display: block;
    font-size: 13px;
    font-weight: 600;
    color: #cbd5e1;
    margin-bottom: 6px;
}

.cp-form-input {
    width: 100%;
    padding: 11px 14px;
    background: #0f172a;
    border: 1px solid rgba(255,255,255,0.1);
    border-radius: 8px;
    color: #f1f5f9;
    font-size: 14px;
    transition: all 0.2s;
}

.cp-form-input:focus {
    outline: none;
    border-color: #a78bfa;
    box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.15);
}

.cp-form-input::placeholder {
    color: #64748b;
}

.cp-form-input[type="datetime-local"] {
    color-scheme: dark;
}

.cp-form-select {
    width: 100%;
    padding: 11px 14px;
    background: #0f172a;
    border: 1px solid rgba(255,255,255,0.1);
    border-radius: 8px;
    color: #f1f5f9;
    font-size: 14px;
    cursor: pointer;
}

.cp-form-select:focus {
    outline: none;
    border-color: #a78bfa;
}

.cp-form-hint {
    font-size: 11px;
    color: #64748b;
    margin-top: 4px;
}

/* Input Group */
.cp-input-group {
    display: flex;
}

.cp-input-group .cp-form-input {
    border-radius: 8px 0 0 8px;
    border-right: none;
}

.cp-input-suffix {
    padding: 11px 14px;
    background: #334155;
    border: 1px solid rgba(255,255,255,0.1);
    border-left: none;
    border-radius: 0 8px 8px 0;
    color: #94a3b8;
    font-size: 13px;
    font-weight: 600;
    display: flex;
    align-items: center;
}

.cp-generate-btn {
    padding: 11px 16px;
    background: #334155;
    border: 1px solid rgba(255,255,255,0.1);
    border-left: none;
    border-radius: 0 8px 8px 0;
    color: #94a3b8;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 6px;
    transition: all 0.2s;
    white-space: nowrap;
}

.cp-generate-btn:hover {
    background: #a78bfa;
    color: #fff;
}

/* Checkbox */
.cp-checkbox {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px 16px;
    background: #0f172a;
    border: 1px solid rgba(255,255,255,0.1);
    border-radius: 10px;
    cursor: pointer;
    margin-top: 18px;
    transition: all 0.2s;
}

.cp-checkbox:hover {
    border-color: #a78bfa;
}

.cp-checkbox input {
    width: 20px;
    height: 20px;
    accent-color: #a78bfa;
    cursor: pointer;
    flex-shrink: 0;
}

.cp-checkbox-label strong {
    display: block;
    color: #f1f5f9;
    font-size: 14px;
    margin-bottom: 2px;
}

.cp-checkbox-label span {
    font-size: 12px;
    color: #64748b;
}

/* Submit Button */
.cp-submit-btn {
    width: 100%;
    padding: 14px 20px;
    background: linear-gradient(135deg, #6366f1, #8b5cf6);
    border: none;
    border-radius: 10px;
    color: #fff;
    font-size: 15px;
    font-weight: 700;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    margin-top: 20px;
    transition: all 0.2s;
}

.cp-submit-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(99, 102, 241, 0.4);
}

.cp-cancel-btn {
    padding: 8px 14px;
    background: #334155;
    border: 1px solid rgba(255,255,255,0.1);
    border-radius: 8px;
    color: #94a3b8;
    font-size: 12px;
    font-weight: 600;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.2s;
}

.cp-cancel-btn:hover {
    background: #ef4444;
    border-color: #ef4444;
    color: #fff;
}

/* Kupon Listesi */
.cp-list {
    display: flex;
    flex-direction: column;
}

.cp-list-empty {
    text-align: center;
    padding: 50px 20px;
}

.cp-list-empty i {
    font-size: 48px;
    color: #334155;
    margin-bottom: 16px;
}

.cp-list-empty h4 {
    font-size: 17px;
    color: #e2e8f0;
    margin: 0 0 8px;
}

.cp-list-empty p {
    font-size: 14px;
    color: #64748b;
    margin: 0;
}

/* Kupon Kartı */
.cp-item {
    padding: 18px 22px;
    border-bottom: 1px solid rgba(255,255,255,0.06);
    transition: background 0.2s;
}

.cp-item:hover {
    background: rgba(139, 92, 246, 0.03);
}

.cp-item:last-child {
    border-bottom: none;
}

.cp-item-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 14px;
    gap: 12px;
    flex-wrap: wrap;
}

.cp-code {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    padding: 8px 14px;
    background: rgba(139, 92, 246, 0.15);
    border: 1px dashed rgba(139, 92, 246, 0.4);
    border-radius: 8px;
    font-family: 'Monaco', 'Consolas', monospace;
    font-size: 15px;
    font-weight: 700;
    color: #c4b5fd;
    letter-spacing: 1px;
}

.cp-code-copy {
    background: none;
    border: none;
    color: #94a3b8;
    cursor: pointer;
    padding: 4px;
    font-size: 13px;
    transition: color 0.2s;
    display: flex;
    align-items: center;
}

.cp-code-copy:hover {
    color: #c4b5fd;
}

.cp-status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.cp-status.active {
    background: rgba(16, 185, 129, 0.15);
    color: #34d399;
}

.cp-status.inactive {
    background: rgba(239, 68, 68, 0.15);
    color: #f87171;
}

.cp-status.expired {
    background: rgba(107, 114, 128, 0.2);
    color: #9ca3af;
}

.cp-status.pending {
    background: rgba(245, 158, 11, 0.15);
    color: #fbbf24;
}

.cp-status.limit {
    background: rgba(239, 68, 68, 0.15);
    color: #f87171;
}

.cp-item-body {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 14px;
}

.cp-info-block h5 {
    font-size: 10px;
    font-weight: 700;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin: 0 0 6px;
}

.cp-discount {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 700;
}

.cp-discount.percent {
    background: rgba(139, 92, 246, 0.15);
    color: #c4b5fd;
}

.cp-discount.fixed {
    background: rgba(59, 130, 246, 0.15);
    color: #93c5fd;
}

.cp-info-text {
    font-size: 13px;
    color: #cbd5e1;
    line-height: 1.5;
}

.cp-info-text strong {
    color: #f1f5f9;
}

.cp-info-text .muted {
    color: #64748b;
}

.cp-info-text .danger {
    color: #f87171;
}

.cp-item-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-top: 14px;
    border-top: 1px solid rgba(255,255,255,0.05);
    gap: 12px;
    flex-wrap: wrap;
}

.cp-desc {
    font-size: 12px;
    color: #64748b;
    font-style: italic;
    flex: 1;
}

.cp-actions {
    display: flex;
    gap: 8px;
}

.cp-action-btn {
    width: 36px;
    height: 36px;
    border: 1px solid rgba(255,255,255,0.1);
    background: #0f172a;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #94a3b8;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    font-size: 14px;
}

.cp-action-btn:hover {
    border-color: #a78bfa;
    color: #a78bfa;
    background: rgba(139, 92, 246, 0.1);
}

.cp-action-btn.toggle-on {
    background: rgba(16, 185, 129, 0.1);
    border-color: rgba(16, 185, 129, 0.3);
    color: #34d399;
}

.cp-action-btn.toggle-off {
    background: rgba(239, 68, 68, 0.1);
    border-color: rgba(239, 68, 68, 0.3);
    color: #f87171;
}

.cp-action-btn.delete:hover {
    background: rgba(239, 68, 68, 0.15);
    border-color: #ef4444;
    color: #f87171;
}

/* Responsive */
@media (max-width: 1199px) {
    .cp-stats {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .cp-grid {
        grid-template-columns: 1fr;
    }
    
    .cp-item-body {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 767px) {
    .cp-stats {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    
    .cp-stat-card {
        padding: 16px;
    }
    
    .cp-stat-icon {
        width: 46px;
        height: 46px;
        font-size: 20px;
    }
    
    .cp-stat-info h3 {
        font-size: 22px;
    }
    
    .cp-card-header {
        padding: 14px 16px;
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }
    
    .cp-card-body {
        padding: 16px;
    }
    
    .cp-form-section {
        padding: 14px;
    }
    
    .cp-form-row {
        grid-template-columns: 1fr;
    }
    
    .cp-item {
        padding: 16px;
    }
    
    .cp-item-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .cp-item-body {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    
    .cp-item-footer {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .cp-actions {
        width: 100%;
        justify-content: flex-end;
    }
}

@media (max-width: 480px) {
    .cp-code {
        font-size: 13px;
        padding: 6px 10px;
    }
    
    .cp-generate-btn span {
        display: none;
    }
    
    .cp-generate-btn {
        padding: 11px 14px;
    }
}
</style>

<!-- İstatistikler -->
<div class="cp-stats">
    <div class="cp-stat-card">
        <div class="cp-stat-icon purple">
            <i class="fas fa-ticket-alt"></i>
        </div>
        <div class="cp-stat-info">
            <h3><?php echo $totalCoupons; ?></h3>
            <span>Toplam Kupon</span>
        </div>
    </div>
    <div class="cp-stat-card">
        <div class="cp-stat-icon green">
            <i class="fas fa-check-circle"></i>
        </div>
        <div class="cp-stat-info">
            <h3><?php echo $activeCouponsCount; ?></h3>
            <span>Aktif Kupon</span>
        </div>
    </div>
    <div class="cp-stat-card">
        <div class="cp-stat-icon yellow">
            <i class="fas fa-clock"></i>
        </div>
        <div class="cp-stat-info">
            <h3><?php echo $expiredCoupons; ?></h3>
            <span>Süresi Dolan</span>
        </div>
    </div>
    <div class="cp-stat-card">
        <div class="cp-stat-icon blue">
            <i class="fas fa-receipt"></i>
        </div>
        <div class="cp-stat-info">
            <h3><?php echo $totalUsage; ?></h3>
            <span>Toplam Kullanım</span>
        </div>
    </div>
</div>

<!-- Ana İçerik -->
<div class="cp-grid">
    
    <!-- Sol: Form -->
    <div class="cp-card">
        <div class="cp-card-header">
            <h5 class="cp-card-title">
                <i class="fas fa-<?php echo $editCoupon ? 'edit' : 'plus-circle'; ?>"></i>
                <?php echo $editCoupon ? 'Kuponu Düzenle' : 'Yeni Kupon Ekle'; ?>
            </h5>
            <?php if ($editCoupon): ?>
            <a href="<?php echo SITE_URL; ?>/admin/kuponlar.php" class="cp-cancel-btn">
                <i class="fas fa-times"></i> İptal
            </a>
            <?php endif; ?>
        </div>
        <div class="cp-card-body">
            <form method="POST" action="">
                <input type="hidden" name="edit_id" value="<?php echo $editId; ?>">
                
                <!-- Kupon Bilgileri -->
                <div class="cp-form-section">
                    <div class="cp-form-title">
                        <i class="fas fa-tag"></i> Kupon Bilgileri
                    </div>
                    
                    <div class="cp-form-group">
                        <label class="cp-form-label">Kupon Kodu *</label>
                        <div class="cp-input-group">
                            <input type="text" class="cp-form-input" name="code" id="couponCode" 
                                   value="<?php echo clean($editId > 0 ? $formData['code'] : $newCode); ?>" 
                                   placeholder="INDIRIM20" required maxlength="50" style="text-transform: uppercase;">
                            <button type="button" class="cp-generate-btn" onclick="generateCode()">
                                <i class="fas fa-sync-alt"></i> <span>Üret</span>
                            </button>
                        </div>
                        <div class="cp-form-hint">3-50 karakter, otomatik büyük harfe çevrilir</div>
                    </div>
                    
                    <div class="cp-form-group">
                        <label class="cp-form-label">Açıklama (Opsiyonel)</label>
                        <input type="text" class="cp-form-input" name="description" 
                               value="<?php echo clean($formData['description']); ?>" 
                               placeholder="Admin notları için...">
                    </div>
                </div>
                
                <!-- İndirim Ayarları -->
                <div class="cp-form-section">
                    <div class="cp-form-title">
                        <i class="fas fa-percent"></i> İndirim Ayarları
                    </div>
                    
                    <div class="cp-form-row">
                        <div class="cp-form-group">
                            <label class="cp-form-label">İndirim Tipi *</label>
                            <select class="cp-form-select" name="discount_type" id="discountType" onchange="toggleMaxDiscount()">
                                <option value="percent" <?php echo $formData['discount_type'] === 'percent' ? 'selected' : ''; ?>>Yüzde (%)</option>
                                <option value="fixed" <?php echo $formData['discount_type'] === 'fixed' ? 'selected' : ''; ?>>Sabit Tutar (₺)</option>
                            </select>
                        </div>
                        <div class="cp-form-group">
                            <label class="cp-form-label">İndirim Değeri *</label>
                            <div class="cp-input-group">
                                <input type="number" class="cp-form-input" name="discount_value" 
                                       value="<?php echo clean($formData['discount_value']); ?>" 
                                       placeholder="10" required min="0.01" step="0.01">
                                <span class="cp-input-suffix" id="discountSuffix"><?php echo $formData['discount_type'] === 'fixed' ? '₺' : '%'; ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="cp-form-group" id="maxDiscountRow" style="<?php echo $formData['discount_type'] === 'fixed' ? 'display:none' : ''; ?>">
                        <label class="cp-form-label">Maksimum İndirim Tutarı</label>
                        <div class="cp-input-group">
                            <input type="number" class="cp-form-input" name="max_discount" 
                                   value="<?php echo clean($formData['max_discount']); ?>" 
                                   placeholder="50" min="0" step="0.01">
                            <span class="cp-input-suffix">₺</span>
                        </div>
                        <div class="cp-form-hint">Yüzde indiriminde uygulanacak maksimum tutar</div>
                    </div>
                </div>
                
                <!-- Limitler -->
                <div class="cp-form-section">
                    <div class="cp-form-title">
                        <i class="fas fa-sliders-h"></i> Kullanım Limitleri
                    </div>
                    
                    <div class="cp-form-row">
                        <div class="cp-form-group">
                            <label class="cp-form-label">Min. Sipariş Tutarı</label>
                            <div class="cp-input-group">
                                <input type="number" class="cp-form-input" name="min_amount" 
                                       value="<?php echo clean($formData['min_amount']); ?>" 
                                       placeholder="0" min="0" step="0.01">
                                <span class="cp-input-suffix">₺</span>
                            </div>
                        </div>
                        <div class="cp-form-group">
                            <label class="cp-form-label">Max. Sipariş Tutarı</label>
                            <div class="cp-input-group">
                                <input type="number" class="cp-form-input" name="max_amount" 
                                       value="<?php echo clean($formData['max_amount']); ?>" 
                                       placeholder="∞" min="0" step="0.01">
                                <span class="cp-input-suffix">₺</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="cp-form-row">
                        <div class="cp-form-group">
                            <label class="cp-form-label">Toplam Kullanım Limiti</label>
                            <input type="number" class="cp-form-input" name="usage_limit" 
                                   value="<?php echo clean($formData['usage_limit']); ?>" 
                                   placeholder="Sınırsız" min="1">
                        </div>
                        <div class="cp-form-group">
                            <label class="cp-form-label">IP Başına Limit</label>
                            <input type="number" class="cp-form-input" name="usage_limit_per_ip" 
                                   value="<?php echo clean($formData['usage_limit_per_ip']); ?>" 
                                   placeholder="1" min="1">
                        </div>
                    </div>
                </div>
                
                <!-- Tarih -->
                <div class="cp-form-section">
                    <div class="cp-form-title">
                        <i class="fas fa-calendar-alt"></i> Geçerlilik Tarihi
                    </div>
                    
                    <div class="cp-form-row">
                        <div class="cp-form-group">
                            <label class="cp-form-label">Başlangıç Tarihi</label>
                            <input type="datetime-local" class="cp-form-input" name="starts_at" 
                                   value="<?php echo $formData['starts_at'] ? date('Y-m-d\TH:i', strtotime($formData['starts_at'])) : ''; ?>">
                        </div>
                        <div class="cp-form-group">
                            <label class="cp-form-label">Bitiş Tarihi</label>
                            <input type="datetime-local" class="cp-form-input" name="expires_at" 
                                   value="<?php echo $formData['expires_at'] ? date('Y-m-d\TH:i', strtotime($formData['expires_at'])) : ''; ?>">
                        </div>
                    </div>
                </div>
                
                <!-- Durum -->
                <label class="cp-checkbox">
                    <input type="checkbox" name="is_active" value="1" 
                           <?php echo $formData['is_active'] == 1 ? 'checked' : ''; ?>>
                    <div class="cp-checkbox-label">
                        <strong>Kupon Aktif</strong>
                        <span>Kullanıcılar bu kuponu kullanabilir</span>
                    </div>
                </label>
                
                <button type="submit" class="cp-submit-btn">
                    <i class="fas fa-<?php echo $editCoupon ? 'save' : 'plus'; ?>"></i>
                    <?php echo $editCoupon ? 'Kuponu Güncelle' : 'Kupon Ekle'; ?>
                </button>
            </form>
        </div>
    </div>
    
    <!-- Sağ: Liste -->
    <div class="cp-card">
        <div class="cp-card-header">
            <h5 class="cp-card-title">
                <i class="fas fa-list"></i>
                Kupon Listesi
            </h5>
            <span class="cp-card-badge"><?php echo $totalCoupons; ?> kupon</span>
        </div>
        
        <div class="cp-list">
            <?php if (empty($coupons)): ?>
            <div class="cp-list-empty">
                <i class="fas fa-ticket-alt"></i>
                <h4>Henüz kupon yok</h4>
                <p>Soldaki formu kullanarak yeni bir kupon ekleyin.</p>
            </div>
            <?php else: ?>
                <?php foreach ($coupons as $coupon): 
                    $isExpired = $coupon['expires_at'] && strtotime($coupon['expires_at']) < time();
                    $isNotStarted = $coupon['starts_at'] && strtotime($coupon['starts_at']) > time();
                    $isLimitReached = $coupon['usage_limit'] && $coupon['usage_count'] >= $coupon['usage_limit'];
                ?>
                <div class="cp-item">
                    <div class="cp-item-header">
                        <div class="cp-code">
                            <?php echo clean($coupon['code']); ?>
                            <button type="button" class="cp-code-copy" onclick="copyCode('<?php echo clean($coupon['code']); ?>', this)" title="Kopyala">
                                <i class="fas fa-copy"></i>
                            </button>
                        </div>
                        
                        <?php if ($isExpired): ?>
                            <span class="cp-status expired"><i class="fas fa-clock"></i> Süresi Doldu</span>
                        <?php elseif ($isNotStarted): ?>
                            <span class="cp-status pending"><i class="fas fa-hourglass-start"></i> Başlamadı</span>
                        <?php elseif ($isLimitReached): ?>
                            <span class="cp-status limit"><i class="fas fa-ban"></i> Limit Doldu</span>
                        <?php elseif ($coupon['is_active']): ?>
                            <span class="cp-status active"><i class="fas fa-check"></i> Aktif</span>
                        <?php else: ?>
                            <span class="cp-status inactive"><i class="fas fa-times"></i> Pasif</span>
                        <?php endif; ?>
                    </div>
                    
                    <div class="cp-item-body">
                        <div class="cp-info-block">
                            <h5>İndirim</h5>
                            <span class="cp-discount <?php echo $coupon['discount_type']; ?>">
                                <?php if ($coupon['discount_type'] === 'percent'): ?>
                                    <i class="fas fa-percent"></i> %<?php echo rtrim(rtrim(number_format($coupon['discount_value'], 2, ',', '.'), '0'), ','); ?>
                                <?php else: ?>
                                    <?php echo number_format($coupon['discount_value'], 2, ',', '.'); ?>₺
                                <?php endif; ?>
                            </span>
                            <?php if ($coupon['max_discount']): ?>
                            <div class="cp-info-text muted" style="margin-top:4px;">Max: <?php echo number_format($coupon['max_discount'], 2, ',', '.'); ?>₺</div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="cp-info-block">
                            <h5>Tutar Limiti</h5>
                            <div class="cp-info-text">
                                <?php if ($coupon['min_amount']): ?>
                                Min: <strong><?php echo number_format($coupon['min_amount'], 2, ',', '.'); ?>₺</strong><br>
                                <?php endif; ?>
                                <?php if ($coupon['max_amount']): ?>
                                Max: <strong><?php echo number_format($coupon['max_amount'], 2, ',', '.'); ?>₺</strong>
                                <?php endif; ?>
                                <?php if (!$coupon['min_amount'] && !$coupon['max_amount']): ?>
                                <span class="muted">Limit yok</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="cp-info-block">
                            <h5>Kullanım</h5>
                            <div class="cp-info-text">
                                <strong><?php echo $coupon['usage_count']; ?></strong> / <?php echo $coupon['usage_limit'] ?: '∞'; ?>
                                <br>IP: <strong><?php echo $coupon['usage_limit_per_ip'] ?: '∞'; ?></strong>
                            </div>
                        </div>
                        
                        <div class="cp-info-block">
                            <h5>Geçerlilik</h5>
                            <div class="cp-info-text">
                                <?php if ($coupon['starts_at']): ?>
                                <i class="fas fa-play" style="font-size:10px;color:#64748b;"></i> <?php echo date('d.m.Y', strtotime($coupon['starts_at'])); ?><br>
                                <?php endif; ?>
                                <?php if ($coupon['expires_at']): ?>
                                <span class="<?php echo $isExpired ? 'danger' : ''; ?>">
                                    <i class="fas fa-stop" style="font-size:10px;color:#64748b;"></i> <?php echo date('d.m.Y', strtotime($coupon['expires_at'])); ?>
                                </span>
                                <?php else: ?>
                                <span class="muted"><i class="fas fa-infinity" style="font-size:10px;"></i> Süresiz</span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <div class="cp-item-footer">
                        <div class="cp-desc">
                            <?php echo $coupon['description'] ? clean($coupon['description']) : '—'; ?>
                        </div>
                        <div class="cp-actions">
                            <a href="<?php echo SITE_URL; ?>/admin/kuponlar.php?action=edit&id=<?php echo $coupon['id']; ?>" 
                               class="cp-action-btn" title="Düzenle">
                                <i class="fas fa-edit"></i>
                            </a>
                            <a href="<?php echo SITE_URL; ?>/admin/kuponlar.php?action=toggle&id=<?php echo $coupon['id']; ?>" 
                               class="cp-action-btn <?php echo $coupon['is_active'] ? 'toggle-on' : 'toggle-off'; ?>" 
                               title="<?php echo $coupon['is_active'] ? 'Pasif Yap' : 'Aktif Yap'; ?>">
                                <i class="fas fa-<?php echo $coupon['is_active'] ? 'toggle-on' : 'toggle-off'; ?>"></i>
                            </a>
                            <a href="<?php echo SITE_URL; ?>/admin/kuponlar.php?action=delete&id=<?php echo $coupon['id']; ?>" 
                               class="cp-action-btn delete" 
                               onclick="return confirm('Bu kuponu silmek istediğinize emin misiniz?')" title="Sil">
                                <i class="fas fa-trash"></i>
                            </a>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function generateCode() {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let code = '';
    for (let i = 0; i < 8; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    document.getElementById('couponCode').value = code;
}

function toggleMaxDiscount() {
    const type = document.getElementById('discountType').value;
    const suffix = document.getElementById('discountSuffix');
    const maxRow = document.getElementById('maxDiscountRow');
    
    if (type === 'percent') {
        suffix.textContent = '%';
        maxRow.style.display = 'block';
    } else {
        suffix.textContent = '₺';
        maxRow.style.display = 'none';
    }
}

function copyCode(code, btn) {
    navigator.clipboard.writeText(code).then(() => {
        const icon = btn.querySelector('i');
        icon.className = 'fas fa-check';
        btn.style.color = '#34d399';
        setTimeout(() => {
            icon.className = 'fas fa-copy';
            btn.style.color = '';
        }, 1500);
    });
}

document.addEventListener('DOMContentLoaded', function() {
    // Kupon kodu otomatik büyük harf
    document.getElementById('couponCode').addEventListener('input', function() {
        this.value = this.value.toUpperCase();
    });
});
</script>

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