<?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 === 'update_status') {
        $purchaseId = (int)($_POST['purchase_id'] ?? 0);
        $status = $_POST['status'] ?? '';
        
        if ($purchaseId > 0 && in_array($status, ['pending', 'completed', 'cancelled', 'refunded'])) {
            // Get purchase details before updating
            $stmt = $pdo->prepare("SELECT user_id, coins, status FROM coin_purchases WHERE id = ?");
            $stmt->execute([$purchaseId]);
            $purchase = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($purchase) {
                $pdo->beginTransaction();
                
                try {
                    // Update purchase status
                    $stmt = $pdo->prepare("UPDATE coin_purchases SET status = ? WHERE id = ?");
                    $stmt->execute([$status, $purchaseId]);
                    
                    // If purchase is being cancelled or refunded, remove coins from user
                    if (($status === 'cancelled' || $status === 'refunded') && $purchase['status'] === 'completed') {
                        $userId = $purchase['user_id'];
                        $coins = $purchase['coins'];
                        
                        // Remove coins from user
                        $stmt = $pdo->prepare("UPDATE users SET coins = coins - ? WHERE id = ? AND coins >= ?");
                        $stmt->execute([$coins, $userId, $coins]);
                        
                        // Add refund transaction record
                        $stmt = $pdo->prepare("
                            INSERT INTO transactions (user_id, type, amount, coin_type, description, created_at) 
                            VALUES (?, 'refund', ?, 'regular', 'Coin purchase refund', NOW())
                        ");
                        $stmt->execute([$userId, $coins]);
                    }
                    
                    $pdo->commit();
                    $success = "وضعیت خرید با موفقیت تغییر کرد" . 
                        (($status === 'cancelled' || $status === 'refunded') ? " و سکه‌ها برگردانده شد" : "");
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $error = "خطا در تغییر وضعیت خرید: " . $e->getMessage();
                }
            } else {
                $error = "خرید یافت نشد";
            }
        }
    }
}

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

// Get filters
$statusFilter = $_GET['status'] ?? '';
$userFilter = $_GET['user'] ?? '';

// Build query
$whereConditions = [];
$params = [];

if ($statusFilter) {
    $whereConditions[] = "cp.status = ?";
    $params[] = $statusFilter;
}

