<?php
/**
 * Sub-Agent Top-ups Admin Page
 * View all top-ups made by sub-agents across all stores
 */

require_once dirname(dirname(__DIR__)) . '/config.php';

// Set page variables for header
$page_title = 'Sub-Agent Top-ups';
$page_description = 'View and monitor all top-ups made by sub-agents';

// Get filter parameters
$filterStoreId = isset($_GET['store_id']) ? intval($_GET['store_id']) : 0;
$filterUserId = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$filterStatus = isset($_GET['status']) ? $_GET['status'] : '';
$filterStartDate = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$filterEndDate = isset($_GET['end_date']) ? $_GET['end_date'] : '';
$pageNum = isset($_GET['page_num']) ? (int)$_GET['page_num'] : 1;
if ($pageNum < 1) $pageNum = 1;
$page = $pageNum;
$limit = 50;

if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Build WHERE clause
$whereConditions = [];
$params = [];
$paramTypes = '';

if ($filterStoreId > 0) {
    $whereConditions[] = "sat.store_id = ?";
    $params[] = $filterStoreId;
    $paramTypes .= 'i';
}

if ($filterUserId > 0) {
    $whereConditions[] = "sat.user_id = ?";
    $params[] = $filterUserId;
    $paramTypes .= 'i';
}

if ($filterStatus && in_array($filterStatus, ['pending', 'processing', 'completed', 'failed', 'cancelled'])) {
    $whereConditions[] = "sat.payment_status = ?";
    $params[] = $filterStatus;
    $paramTypes .= 's';
}

if ($filterStartDate && $filterEndDate) {
    $whereConditions[] = "DATE(sat.created_at) BETWEEN ? AND ?";
    $params[] = $filterStartDate;
    $params[] = $filterEndDate;
    $paramTypes .= 'ss';
} elseif ($filterStartDate) {
    $whereConditions[] = "DATE(sat.created_at) >= ?";
    $params[] = $filterStartDate;
    $paramTypes .= 's';
} elseif ($filterEndDate) {
    $whereConditions[] = "DATE(sat.created_at) <= ?";
    $params[] = $filterEndDate;
    $paramTypes .= 's';
}

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

// Get total count
$countQuery = "SELECT COUNT(*) as total FROM subagent_topup_tracking sat $whereClause";
$countStmt = $conn->prepare($countQuery);
if ($countStmt && !empty($params)) {
    $countStmt->bind_param($paramTypes, ...$params);
} elseif ($countStmt) {
    // No parameters
}
if ($countStmt) {
    $countStmt->execute();
    $countResult = $countStmt->get_result();
    $totalRecords = $countResult->fetch_assoc()['total'];
    $totalPages = ceil($totalRecords / $limit);
    $countStmt->close();
} else {
    $totalRecords = 0;
    $totalPages = 0;
}

// Get top-ups with related information
$query = "
    SELECT 
        sat.id,
        sat.user_id,
        sat.store_id,
        sat.store_owner_id,
        sat.payment_reference,
        sat.base_amount,
        sat.charge_amount,
        sat.total_amount,
        sat.payment_status,
        sat.payment_method,
        sat.external_transaction_id,
        sat.ip_address,
        sat.credited_at,
        sat.created_at,
        sat.updated_at,
        sat.notes,
        a.username as agent_username,
        a.email as agent_email,
        s.store_name,
        owner.username as owner_username,
        owner.email as owner_email
    FROM subagent_topup_tracking sat
    INNER JOIN agents a ON sat.user_id = a.id
    INNER JOIN stores s ON sat.store_id = s.id
    INNER JOIN agents owner ON sat.store_owner_id = owner.id
    $whereClause
    ORDER BY sat.created_at DESC
    LIMIT ? OFFSET ?
";

$stmt = $conn->prepare($query);
if ($stmt) {
    $mainParams = $params;
    $mainParams[] = $limit;
    $mainParams[] = $offset;
    $mainParamTypes = $paramTypes . 'ii';
    $stmt->bind_param($mainParamTypes, ...$mainParams);
    $stmt->execute();
    $result = $stmt->get_result();
    $topups = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} else {
    $topups = [];
}

