<?php
/**
 * Banner Yönetimi Sayfası
 * Uygulama içi banner yönetimi
 */

session_start();
require_once __DIR__ . '/config/database.php';

$page_title = 'Banner Yönetimi';

// Admin session kontrolü
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

// Database bağlantısı
$database = new Database();
$db = $database->getConnection();

// Form işleme
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'add_banner':
                    $title = trim($_POST['title'] ?? '');
                    $description = trim($_POST['description'] ?? '');
                    $banner_type = $_POST['banner_type'] ?? 'verse_top';
                    $click_url = trim($_POST['click_url'] ?? '');
                    $start_date = $_POST['start_date'] ?? null;
                    $end_date = $_POST['end_date'] ?? null;
                    $is_active = isset($_POST['is_active']) ? 1 : 0;
                    
                    if (empty($title)) {
                        throw new Exception("Banner başlığı gereklidir");
                    }
                    
                    // Görsel yükleme
                    $image_path = null;
                    if (isset($_FILES['banner_image']) && $_FILES['banner_image']['error'] === UPLOAD_ERR_OK) {
                        $upload_dir = 'uploads/banners/';
                        if (!is_dir($upload_dir)) {
                            mkdir($upload_dir, 0755, true);
                        }
                        
                        $file_info = pathinfo($_FILES['banner_image']['name']);
                        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                        $file_extension = strtolower($file_info['extension']);
                        
                        if (!in_array($file_extension, $allowed_extensions)) {
                            throw new Exception("Sadece JPG, PNG, GIF ve WebP formatları desteklenir");
                        }
                        
                        // Dosya boyutu kontrolü (2MB)
                        if ($_FILES['banner_image']['size'] > 2 * 1024 * 1024) {
                            throw new Exception("Dosya boyutu 2MB'dan küçük olmalıdır");
                        }
                        
                        // Görsel boyutu kontrolü (728x90 için)
                        $image_info = getimagesize($_FILES['banner_image']['tmp_name']);
                        if ($image_info === false) {
                            throw new Exception("Geçersiz görsel dosyası");
                        }
                        
                        $width = $image_info[0];
                        $height = $image_info[1];
                        
                        // 728x90 boyut kontrolü (tolerans %10)
                        if (abs($width - 728) > 73 || abs($height - 90) > 9) {
                            throw new Exception("Banner boyutu 728x90 piksel olmalıdır. (Mevcut: {$width}x{$height})");
                        }
                        
                        $filename = uniqid() . '_' . time() . '.' . $file_extension;
                        $target_path = $upload_dir . $filename;
                        
                        if (move_uploaded_file($_FILES['banner_image']['tmp_name'], $target_path)) {
                            $image_path = 'banners/' . $filename;
                        } else {
                            throw new Exception("Dosya yüklenirken hata oluştu");
                        }
                    } else {
                        throw new Exception("Banner görseli gereklidir");
                    }
                    
                    $stmt = $db->prepare("
                        INSERT INTO app_banners (title, description, image_path, banner_type, click_url, start_date, end_date, is_active, created_by) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    
                    if ($stmt->execute([$title, $description, $image_path, $banner_type, $click_url, $start_date, $end_date, $is_active, $_SESSION['admin_id']])) {
                        $_SESSION['success_message'] = 'Banner başarıyla eklendi';
                    } else {
                        throw new Exception("Banner eklenirken hata oluştu");
                    }
                    break;
                    
                case 'toggle_banner':
                    $bannerId = (int)($_POST['banner_id'] ?? 0);
                    $isActive = (int)($_POST['is_active'] ?? 0);
                    
                    if ($bannerId <= 0) {
                        throw new Exception("Geçersiz banner ID");
                    }
                    
                    $stmt = $db->prepare("UPDATE app_banners SET is_active = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                    
                    if ($stmt->execute([$isActive, $bannerId])) {
                        $status = $isActive ? 'aktif' : 'pasif';
                        $_SESSION['success_message'] = "Banner başarıyla $status yapıldı";
                    } else {
                        throw new Exception("Banner durumu değiştirilirken hata oluştu");
                    }
                    break;
                    
                case 'delete_banner':
                    $bannerId = (int)($_POST['banner_id'] ?? 0);
                    
                    if ($bannerId <= 0) {
                        throw new Exception("Geçersiz banner ID");
                    }
                    
                    // Önce görseli sil
                    $stmt = $db->prepare("SELECT image_path FROM app_banners WHERE id = ?");
                    $stmt->execute([$bannerId]);
                    $banner = $stmt->fetch();
                    
                    if ($banner && !empty($banner['image_path'])) {
                        $image_path = 'uploads/' . $banner['image_path'];
                        if (file_exists($image_path)) {
                            unlink($image_path);
                        }
                    }
                    
                    $stmt = $db->prepare("DELETE FROM app_banners WHERE id = ?");
                    
                    if ($stmt->execute([$bannerId])) {
                        $_SESSION['success_message'] = "Banner başarıyla silindi";
                    } else {
                        throw new Exception("Banner silinirken hata oluştu");
                    }
                    break;
            }
        }
        
        header('Location: banner-management.php');
        exit();
        
    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
}