if ($userFilter) {
    $whereConditions[] = "(u.username LIKE ? OR u.email LIKE ? OR u.full_name LIKE ?)";
    $searchTerm = "%$userFilter%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$whereClause = !empty($whereConditions) ? "WHERE " . implode(" AND ", $whereConditions) : "";

// Get total count
$countQuery = "
    SELECT COUNT(*) 
    FROM coin_purchases cp
    JOIN users u ON cp.user_id = u.id
    JOIN coin_packages pkg ON cp.package_id = pkg.id
    $whereClause
";
$stmt = $pdo->prepare($countQuery);
$stmt->execute($params);
$totalPurchases = $stmt->fetchColumn();
$totalPages = ceil($totalPurchases / $limit);

// Get purchases
$query = "
    SELECT cp.id, cp.product_id, cp.purchase_token, cp.order_id, cp.coins, cp.price, 
           cp.currency, cp.status, cp.purchase_time, cp.created_at,
           u.username, u.email, u.full_name,
           pkg.name as package_name
    FROM coin_purchases cp
    JOIN users u ON cp.user_id = u.id
    JOIN coin_packages pkg ON cp.package_id = pkg.id
    $whereClause
    ORDER BY cp.created_at DESC
    LIMIT " . (int)$limit . " OFFSET " . (int)$offset
;

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$purchases = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get statistics
$stmt = $pdo->query("
    SELECT 
        COUNT(*) as total_purchases,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_purchases,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_purchases,
        SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_purchases,
        SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) as refunded_purchases,
        SUM(CASE WHEN status = 'completed' THEN price ELSE 0 END) as total_revenue,
        SUM(CASE WHEN status = 'completed' THEN coins ELSE 0 END) as total_coins_sold
    FROM coin_purchases
");
$stats = $stmt->fetch(PDO::FETCH_ASSOC);

// Get today's statistics
$stmt = $pdo->query("
    SELECT 
        COUNT(*) as today_purchases,
        SUM(CASE WHEN status = 'completed' THEN price ELSE 0 END) as today_revenue
    FROM coin_purchases 
    WHERE DATE(created_at) = CURDATE()
");
$todayStats = $stmt->fetch(PDO::FETCH_ASSOC);
?>

<!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">
</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-receipt';
                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-2">
                            <div class="card stat-card info">
                                <div class="card-body text-center">
                                    <i class="fas fa-shopping-cart fa-2x mb-2"></i>
                                    <h4><?= number_format($stats['total_purchases']) ?></h4>
                                    <p class="mb-0">کل خریدها</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="card stat-card warning">
                                <div class="card-body text-center">
                                    <i class="fas fa-clock fa-2x mb-2"></i>
                                    <h4><?= number_format($stats['pending_purchases']) ?></h4>
                                    <p class="mb-0">در انتظار</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="card stat-card success">
                                <div class="card-body text-center">
                                    <i class="fas fa-check-circle fa-2x mb-2"></i>
                                    <h4><?= number_format($stats['completed_purchases']) ?></h4>
                                    <p class="mb-0">تکمیل شده</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="card stat-card danger">
                                <div class="card-body text-center">
                                    <i class="fas fa-times-circle fa-2x mb-2"></i>
                                    <h4><?= number_format($stats['cancelled_purchases']) ?></h4>
                                    <p class="mb-0">لغو شده</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="card stat-card warning">
                                <div class="card-body text-center">
                                    <i class="fas fa-dollar-sign fa-2x mb-2"></i>
                                    <h4>$<?= number_format($stats['total_revenue'], 2) ?></h4>
                                    <p class="mb-0">کل درآمد</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-coins fa-2x mb-2"></i>
                                    <h4><?= number_format($stats['total_coins_sold']) ?></h4>
                                    <p class="mb-0">سکه فروخته شده</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <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">
                            <form method="GET" class="row g-3">
                                <div class="col-md-4">
                                    <label for="status" class="form-label">وضعیت</label>
                                    <select class="form-control" id="status" name="status">
                                        <option value="">همه وضعیت‌ها</option>
                                        <option value="pending" <?= $statusFilter === 'pending' ? 'selected' : '' ?>>در انتظار</option>
                                        <option value="completed" <?= $statusFilter === 'completed' ? 'selected' : '' ?>>تکمیل شده</option>
                                        <option value="cancelled" <?= $statusFilter === 'cancelled' ? 'selected' : '' ?>>لغو شده</option>
                                        <option value="refunded" <?= $statusFilter === 'refunded' ? 'selected' : '' ?>>برگردانده شده</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label for="user" class="form-label">کاربر</label>
                                    <input type="text" class="form-control" id="user" name="user" 
                                           value="<?= htmlspecialchars($userFilter) ?>" 
                                           placeholder="نام کاربری، ایمیل یا نام کامل">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">&nbsp;</label>
                                    <div class="d-flex gap-2">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-search me-1"></i>جستجو
                                        </button>
                                        <a href="coin_purchases.php" class="btn btn-secondary">
                                            <i class="fas fa-times me-1"></i>پاک کردن
                                        </a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Purchases 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>شناسه</th>
                                            <th>کاربر</th>
                                            <th>پکیج</th>
                                            <th>Product ID</th>
                                            <th>Order ID</th>
                                            <th>سکه</th>
                                            <th>قیمت</th>
                                            <th>وضعیت</th>
                                            <th>تاریخ خرید</th>
                                            <th>عملیات</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($purchases as $purchase): ?>
                                        <tr>
                                            <td><?= $purchase['id'] ?></td>
                                            <td>
                                                <strong><?= htmlspecialchars($purchase['username']) ?></strong><br>
                                                <small class="text-muted"><?= htmlspecialchars($purchase['email']) ?></small><br>
                                                <small class="text-muted"><?= htmlspecialchars($purchase['full_name']) ?></small>
                                            </td>
                                            <td><?= htmlspecialchars($purchase['package_name']) ?></td>
                                            <td>
                                                <code><?= htmlspecialchars($purchase['product_id']) ?></code>
                                            </td>
                                            <td>
                                                <?php if ($purchase['order_id']): ?>
                                                    <code class="text-success" style="font-size: 0.85em; word-break: break-all;" title="<?= htmlspecialchars($purchase['order_id']) ?>">
                                                        <?= htmlspecialchars($purchase['order_id']) ?>
                                                    </code>
                                                <?php else: ?>
                                                    <span class="text-muted">
                                                        <i class="fas fa-clock me-1"></i>در انتظار
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-primary">
                                                    <i class="fas fa-coins me-1"></i><?= number_format($purchase['coins']) ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="text-success">
                                                    <i class="fas fa-dollar-sign me-1"></i><?= number_format($purchase['price'], 2) ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php
                                                $statusClass = [
                                                    'pending' => 'warning',
                                                    'completed' => 'success',
                                                    'cancelled' => 'danger',
                                                    'refunded' => 'info'
                                                ];
                                                $statusText = [
                                                    'pending' => 'در انتظار',
                                                    'completed' => 'تکمیل شده',
                                                    'cancelled' => 'لغو شده',
                                                    'refunded' => 'برگردانده شده'
                                                ];
                                                ?>
                                                <span class="badge bg-<?= $statusClass[$purchase['status']] ?>">
                                                    <?= $statusText[$purchase['status']] ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?= date('Y/m/d H:i', strtotime($purchase['created_at'])) ?>
                                                <?php if ($purchase['purchase_time']): ?>
                                                    <br><small class="text-muted">
                                                        تأیید: <?= date('Y/m/d H:i', strtotime($purchase['purchase_time'])) ?>
                                                    </small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-outline-primary" 
                                                        onclick="editPurchase(<?= htmlspecialchars(json_encode($purchase)) ?>)">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                        <?php if (empty($purchases)): ?>
                                        <tr>
                                            <td colspan="10" class="text-center text-muted">
                                                هیچ خریدی یافت نشد
                                            </td>
                                        </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>

                            <!-- Pagination -->
                            <?php if ($totalPages > 1): ?>
                            <nav aria-label="Page navigation">
                                <ul class="pagination justify-content-center">
                                    <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?= $page - 1 ?>&status=<?= $statusFilter ?>&user=<?= urlencode($userFilter) ?>">قبلی</a>
                                        </li>
                                    <?php endif; ?>
                                    
                                    <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                        <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                            <a class="page-link" href="?page=<?= $i ?>&status=<?= $statusFilter ?>&user=<?= urlencode($userFilter) ?>"><?= $i ?></a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <?php if ($page < $totalPages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?= $page + 1 ?>&status=<?= $statusFilter ?>&user=<?= urlencode($userFilter) ?>">بعدی</a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                            <?php endif; ?>
                        </div>
                    </div>
        </div>
    </main>

    <!-- Edit Purchase Modal -->
    <div class="modal fade" id="editPurchaseModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">ویرایش وضعیت خرید</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="update_status">
                    <input type="hidden" name="purchase_id" id="edit_purchase_id">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="edit_status" class="form-label">وضعیت جدید</label>
                            <select class="form-control" id="edit_status" name="status" required>
                                <option value="pending">در انتظار</option>
                                <option value="completed">تکمیل شده</option>
                                <option value="cancelled">لغو شده</option>
                                <option value="refunded">برگردانده شده</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                        <button type="submit" class="btn btn-primary">ذخیره تغییرات</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <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>
        function editPurchase(purchase) {
            document.getElementById('edit_purchase_id').value = purchase.id;
            document.getElementById('edit_status').value = purchase.status;
            
            const modal = new bootstrap.Modal(document.getElementById('editPurchaseModal'));
            modal.show();
        }
    </script>
</body>
</html>