// Get summary statistics
$summaryQuery = "
    SELECT 
        COUNT(*) as total_topups,
        SUM(CASE WHEN sat.payment_status = 'completed' THEN 1 ELSE 0 END) as completed_count,
        SUM(CASE WHEN sat.payment_status = 'pending' THEN 1 ELSE 0 END) as pending_count,
        SUM(CASE WHEN sat.payment_status = 'failed' THEN 1 ELSE 0 END) as failed_count,
        SUM(CASE WHEN sat.payment_status = 'completed' THEN sat.base_amount ELSE 0 END) as total_credited,
        SUM(CASE WHEN sat.payment_status = 'completed' THEN sat.total_amount ELSE 0 END) as total_paid
    FROM subagent_topup_tracking sat
    $whereClause
";

$summaryStmt = $conn->prepare($summaryQuery);
if ($summaryStmt && !empty($params)) {
    $summaryStmt->bind_param($paramTypes, ...$params);
} elseif ($summaryStmt) {
    // No parameters
}
if ($summaryStmt) {
    $summaryStmt->execute();
    $summaryResult = $summaryStmt->get_result();
    $summary = $summaryResult->fetch_assoc();
    $summaryStmt->close();
} else {
    $summary = [
        'total_topups' => 0,
        'completed_count' => 0,
        'pending_count' => 0,
        'failed_count' => 0,
        'total_credited' => 0,
        'total_paid' => 0
    ];
}

// Get all stores for filter dropdown
$storesStmt = $conn->query("SELECT id, store_name FROM stores ORDER BY store_name");
$allStores = $storesStmt->fetch_all(MYSQLI_ASSOC);
$storesStmt->close();

