<?php
session_start();
require_once '../config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'delete_transaction') {
        $transactionId = (int)($_POST['transaction_id'] ?? 0);
        
        if ($transactionId > 0) {
            $stmt = $pdo->prepare("DELETE FROM transactions WHERE id = ?");
            if ($stmt->execute([$transactionId])) {
                $success = "تراکنش با موفقیت حذف شد";
            } else {
                $error = "خطا در حذف تراکنش";
            }
        }
    }
}

// Get transactions with pagination
$page = (int)($_GET['page'] ?? 1);
$limit = 20;
$offset = ($page - 1) * $limit;

$stmt = $pdo->query("SELECT COUNT(*) FROM transactions");
$totalTransactions = $stmt->fetchColumn();
$totalPages = ceil($totalTransactions / $limit);

$stmt = $pdo->prepare("
    SELECT t.id, t.type, t.amount, t.description, t.created_at,
           u.username, u.email, u.full_name
    FROM transactions t
    JOIN users u ON t.user_id = u.id
    ORDER BY t.created_at DESC
    LIMIT " . (int)$limit . " OFFSET " . (int)$offset
);
$stmt->execute();
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$stmt = $pdo->query("SELECT COUNT(*) FROM transactions WHERE type = 'purchase'");
$purchaseCount = $stmt->fetchColumn();

$stmt = $pdo->query("SELECT COUNT(*) FROM transactions WHERE type = 'bonus'");
$bonusCount = $stmt->fetchColumn();

$stmt = $pdo->query("SELECT SUM(amount) FROM transactions WHERE type = 'purchase'");
$totalPurchases = $stmt->fetchColumn() ?: 0;

$stmt = $pdo->query("SELECT SUM(amount) FROM transactions WHERE type = 'bonus'");
$totalBonus = $stmt->fetchColumn() ?: 0;
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت تراکنشات - پنل مدیریت</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="assets/css/admin.css" rel="stylesheet">
    <style>
        .amount-positive { color: #27ae60; }
        .amount-negative { color: #e74c3c; }
    </style>
</head>
<body class="admin-app">
    <?php include 'includes/menu.php'; ?>
    <?php include 'includes/header_bar.php'; ?>

    <main class="main">
        <div class="main-content">
                <?php
                $admin_page_title = 'مدیریت تراکنشات';
                $admin_page_icon = 'fas fa-exchange-alt';
                $admin_page_actions = '<span class="badge rounded-pill admin-badge-soft">' . number_format($totalTransactions) . ' تراکنش</span>';
                include 'includes/topbar.php';
                ?>

                <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i>
                        <?= htmlspecialchars($success) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <?= htmlspecialchars($error) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card stat-card info">
                            <div class="card-body text-center">
                                <i class="fas fa-exchange-alt fa-2x mb-2"></i>
                                <h4><?= number_format($totalTransactions) ?></h4>
                                <p class="mb-0">کل تراکنشات</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card success">
                            <div class="card-body text-center">
                                <i class="fas fa-shopping-cart fa-2x mb-2"></i>
                                <h4><?= number_format($purchaseCount) ?></h4>
                                <p class="mb-0">تراکنشات خرید</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card warning">
                            <div class="card-body text-center">
                                <i class="fas fa-gift fa-2x mb-2"></i>
                                <h4><?= number_format($bonusCount) ?></h4>
                                <p class="mb-0">تراکنشات پاداش</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card">
                            <div class="card-body text-center">
                                <i class="fas fa-coins fa-2x mb-2"></i>
                                <h4><?= number_format(abs($totalPurchases)) ?></h4>
                                <p class="mb-0">کل خریدها (سکه)</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Transactions Table -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">لیست تراکنشات</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>کاربر</th>
                                        <th>نوع تراکنش</th>
                                        <th>مبلغ</th>
                                        <th>توضیحات</th>
                                        <th>تاریخ تراکنش</th>
                                        <th>عملیات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($transactions as $transaction): ?>
                                    <tr>
                                        <td><?= $transaction['id'] ?></td>
                                        <td>
                                            <strong><?= htmlspecialchars($transaction['full_name']) ?></strong>
                                            <br><small class="text-muted">@<?= htmlspecialchars($transaction['username']) ?></small>
                                            <br><small class="text-muted"><?= htmlspecialchars($transaction['email']) ?></small>
                                        </td>
                                        <td>
                                            <?php
                                            $typeLabels = [
                                                'purchase' => 'خرید',
                                                'refund' => 'بازپرداخت',
                                                'bonus' => 'پاداش',
                                                'withdrawal' => 'برداشت'
                                            ];
                                            $typeColors = [
                                                'purchase' => 'danger',
                                                'refund' => 'success',
                                                'bonus' => 'warning',
                                                'withdrawal' => 'info'
                                            ];
                                            ?>
                                            <span class="badge bg-<?= $typeColors[$transaction['type']] ?? 'secondary' ?>">
                                                <?= $typeLabels[$transaction['type']] ?? $transaction['type'] ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold <?= $transaction['amount'] >= 0 ? 'amount-positive' : 'amount-negative' ?>">
                                                <?= $transaction['amount'] >= 0 ? '+' : '' ?><?= number_format($transaction['amount']) ?> سکه
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($transaction['description']): ?>
                                                <span title="<?= htmlspecialchars($transaction['description']) ?>">
                                                    <?= htmlspecialchars(substr($transaction['description'], 0, 50)) ?>
                                                    <?= strlen($transaction['description']) > 50 ? '...' : '' ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted">بدون توضیح</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= date('Y/m/d H:i', strtotime($transaction['created_at'])) ?></td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-danger" 
                                                    onclick="deleteTransaction(<?= $transaction['id'] ?>)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($totalPages > 1): ?>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center">
                                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                    <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                                </li>
                                <?php endfor; ?>
                            </ul>
                        </nav>
                        <?php endif; ?>
                    </div>
                </div>
        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <?php include 'includes/admin_shell_scripts.php'; ?>
    <script>
        // Delete Transaction
        function deleteTransaction(transactionId) {
            if (confirm('آیا از حذف این تراکنش اطمینان دارید؟')) {
                var form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_transaction">
                    <input type="hidden" name="transaction_id" value="${transactionId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>
