<?php
session_start();
require_once '/home/akgbilis/fi_sf/config.php';
if (!isset($_SESSION['logged_in'])) {
    header("Location: login.php");
    exit;
}

// Filtreler
$search = $_GET['search'] ?? '';
$date = $_GET['date'] ?? '';
$status = $_GET['status'] ?? '';

// Ana query ve parametreler
$query = "SELECT * FROM combines WHERE 1";
$params = [];

if ($search !== '') {
    $query .= " AND name LIKE :search";
    $params[':search'] = "%$search%";
}
if ($date !== '') {
    $query .= " AND date = :date";
    $params[':date'] = $date;
}

// Duruma göre filtreleme
if ($status !== '') {
    $query .= " AND id IN (
        SELECT combine_id FROM combine_matches cm
        JOIN matches m ON cm.match_id = m.id
        GROUP BY cm.combine_id
        HAVING 
            (:status_lost = 'LOST' AND SUM(m.status = 'LOST') > 0)
            OR (:status_waiting = 'WAITING' AND SUM(m.status = 'WAITING') > 0)
            OR (:status_won = 'WON' AND SUM(m.status = 'WON') = COUNT(*))
    )";
    $params[':status_lost'] = $status;
    $params[':status_waiting'] = $status;
    $params[':status_won'] = $status;
}

// Sayfalama
$perPage = 10;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $perPage;

// Toplam sayfa
$countQuery = "SELECT COUNT(*) FROM combines WHERE 1";
$countStmt = $pdo->prepare($countQuery);
$countStmt->execute();
$totalCombines = $countStmt->fetchColumn();
$totalPages = ceil($totalCombines / $perPage);

