<?php
session_start();
include 'config.php';

// Admin login control
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: index.php");
    exit;
}

// Handle POST request for adding, updating, or deleting promotions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Handle Add or Update Promotion
    if (isset($_POST['id']) || isset($_POST['delete'])) {
        // Check if it's a delete request
        if (isset($_POST['delete'])) {
            $id = filter_input(INPUT_POST, 'delete', FILTER_VALIDATE_INT);
            if ($id) {
                // Delete promotion from the database
                $stmt = $pdo->prepare("DELETE FROM bonuses WHERE id = :id");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                if ($stmt->execute()) {
                    echo "<script>Swal.fire('Başarılı', 'Promosyon silindi', 'success');</script>";
                } else {
                    echo "<script>Swal.fire('Hata', 'Promosyon silinirken bir hata oluştu', 'error');</script>";
                }
            }
        } else {
            // Add or Update Promotion (Existing code)
            $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
            $title = trim($_POST['title']);
            $description = nl2br(trim($_POST['description'])); // Convert new lines to <br> tags
            $image_url = trim($_POST['image_url']);
            $detail_image_url = trim($_POST['detail_image_url']);
            $terms = nl2br(trim($_POST['terms'])); // Convert new lines to <br> tags
            $max_withdrawal = filter_input(INPUT_POST, 'max_withdrawal', FILTER_VALIDATE_FLOAT);

            if ($title && $description && $image_url && $detail_image_url && $terms && $max_withdrawal !== false) {
                if ($id) {
                    // Update existing promotion
                    $stmt = $pdo->prepare("UPDATE bonuses SET title = :title, description = :description, image_url = :image_url, detail_image_url = :detail_image_url, terms = :terms, max_withdrawal = :max_withdrawal WHERE id = :id");
                    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                } else {
                    // Add new promotion
                    $stmt = $pdo->prepare("INSERT INTO bonuses (title, description, image_url, detail_image_url, terms, max_withdrawal, created_at) VALUES (:title, :description, :image_url, :detail_image_url, :terms, :max_withdrawal, NOW())");
                }

                $stmt->bindParam(':title', $title);
                $stmt->bindParam(':description', $description);
                $stmt->bindParam(':image_url', $image_url);
                $stmt->bindParam(':detail_image_url', $detail_image_url);
                $stmt->bindParam(':terms', $terms);
                $stmt->bindParam(':max_withdrawal', $max_withdrawal);

                if ($stmt->execute()) {
                    echo "<script>Swal.fire('Başarılı', 'Promosyon kaydedildi', 'success');</script>";
                } else {
                    echo "<script>Swal.fire('Hata', 'Promosyon kaydedilirken bir hata oluştu', 'error');</script>";
                }
            } else {
                echo "<script>Swal.fire('Hata', 'Geçersiz giriş verileri', 'error');</script>";
            }
        }
    }
}

// Pagination setup
$limit = 5; // Number of items per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1; // Current page
$offset = ($page - 1) * $limit; // Offset for the query

// Fetch total number of promotions
$stmt = $pdo->query("SELECT COUNT(*) FROM bonuses");
$total_promotions = $stmt->fetchColumn();

