<?php
session_start();
require_once '../inc/functions.php';

if (!isLoggedIn()) {
    header('Location: ../index.php');
    exit;
}

$user = getUserById($_SESSION['user_id']);
if (!$user || $user['role'] !== 'admin') {
    header('Location: ../profile.php');
    exit;
}

// Обработка зачисления золота
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['credit_payment'])) {
    $paymentId = (int)$_POST['payment_id'];
    $statusFilter = $_POST['status_filter'] ?? '';
    $page = (int)($_POST['page'] ?? 1);

    $stmt = $pdo->prepare("SELECT * FROM payments WHERE id = ?");
    $stmt->execute([$paymentId]);
    $payment = $stmt->fetch();

    if ($payment && $payment['status'] === 'pending') {
        try {
            $pdo->beginTransaction();

            // Обновляем статус платежа
            $update = $pdo->prepare("UPDATE payments SET status = 'completed' WHERE id = ?");
            $update->execute([$paymentId]);

            // Начисляем золото пользователю
            $addGold = $pdo->prepare("UPDATE users SET gold = gold + ? WHERE id = ?");
            $addGold->execute([$payment['amount_gold'], $payment['user_id']]);

            // Логируем действие в user_action_logs
            $log = $pdo->prepare("INSERT INTO user_action_logs (user_id, action, details, ip, created_at) VALUES (?, 'payment_credited', ?, ?, NOW())");
            $details = "Зачислено {$payment['amount_gold']} золота за платеж ID {$paymentId}";
            $log->execute([$payment['user_id'], $details, $_SERVER['REMOTE_ADDR']]);

            // Если есть отдельная таблица уведомлений (например, notifications) – раскомментировать:
            // $notify = $pdo->prepare("INSERT INTO notifications (user_id, message) VALUES (?, ?)");
            // $notify->execute([$payment['user_id'], "Вам зачислено {$payment['amount_gold']} золота за покупку."]);

            $pdo->commit();
            $_SESSION['success_message'] = 'Золото успешно зачислено пользователю.';
        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['error_message'] = 'Ошибка при зачислении золота.';
        }
    } else {
        $_SESSION['error_message'] = 'Платёж не найден или уже обработан.';
    }

    // Редирект с сохранением фильтра и страницы
    header("Location: payments.php?status=" . urlencode($statusFilter) . "&page=$page");
    exit;
}

// Получаем параметры фильтра и пагинации
$statusFilter = $_GET['status'] ?? '';
$page = (int)($_GET['page'] ?? 1);
if ($page < 1) $page = 1;
$perPage = 20;

$payments = getPayments($statusFilter ?: null, $page, $perPage);
$total = countPayments($statusFilter ?: null);
$totalPages = ceil($total / $perPage);