// Sınırlı kayıtları çek
$query .= " ORDER BY date DESC LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($query);
foreach ($params as $key => &$val) {
    $stmt->bindParam($key, $val);
}
$stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$combines = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Kuponlar - Panel</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        * { box-sizing: border-box; }
        body {
            margin: 0; padding: 0;
            font-family: 'Segoe UI', sans-serif;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 900px;
            margin: auto;
            padding: 20px;
        }
        .header-bar {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            align-items: center;
            margin-bottom: 20px;
        }
        .header-bar h2 { margin: 0; font-size: 24px; }
        .header-actions .button {
            background: #3498db; color: white;
            padding: 8px 14px; border-radius: 6px;
            text-decoration: none; margin-left: 8px;
        }
        .filter-bar {
            display: flex; flex-wrap: wrap;
            gap: 10px; margin-bottom: 20px;
            align-items: center;
        }
        .filter-bar input[type="text"],
        .filter-bar input[type="date"] {
            padding: 10px; border-radius: 6px;
            border: 1px solid #ccc; flex: 1;
            min-width: 150px;
        }
        .filter-bar label {
            display: flex; align-items: center;
            gap: 4px;
        }
        .filter-bar .button {
            background-color: #2ecc71;
            color: white; border: none;
            padding: 10px 16px; border-radius: 6px;
            cursor: pointer;
        }
        .combine-card {
            background: white;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 20px;
            box-shadow: 0 1px 5px rgba(0,0,0,0.1);
        }
        .combine-header {
            display: flex; justify-content: space-between;
            align-items: center; flex-wrap: wrap;
            margin-bottom: 10px;
        }
        .combine-header .button {
            padding: 6px 12px; border-radius: 4px;
            text-decoration: none; font-size: 14px;
        }
        .combine-header .button.small { font-size: 13px; }
        .combine-header .danger {
            background-color: #e74c3c; color: white;
        }
        .combine-header .button:not(.danger) {
            background-color: #2980b9; color: white;
        }
        .match-list {
            display: grid;
            grid-template-columns: 1fr;
            gap: 10px;
        }
        .match-card {
            padding: 10px; border: 1px solid #ddd;
            border-radius: 6px; background-color: #f9f9f9;
        }
        .match-header {
            font-size: 13px; color: #777;
        }
        .match-teams {
            font-weight: bold;
            margin: 4px 0;
        }
        .match-details {
            display: flex; justify-content: space-between;
            font-size: 14px;
        }
        .status.waiting { color: #f39c12; }
        .status.won { color: #27ae60; }
        .status.lost { color: #c0392b; }
        .pagination {
            text-align: center;
            margin-top: 30px;
        }
        .pagination a {
            padding: 8px 12px; margin: 0 4px;
            background: #3498db; color: white;
            border-radius: 4px; text-decoration: none;
            font-size: 14px;
        }
        .pagination a.active {
            background: #2c3e50;
        }
        @media (max-width: 600px) {
            .header-bar, .combine-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            .match-details {
                flex-direction: column;
                gap: 4px;
            }
            .filter-bar {
                flex-direction: column;
                align-items: stretch;
            }
            .filter-bar .button {
                width: 100%;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header-bar">
        <h2>Kuponlar</h2>
        <div class="header-actions">
            <a href="dashboard.php" class="button">← Ana Sayfa</a>
            <a href="add_combine.php" class="button">➕ Yeni Kupon</a>
        </div>
    </div>

    <form method="GET" class="filter-bar">
        <input type="text" name="search" placeholder="Kupon adı..." value="<?= htmlspecialchars($search) ?>">
        <input type="date" name="date" value="<?= htmlspecialchars($date) ?>">

        <label><input type="radio" name="status" value="" <?= $status === '' ? 'checked' : '' ?> onchange="this.form.submit()"> Tümü</label>
        <label><input type="radio" name="status" value="WAITING" <?= $status === 'WAITING' ? 'checked' : '' ?> onchange="this.form.submit()"> ⏳</label>
        <label><input type="radio" name="status" value="WON" <?= $status === 'WON' ? 'checked' : '' ?> onchange="this.form.submit()"> ✅</label>
        <label><input type="radio" name="status" value="LOST" <?= $status === 'LOST' ? 'checked' : '' ?> onchange="this.form.submit()"> ❌</label>

        <button type="submit" class="button">Filtrele</button>
        <a href="combine_dashboard.php" class="button" style="background:#95a5a6;">Sıfırla</a>
    </form>

    <?php foreach ($combines as $combine): ?>
        <div class="combine-card">
            <div class="combine-header">
                <div><strong><?= htmlspecialchars($combine['name']) ?></strong> - <?= htmlspecialchars($combine['date']) ?></div>
                <div>
                    <a href="edit_combine.php?id=<?= $combine['id'] ?>" class="button small">📝 Düzenle</a>
                    <a href="delete_combine.php?id=<?= $combine['id'] ?>" class="button small danger" onclick="return confirm('Bu kuponu silmek istediğinize emin misiniz?')">🗑️ Sil</a>
                </div>
            </div>
            <?php
            $stmt = $pdo->prepare("
                SELECT m.* FROM combine_matches cm
                JOIN matches m ON cm.match_id = m.id
                WHERE cm.combine_id = ?
            ");
            $stmt->execute([$combine['id']]);
            $matches = $stmt->fetchAll();
            ?>
            <div class="match-list">
                <?php foreach ($matches as $match): ?>
                    <div class="match-card">
                        <div class="match-header"><?= $match['date'] ?> • <?= $match['time'] ?> • <?= $match['id'] ?></div>
                        <div class="match-teams"><?= htmlspecialchars($match['home']) ?> - <?= htmlspecialchars($match['away']) ?></div>
                        <div class="match-details">
                            <span><?= htmlspecialchars($match['prediction']) ?> @ <?= number_format((float)$match['odds'], 2) ?></span>
                            <span class="status <?= strtolower($match['status']) ?>">
                                <?= $match['status'] === 'WAITING' ? '⏳' : ($match['status'] === 'WON' ? '✅' : '❌') ?>
                            </span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endforeach; ?>

    <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&date=<?= $date ?>&status=<?= $status ?>" class="<?= $i == $page ? 'active' : '' ?>">
                    <?= $i ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>

    <?php if (count($combines) === 0): ?>
        <p>Henüz kupon eklenmedi ya da filtrelere uyan yok.</p>
    <?php endif; ?>
</div>
</body>
</html>