// Fetch promotions for the current page
$stmt = $pdo->prepare("SELECT * FROM bonuses ORDER BY created_at DESC LIMIT :limit OFFSET :offset");
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$promotions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate total pages
$total_pages = ceil($total_promotions / $limit);
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promosyon Yönetim Sistemi</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
<link rel="stylesheet" href="styles.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .table td, .table th {
            vertical-align: middle;
        }
        .promo-action-btns {
            display: flex;
            gap: 10px;
        }
        .promo-action-btns .btn {
            font-size: 14px;
            padding: 6px 12px;
        }
        .promo-action-btns .btn-edit {
            background-color: #ffc107;
            color: white;
            border-radius: 4px;
        }
        .promo-action-btns .btn-delete {
            background-color: #dc3545;
            color: white;
            border-radius: 4px;
        }
        .promo-action-btns .btn:hover {
            opacity: 0.8;
        }
        .pagination {
            justify-content: center;
        }
        .add-promotion-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            z-index: 10;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            <div class="col-md-10 p-4">
                <div class="p-4 position-relative">
                    <h2 class="mb-4 text-primary">Promosyon Yönetim Sistemi</h2>
                    <button class="btn btn-success add-promotion-btn" data-bs-toggle="modal" data-bs-target="#promotionModal">Yeni Promosyon Ekle</button>

                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Başlık</th>
                                <th>Açıklama</th>
                                <th>Görsel</th>
                                <th>Detay Görsel</th>
                                <th>Şartlar</th>
                                <th>Maksimum Çekim</th>
                                <th>Oluşturulma Tarihi</th>
                                <th>İşlemler</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($promotions as $promo): ?>
                            <tr>
                                <td><?= htmlspecialchars($promo['id']) ?></td>
                                <td><?= htmlspecialchars($promo['title']) ?></td>
                                <td><?= nl2br(htmlspecialchars($promo['description'])) ?></td> <!-- Display with line breaks -->
                                <td><img src="<?= htmlspecialchars($promo['image_url']) ?>" alt="Promo" style="width: 100px; height: auto;"></td>
                                <td><img src="<?= htmlspecialchars($promo['detail_image_url']) ?>" alt="Detail" style="width: 100px; height: auto;"></td>
                                <td><?= nl2br(htmlspecialchars($promo['terms'])) ?></td> <!-- Display with line breaks -->
                                <td><?= htmlspecialchars($promo['max_withdrawal']) ?></td>
                                <td><?= htmlspecialchars($promo['created_at']) ?></td>
                                <td class="promo-action-btns">
                                    <button class="btn btn-edit" data-bs-toggle="modal" data-bs-target="#promotionModal" 
                                            data-id="<?= htmlspecialchars($promo['id']) ?>"
                                            data-title="<?= htmlspecialchars($promo['title']) ?>"
                                            data-description="<?= htmlspecialchars($promo['description']) ?>"
                                            data-image_url="<?= htmlspecialchars($promo['image_url']) ?>"
                                            data-detail_image_url="<?= htmlspecialchars($promo['detail_image_url']) ?>"
                                            data-terms="<?= htmlspecialchars($promo['terms']) ?>"
                                            data-max_withdrawal="<?= htmlspecialchars($promo['max_withdrawal']) ?>">
                                        Düzenle
                                    </button>
                                    <form method="post" class="d-inline-block">
                                        <input type="hidden" name="delete" value="<?= htmlspecialchars($promo['id']) ?>">
                                        <button type="submit" class="btn btn-delete" onclick="return confirm('Emin misiniz?');">Sil</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                    <!-- Pagination -->
                    <nav aria-label="Page navigation example">
                        <ul class="pagination">
                            <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                                <a class="page-link" href="?page=<?= max($page - 1, 1) ?>" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?= ($i == $page) ? 'active' : '' ?>"><a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a></li>
                            <?php endfor; ?>
                            <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                                <a class="page-link" href="?page=<?= min($page + 1, $total_pages) ?>" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal for Add/Edit Promotion -->
    <div class="modal fade" id="promotionModal" tabindex="-1" aria-labelledby="promotionModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="promotionModalLabel">Yeni Promosyon Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form method="post" id="promotionForm">
                        <input type="hidden" name="id" id="promo_id">
                        <div class="mb-3">
                            <label for="title" class="form-label">Başlık</label>
                            <input type="text" class="form-control" id="title" name="title" required>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">Açıklama</label>
                            <textarea class="form-control" id="description" name="description" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="image_url" class="form-label">Görsel URL</label>
                            <input type="text" class="form-control" id="image_url" name="image_url" required>
                        </div>
                        <div class="mb-3">
                            <label for="detail_image_url" class="form-label">Detay Görsel URL</label>
                            <input type="text" class="form-control" id="detail_image_url" name="detail_image_url" required>
                        </div>
                        <div class="mb-3">
                            <label for="terms" class="form-label">Şartlar</label>
                            <textarea class="form-control" id="terms" name="terms" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="max_withdrawal" class="form-label">Maksimum Çekim</label>
                            <input type="number" class="form-control" id="max_withdrawal" name="max_withdrawal" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Kaydet</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        const modal = new bootstrap.Modal(document.getElementById('promotionModal'));
        const form = document.getElementById('promotionForm');
        
        // Populate the form with promotion data when editing
        const editButtons = document.querySelectorAll('.btn-edit');
        editButtons.forEach(button => {
            button.addEventListener('click', () => {
                const promoId = button.getAttribute('data-id');
                const title = button.getAttribute('data-title');
                const description = button.getAttribute('data-description');
                const imageUrl = button.getAttribute('data-image_url');
                const detailImageUrl = button.getAttribute('data-detail_image_url');
                const terms = button.getAttribute('data-terms');
                const maxWithdrawal = button.getAttribute('data-max_withdrawal');
                
                document.getElementById('promo_id').value = promoId;
                document.getElementById('title').value = title;
                document.getElementById('description').value = description;
                document.getElementById('image_url').value = imageUrl;
                document.getElementById('detail_image_url').value = detailImageUrl;
                document.getElementById('terms').value = terms;
                document.getElementById('max_withdrawal').value = maxWithdrawal;
            });
        });

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            // You can process the form submission here via AJAX or a regular POST request
            form.submit();
        });
    </script>
</body>
</html>