// Get all sub-agents for filter dropdown
$agentsStmt = $conn->query("
    SELECT DISTINCT a.id, a.username, a.email, s.store_name 
    FROM agents a
    INNER JOIN subagent_topup_tracking sat ON a.id = sat.user_id
    INNER JOIN stores s ON sat.store_id = s.id
    WHERE a.is_store_owner = 0 AND a.store_id IS NOT NULL
    ORDER BY s.store_name, a.username
");
$allAgents = $agentsStmt->fetch_all(MYSQLI_ASSOC);
$agentsStmt->close();
?>

<div class="container mx-auto px-4 py-8">
    <!-- Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-sm mb-1">Total Top-ups</p>
                    <p class="text-3xl font-bold text-white"><?php echo number_format($summary['total_topups']); ?></p>
                </div>
                <div class="text-blue-400">
                    <i class="fas fa-list text-3xl"></i>
                </div>
            </div>
        </div>
        <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-sm mb-1">Completed</p>
                    <p class="text-3xl font-bold text-green-400"><?php echo number_format($summary['completed_count']); ?></p>
                </div>
                <div class="text-green-400">
                    <i class="fas fa-check-circle text-3xl"></i>
                </div>
            </div>
        </div>
        <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-sm mb-1">Total Credited</p>
                    <p class="text-3xl font-bold text-white">GH₵ <?php echo number_format($summary['total_credited'], 2); ?></p>
                </div>
                <div class="text-green-400">
                    <i class="fas fa-wallet text-3xl"></i>
                </div>
            </div>
        </div>
        <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-sm mb-1">Total Paid</p>
                    <p class="text-3xl font-bold text-white">GH₵ <?php echo number_format($summary['total_paid'], 2); ?></p>
                </div>
                <div class="text-blue-400">
                    <i class="fas fa-money-bill-wave text-3xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-gray-800 border border-gray-700 rounded-lg p-6 mb-6">
        <h2 class="text-xl font-bold text-white mb-4">
            <i class="fas fa-filter text-blue-400 mr-2"></i>
            Filters
        </h2>
        <form method="GET" action="index.php?page=subagent_topups" class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
            <input type="hidden" name="page" value="subagent_topups">
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">Store</label>
                <select name="store_id" class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
                    <option value="0">All Stores</option>
                    <?php foreach ($allStores as $store): ?>
                        <option value="<?php echo $store['id']; ?>" <?php echo $filterStoreId == $store['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($store['store_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">Sub-Agent</label>
                <select name="user_id" class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
                    <option value="0">All Sub-Agents</option>
                    <?php foreach ($allAgents as $agent): ?>
                        <option value="<?php echo $agent['id']; ?>" <?php echo $filterUserId == $agent['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($agent['username'] . ' (' . $agent['store_name'] . ')'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">Status</label>
                <select name="status" class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
                    <option value="">All Status</option>
                    <option value="pending" <?php echo $filterStatus === 'pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="processing" <?php echo $filterStatus === 'processing' ? 'selected' : ''; ?>>Processing</option>
                    <option value="completed" <?php echo $filterStatus === 'completed' ? 'selected' : ''; ?>>Completed</option>
                    <option value="failed" <?php echo $filterStatus === 'failed' ? 'selected' : ''; ?>>Failed</option>
                    <option value="cancelled" <?php echo $filterStatus === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">Start Date</label>
                <input type="date" name="start_date" value="<?php echo htmlspecialchars($filterStartDate); ?>" class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-300 mb-2">End Date</label>
                <input type="date" name="end_date" value="<?php echo htmlspecialchars($filterEndDate); ?>" class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
            </div>
            <div class="md:col-span-3 lg:col-span-5 flex gap-2">
                <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg font-medium">
                    <i class="fas fa-filter mr-2"></i>Filter
                </button>
                <a href="index.php?page=subagent_topups" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg font-medium">
                    <i class="fas fa-times mr-2"></i>Clear
                </a>
            </div>
        </form>
    </div>

    <!-- Top-ups Table -->
    <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
        <h2 class="text-xl font-bold text-white mb-4">
            <i class="fas fa-credit-card text-blue-400 mr-2"></i>
            Top-up History
        </h2>
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead>
                    <tr class="border-b border-gray-700">
                        <th class="text-left py-3 px-2 text-gray-300 font-semibold">ID</th>
                        <th class="text-left py-3 px-2 text-gray-300 font-semibold">Date</th>
                        <th class="text-left py-3 px-2 text-gray-300 font-semibold">Sub-Agent</th>
                        <th class="text-left py-3 px-2 text-gray-300 font-semibold">Store</th>
                        <th class="text-left py-3 px-2 text-gray-300 font-semibold">Store Owner</th>
                        <th class="text-right py-3 px-2 text-gray-300 font-semibold">Base Amount</th>
                        <th class="text-right py-3 px-2 text-gray-300 font-semibold">Charge</th>
                        <th class="text-right py-3 px-2 text-gray-300 font-semibold">Total Paid</th>
                        <th class="text-center py-3 px-2 text-gray-300 font-semibold">Status</th>
                        <th class="text-left py-3 px-2 text-gray-300 font-semibold">Credited At</th>
                        <th class="text-left py-3 px-2 text-gray-300 font-semibold">Reference</th>
                        <th class="text-left py-3 px-2 text-gray-300 font-semibold">IP Address</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($topups)): ?>
                        <tr>
                            <td colspan="12" class="text-center text-gray-400 py-8">
                                <i class="fas fa-inbox text-4xl mb-3"></i>
                                <p>No top-ups found</p>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($topups as $topup): ?>
                            <tr class="border-b border-gray-700 hover:bg-gray-700/50 transition-colors">
                                <td class="py-3 px-2 text-gray-300"><?php echo $topup['id']; ?></td>
                                <td class="py-3 px-2 text-gray-300"><?php echo date('Y-m-d H:i', strtotime($topup['created_at'])); ?></td>
                                <td class="py-3 px-2">
                                    <div class="text-white"><?php echo htmlspecialchars($topup['agent_username']); ?></div>
                                    <small class="text-gray-400"><?php echo htmlspecialchars($topup['agent_email']); ?></small>
                                </td>
                                <td class="py-3 px-2 text-white"><?php echo htmlspecialchars($topup['store_name']); ?></td>
                                <td class="py-3 px-2">
                                    <div class="text-white"><?php echo htmlspecialchars($topup['owner_username']); ?></div>
                                    <small class="text-gray-400"><?php echo htmlspecialchars($topup['owner_email']); ?></small>
                                </td>
                                <td class="py-3 px-2 text-right text-green-400 font-semibold">GH₵ <?php echo number_format($topup['base_amount'], 2); ?></td>
                                <td class="py-3 px-2 text-right text-yellow-400">GH₵ <?php echo number_format($topup['charge_amount'], 2); ?></td>
                                <td class="py-3 px-2 text-right text-white font-semibold">GH₵ <?php echo number_format($topup['total_amount'], 2); ?></td>
                                <td class="py-3 px-2 text-center">
                                    <?php
                                    $statusColors = [
                                        'pending' => 'bg-yellow-600 text-yellow-100',
                                        'processing' => 'bg-blue-600 text-blue-100',
                                        'completed' => 'bg-green-600 text-green-100',
                                        'failed' => 'bg-red-600 text-red-100',
                                        'cancelled' => 'bg-gray-600 text-gray-100'
                                    ];
                                    $statusColor = $statusColors[$topup['payment_status']] ?? 'bg-gray-600 text-gray-100';
                                    ?>
                                    <span class="px-2 py-1 rounded text-xs font-semibold <?php echo $statusColor; ?>">
                                        <?php echo ucfirst($topup['payment_status']); ?>
                                    </span>
                                </td>
                                <td class="py-3 px-2 text-gray-300">
                                    <?php if ($topup['credited_at']): ?>
                                        <?php echo date('Y-m-d H:i', strtotime($topup['credited_at'])); ?>
                                    <?php else: ?>
                                        <span class="text-gray-500">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="py-3 px-2">
                                    <code class="text-blue-400 text-xs"><?php echo htmlspecialchars($topup['payment_reference']); ?></code>
                                </td>
                                <td class="py-3 px-2">
                                    <small class="text-gray-400"><?php echo htmlspecialchars($topup['ip_address'] ?? 'N/A'); ?></small>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
            <div class="mt-6 flex justify-center items-center gap-2">
                <a href="index.php?page=subagent_topups&page_num=<?php echo $pageNum - 1; ?><?php echo $filterStoreId ? '&store_id=' . $filterStoreId : ''; ?><?php echo $filterUserId ? '&user_id=' . $filterUserId : ''; ?><?php echo $filterStatus ? '&status=' . $filterStatus : ''; ?><?php echo $filterStartDate ? '&start_date=' . $filterStartDate : ''; ?><?php echo $filterEndDate ? '&end_date=' . $filterEndDate : ''; ?>" 
                   class="px-4 py-2 bg-gray-700 text-white rounded-lg hover:bg-gray-600 transition-colors <?php echo $pageNum <= 1 ? 'opacity-50 cursor-not-allowed' : ''; ?>"
                   <?php echo $pageNum <= 1 ? 'onclick="return false;"' : ''; ?>>
                    <i class="fas fa-chevron-left mr-2"></i>Previous
                </a>
                <span class="text-gray-300 px-4">
                    Page <?php echo $pageNum; ?> of <?php echo $totalPages; ?>
                </span>
                <a href="index.php?page=subagent_topups&page_num=<?php echo $pageNum + 1; ?><?php echo $filterStoreId ? '&store_id=' . $filterStoreId : ''; ?><?php echo $filterUserId ? '&user_id=' . $filterUserId : ''; ?><?php echo $filterStatus ? '&status=' . $filterStatus : ''; ?><?php echo $filterStartDate ? '&start_date=' . $filterStartDate : ''; ?><?php echo $filterEndDate ? '&end_date=' . $filterEndDate : ''; ?>" 
                   class="px-4 py-2 bg-gray-700 text-white rounded-lg hover:bg-gray-600 transition-colors <?php echo $pageNum >= $totalPages ? 'opacity-50 cursor-not-allowed' : ''; ?>"
                   <?php echo $pageNum >= $totalPages ? 'onclick="return false;"' : ''; ?>>
                    Next<i class="fas fa-chevron-right ml-2"></i>
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