// Banner listesini getir
$banners = [];
try {
    $stmt = $db->prepare("
        SELECT b.*, au.full_name as created_by_name 
        FROM app_banners b 
        LEFT JOIN admin_users au ON b.created_by = au.id 
        ORDER BY b.created_at DESC
    ");
    $stmt->execute();
    $banners = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("Banner listesi getirme hatası: " . $e->getMessage());
}

include 'includes/header.php';
?>

<div class="page-header">
    <h2>Banner Yönetimi</h2>
    <p>Uygulama içi banner reklamlarını yönetin</p>
</div>

<!-- Banner Ekleme Formu -->
<div class="card">
    <div class="card-header">
        <h3><i class="fas fa-plus"></i> Yeni Banner Ekle</h3>
    </div>
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data" class="banner-form">
            <input type="hidden" name="action" value="add_banner">
            
            <div class="form-row">
                <div class="form-group">
                    <label for="title">Banner Başlığı *</label>
                    <input type="text" id="title" name="title" class="form-control" required 
                           placeholder="Banner başlığını girin">
                </div>
                
                <div class="form-group">
                    <label for="banner_type">Banner Konumu *</label>
                    <select id="banner_type" name="banner_type" class="form-control" required>
                        <option value="verse_top">Vaktin Ayeti Üstü (728x90)</option>
                        <option value="main_top">Ana Sayfa Üstü (728x90)</option>
                        <option value="content_bottom">İçerik Altı (728x90)</option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <label for="description">Açıklama</label>
                <textarea id="description" name="description" class="form-control" rows="3" 
                          placeholder="Banner açıklaması (isteğe bağlı)"></textarea>
            </div>
            
            <div class="form-group">
                <label for="banner_image">Banner Görseli * (728x90 piksel)</label>
                <div class="file-upload">
                    <input type="file" id="banner_image" name="banner_image" accept="image/*" required>
                    <label for="banner_image" class="file-upload-label">
                        <i class="fas fa-cloud-upload-alt"></i><br>
                        Banner görselini seçin<br>
                        <small>728x90 piksel - JPG, PNG, GIF, WebP - Max 2MB</small>
                    </label>
                </div>
                <img id="imagePreview" class="image-preview" style="display: none; max-width: 728px; height: auto; margin-top: 10px;">
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label for="click_url">Tıklama URL'si</label>
                    <input type="url" id="click_url" name="click_url" class="form-control" 
                           placeholder="https://example.com (isteğe bağlı)">
                </div>
                
                <div class="form-group">
                    <label>
                        <input type="checkbox" name="is_active" value="1" checked>
                        Banner'ı aktif olarak yayınla
                    </label>
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label for="start_date">Başlangıç Tarihi</label>
                    <input type="datetime-local" id="start_date" name="start_date" class="form-control">
                </div>
                
                <div class="form-group">
                    <label for="end_date">Bitiş Tarihi</label>
                    <input type="datetime-local" id="end_date" name="end_date" class="form-control">
                </div>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Banner Ekle
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Banner Listesi -->
<div class="card">
    <div class="card-header">
        <h3><i class="fas fa-list"></i> Mevcut Banner'lar</h3>
    </div>
    <div class="card-body">
        <?php if (!empty($banners)): ?>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Görsel</th>
                            <th>Başlık</th>
                            <th>Konum</th>
                            <th>Durum</th>
                            <th>İstatistik</th>
                            <th>Tarih</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($banners as $banner): ?>
                            <tr>
                                <td>
                                    <img src="uploads/<?php echo htmlspecialchars($banner['image_path']); ?>" 
                                         alt="Banner" style="max-width: 150px; height: auto; border-radius: 4px;">
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($banner['title']); ?></strong>
                                    <?php if (!empty($banner['description'])): ?>
                                        <br><small class="text-muted"><?php echo htmlspecialchars(mb_substr($banner['description'], 0, 50)); ?>...</small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge badge-info">
                                        <?php 
                                        switch($banner['banner_type']) {
                                            case 'verse_top': echo 'Vaktin Ayeti Üstü'; break;
                                            case 'main_top': echo 'Ana Sayfa Üstü'; break;
                                            case 'content_bottom': echo 'İçerik Altı'; break;
                                        }
                                        ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if ($banner['is_active']): ?>
                                        <span class="badge badge-success">Aktif</span>
                                    <?php else: ?>
                                        <span class="badge badge-danger">Pasif</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <small>
                                        <strong>Görüntülenme:</strong> <?php echo number_format($banner['view_count']); ?><br>
                                        <strong>Tıklama:</strong> <?php echo number_format($banner['click_count']); ?>
                                    </small>
                                </td>
                                <td>
                                    <small><?php echo date('d.m.Y H:i', strtotime($banner['created_at'])); ?></small>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <!-- Aktif/Pasif Toggle -->
                                        <form method="POST" style="display: inline;">
                                            <input type="hidden" name="action" value="toggle_banner">
                                            <input type="hidden" name="banner_id" value="<?php echo $banner['id']; ?>">
                                            <input type="hidden" name="is_active" value="<?php echo $banner['is_active'] ? 0 : 1; ?>">
                                            <button type="submit" class="btn btn-sm <?php echo $banner['is_active'] ? 'btn-warning' : 'btn-success'; ?>" 
                                                    title="<?php echo $banner['is_active'] ? 'Pasif Yap' : 'Aktif Yap'; ?>">
                                                <i class="fas <?php echo $banner['is_active'] ? 'fa-pause' : 'fa-play'; ?>"></i>
                                            </button>
                                        </form>
                                        
                                        <!-- Silme -->
                                        <form method="POST" style="display: inline;" 
                                              onsubmit="return confirm('Bu banner\'ı silmek istediğinizden emin misiniz?')">
                                            <input type="hidden" name="action" value="delete_banner">
                                            <input type="hidden" name="banner_id" value="<?php echo $banner['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-danger" title="Sil">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-ad"></i>
                <h3>Henüz banner eklenmemiş</h3>
                <p>İlk banner'ınızı eklemek için yukarıdaki formu kullanın.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
// Görsel önizleme
document.getElementById('banner_image').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('imagePreview');
            preview.src = e.target.result;
            preview.style.display = 'block';
        }
        reader.readAsDataURL(file);
    }
});
</script>