// Статистика по платежам (общая, без учёта фильтра)
$stats = [
    'total_payments' => 0,
    'total_gold' => 0,
    'total_revenue' => 0,
    'pending' => 0,
    'completed' => 0,
    'failed' => 0,
    'expired' => 0,
];
$statsRaw = $pdo->query("
    SELECT 
        status,
        COUNT(*) as cnt,
        SUM(amount_gold) as gold_sum,
        SUM(price) as revenue_sum
    FROM payments
    GROUP BY status
")->fetchAll();
foreach ($statsRaw as $row) {
    $stats[$row['status']] = $row['cnt'];
    $stats['total_payments'] += $row['cnt'];
    $stats['total_gold'] += $row['gold_sum'];
    $stats['total_revenue'] += $row['revenue_sum'];
}

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

<style>
/* === Modern Dark Theme for Payments === */
.payments-dark {
    font-family: 'Inter', 'Segoe UI', Roboto, system-ui, sans-serif;
    background: #0b0f17;
    color: #e2e8f0;
    padding: 2rem;
    border-radius: 2rem;
    box-shadow: inset 0 0 0 1px rgba(255,255,255,0.05), 0 20px 30px -10px black;
    margin: 1rem 0;
}

/* header */
.payments-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 1rem;
    margin-bottom: 2rem;
}
.payments-header h2 {
    margin: 0;
    font-weight: 600;
    font-size: 2rem;
    background: linear-gradient(135deg, #a5b4fc, #818cf8);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

/* stats cards */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}
.stat-card {
    background: rgba(18, 25, 40, 0.7);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: 1px solid rgba(255,255,255,0.05);
    border-radius: 1.5rem;
    padding: 1.2rem 1rem;
    box-shadow: 0 8px 20px rgba(0,0,0,0.6);
    transition: 0.2s;
}
.stat-card:hover {
    background: rgba(28, 35, 55, 0.8);
    border-color: rgba(255,255,255,0.1);
}
.stat-title {
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: #94a3b8;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.stat-value {
    font-size: 2rem;
    font-weight: 700;
    line-height: 1;
    color: white;
}
.stat-value small {
    font-size: 1rem;
    font-weight: 400;
    color: #94a3b8;
}
.stat-card.total   { border-left: 4px solid #818cf8; }
.stat-card.pending { border-left: 4px solid #f59e0b; }
.stat-card.completed { border-left: 4px solid #10b981; }
.stat-card.failed  { border-left: 4px solid #ef4444; }
.stat-card.expired { border-left: 4px solid #64748b; }

/* filter bar */
.filter-bar {
    background: rgba(18, 25, 40, 0.8);
    backdrop-filter: blur(8px);
    border: 1px solid rgba(255,255,255,0.05);
    border-radius: 3rem;
    padding: 0.8rem 1.5rem;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 1rem;
    margin-bottom: 2rem;
    box-shadow: 0 8px 16px rgba(0,0,0,0.4);
}
.filter-group {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    flex-wrap: wrap;
}
.filter-group label {
    font-weight: 500;
    color: #cbd5e1;
    font-size: 0.95rem;
}
.filter-group select {
    background: #1e293b;
    border: 1px solid #334155;
    color: #f1f5f9;
    padding: 0.5rem 2.5rem 0.5rem 1.2rem;
    border-radius: 2rem;
    font-size: 0.95rem;
    cursor: pointer;
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 1rem center;
}
.btn {
    padding: 0.5rem 1.5rem;
    border-radius: 2rem;
    font-weight: 500;
    font-size: 0.95rem;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    transition: 0.2s;
    border: none;
    cursor: pointer;
    background: transparent;
    color: #e2e8f0;
}
.btn-primary {
    background: linear-gradient(145deg, #4f46e5, #6366f1);
    color: white;
    box-shadow: 0 8px 16px -5px #4f46e5;
}
.btn-primary:hover {
    background: linear-gradient(145deg, #6366f1, #818cf8);
    transform: translateY(-2px);
}
.btn-secondary {
    background: #1e293b;
    color: #e2e8f0;
    border: 1px solid #334155;
}
.btn-secondary:hover {
    background: #2d3a4f;
}
.btn-success {
    background: #059669;
    color: white;
}
.btn-success:hover {
    background: #047857;
}

/* table */
.table-responsive {
    overflow-x: auto;
    border-radius: 1.5rem;
    background: #0f172a;
    border: 1px solid #1e293b;
    box-shadow: 0 15px 30px -12px black;
}
.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.9rem;
    color: #e2e8f0;
}
.modern-table th {
    background: #111c2e;
    color: #a5b4fc;
    font-weight: 600;
    padding: 1rem 0.75rem;
    text-align: left;
    white-space: nowrap;
    border-bottom: 1px solid #1e293b;
}
.modern-table td {
    padding: 1rem 0.75rem;
    border-bottom: 1px solid #1e293b;
    vertical-align: middle;
}
.modern-table tbody tr:hover {
    background: #1a2538;
}
.modern-table tbody tr:last-child td {
    border-bottom: none;
}

/* badges */
.badge {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    padding: 0.3rem 1rem;
    border-radius: 20px;
    font-weight: 600;
    font-size: 0.8rem;
    letter-spacing: 0.3px;
    text-transform: uppercase;
    background: #1e293b;
    color: #e2e8f0;
    white-space: nowrap;
}
.badge-pending {
    background: #92400e;
    color: #fde68a;
}
.badge-completed {
    background: #065f46;
    color: #a7f3d0;
}
.badge-failed {
    background: #7f1d1d;
    color: #fecaca;
}
.badge-expired {
    background: #2d3748;
    color: #cbd5e0;
}

/* messages */
.alert {
    padding: 1rem 1.5rem;
    border-radius: 2rem;
    margin-bottom: 1.5rem;
    font-weight: 500;
}
.alert-success {
    background: #065f46;
    color: #d1fae5;
    border: 1px solid #10b981;
}
.alert-error {
    background: #7f1d1d;
    color: #fee2e2;
    border: 1px solid #ef4444;
}

/* pagination & counter */
.pagination {
    margin-top: 2rem;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 0.4rem;
}
.page-item {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 2.5rem;
    height: 2.5rem;
    padding: 0 0.2rem;
    border-radius: 9999px;
    background: #1e293b;
    border: 1px solid #334155;
    color: #cbd5e1;
    text-decoration: none;
    font-weight: 500;
    transition: 0.2s;
}
.page-item:hover {
    background: #2d3a4f;
    border-color: #4f46e5;
    color: white;
}
.page-item.active {
    background: #4f46e5;
    border-color: #4f46e5;
    color: white;
}
.record-counter {
    margin-top: 1rem;
    font-size: 0.9rem;
    color: #94a3b8;
    background: #111c2e;
    padding: 0.5rem 1.2rem;
    border-radius: 2rem;
    display: inline-block;
    border: 1px solid #1e293b;
}
</style>

<div class="payments-dark">

    <!-- Header with back button -->
    <div class="payments-header">
        <h2>
            <span>💰</span> Управление платежами
        </h2>
        <a class="btn btn-secondary" href="index.php">
            ← В админ-панель
        </a>
    </div>

    <!-- Display messages -->
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success"><?= $_SESSION['success_message'] ?></div>
        <?php unset($_SESSION['success_message']); ?>
    <?php endif; ?>
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-error"><?= $_SESSION['error_message'] ?></div>
        <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>

    <!-- Statistics cards -->
    <div class="stats-grid">
        <div class="stat-card total">
            <div class="stat-title"><span>📊</span> Всего платежей</div>
            <div class="stat-value"><?= $stats['total_payments'] ?></div>
        </div>
        <div class="stat-card total">
            <div class="stat-title"><span>🪙</span> Всего золота</div>
            <div class="stat-value"><?= number_format($stats['total_gold'], 0, '', ' ') ?> <small>ед.</small></div>
        </div>
        <div class="stat-card total">
            <div class="stat-title"><span>💵</span> Выручка (RUB)</div>
            <div class="stat-value"><?= number_format($stats['total_revenue'], 2, '.', ' ') ?> <small>₽</small></div>
        </div>
        <div class="stat-card pending">
            <div class="stat-title"><span>⏳</span> Ожидание</div>
            <div class="stat-value"><?= $stats['pending'] ?></div>
        </div>
        <div class="stat-card completed">
            <div class="stat-title"><span>✅</span> Выполнено</div>
            <div class="stat-value"><?= $stats['completed'] ?></div>
        </div>
        <div class="stat-card failed">
            <div class="stat-title"><span>❌</span> Ошибка</div>
            <div class="stat-value"><?= $stats['failed'] ?></div>
        </div>
        <div class="stat-card expired">
            <div class="stat-title"><span>⌛</span> Просрочено</div>
            <div class="stat-value"><?= $stats['expired'] ?></div>
        </div>
    </div>

    <!-- Filter bar -->
    <div class="filter-bar">
        <form method="get" style="display: contents;">
            <div class="filter-group">
                <label for="status-filter">Статус платежа:</label>
                <select name="status" id="status-filter">
                    <option value="">Все</option>
                    <option value="pending" <?= $statusFilter === 'pending' ? 'selected' : '' ?>>Ожидание</option>
                    <option value="completed" <?= $statusFilter === 'completed' ? 'selected' : '' ?>>Выполнено</option>
                    <option value="failed" <?= $statusFilter === 'failed' ? 'selected' : '' ?>>Ошибка</option>
                    <option value="expired" <?= $statusFilter === 'expired' ? 'selected' : '' ?>>Просрочено</option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">
                🔍 Применить
            </button>
            <?php if ($statusFilter): ?>
                <a href="payments.php" class="btn btn-secondary">
                    ✕ Сбросить
                </a>
            <?php endif; ?>
        </form>
    </div>

    <!-- Payments table -->
    <div class="table-responsive">
        <table class="modern-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Пользователь</th>
                    <th>Пакет</th>
                    <th>Золото</th>
                    <th>Цена (RUB)</th>
                    <th>Статус</th>
                    <th>Дата</th>
                    <th>Invoice ID</th>
                    <th>Транзакция</th>
                    <th>Действие</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($payments as $p): 
                $badgeClass = 'badge';
                $icon = '';
                switch ($p['status']) {
                    case 'pending': $badgeClass .= ' badge-pending'; $icon = '⏳'; break;
                    case 'completed': $badgeClass .= ' badge-completed'; $icon = '✅'; break;
                    case 'failed': $badgeClass .= ' badge-failed'; $icon = '❌'; break;
                    case 'expired': $badgeClass .= ' badge-expired'; $icon = '⌛'; break;
                    default: $badgeClass .= ' badge-other'; $icon = '⚙️';
                }
            ?>
                <tr>
                    <td><code>#<?= $p['id'] ?></code></td>
                    <td><?= htmlspecialchars($p['username']) ?> <small>(ID: <?= $p['user_id'] ?>)</small></td>
                    <td><?= $p['package_id'] ?></td>
                    <td><?= number_format($p['amount_gold'], 0, '', ' ') ?></td>
                    <td><?= number_format($p['price'], 2, '.', ' ') ?> ₽</td>
                    <td>
                        <span class="<?= $badgeClass ?>">
                            <?= $icon ?> <?= $p['status'] ?>
                        </span>
                    </td>
                    <td><small><?= date('d.m.Y H:i', strtotime($p['created_at'])) ?></small></td>
                    <td><small><?= htmlspecialchars($p['invoice_id']) ?></small></td>
                    <td><small><?= htmlspecialchars($p['transaction_id'] ?? '') ?></small></td>
                    <td>
                        <?php if ($p['status'] === 'pending'): ?>
                            <form method="post" style="display:inline;">
                                <input type="hidden" name="payment_id" value="<?= $p['id'] ?>">
                                <input type="hidden" name="status_filter" value="<?= htmlspecialchars($statusFilter) ?>">
                                <input type="hidden" name="page" value="<?= $page ?>">
                                <button type="submit" name="credit_payment" class="btn btn-success" style="padding:0.3rem 1rem;">
                                    ✅ Зачислить
                                </button>
                            </form>
                        <?php else: ?>
                            <span class="badge badge-other" style="background:transparent;">—</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Record counter -->
    <div class="record-counter">
        <?php
        $from = ($page - 1) * $perPage + 1;
        $to = min($page * $perPage, $total);
        if ($total > 0) {
            echo "Показано записей: $from – $to из $total";
        } else {
            echo "Записей не найдено";
        }
        ?>
    </div>

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

</div> <!-- .payments-dark -->

<?php require_once '../inc/foot.php'; ?>