<style>
.banner-form .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
    margin-bottom: 1rem;
}

.form-group {
    margin-bottom: 1rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 600;
    color: #333;
}

.form-group input, .form-group select, .form-group textarea {
    width: 100%;
    padding: 0.75rem;
    border: 2px solid #e1e5e9;
    border-radius: 8px;
    font-size: 0.9rem;
}

.file-upload {
    position: relative;
    display: inline-block;
    width: 100%;
}

.file-upload input[type=file] {
    position: absolute;
    left: -9999px;
}

.file-upload-label {
    display: block;
    padding: 2rem;
    border: 2px dashed #ddd;
    border-radius: 8px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
}

.file-upload-label:hover {
    border-color: #4f46e5;
    background: #f8fafc;
}

.form-actions {
    margin-top: 2rem;
}

.btn {
    padding: 0.75rem 1.5rem;
    border: none;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    transition: all 0.3s;
}

.btn-primary {
    background: linear-gradient(135deg, #4f46e5, #7c3aed);
    color: white;
}

.btn-sm {
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
}

.btn-success {
    background: #10b981;
    color: white;
}

.btn-warning {
    background: #f59e0b;
    color: white;
}

.btn-danger {
    background: #ef4444;
    color: white;
}

.action-buttons {
    display: flex;
    gap: 0.5rem;
}

.empty-state {
    text-align: center;
    padding: 3rem;
    color: #6b7280;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 1rem;
    color: #d1d5db;
}

.badge {
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: 600;
}

.badge-info {
    background: #dbeafe;
    color: #1e40af;
}

.badge-success {
    background: #dcfce7;
    color: #166534;
}

.badge-danger {
    background: #fee2e2;
    color: #991b1b;
}

@media (max-width: 768px) {
    .banner-form .form-row {
        grid-template-columns: 1fr;
    }
    
    .action-buttons {
        flex-direction: column;
    }
}
</style>

<?php include 'includes/footer.php'; ?>
