<?php
/**
 * Store Sub-Agent Top-ups Page
 * For Store Owners to view top-ups made by their sub-agents
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/SessionManager.php';
use App\classes\SessionManager;

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

$userId = $_SESSION['user_id'];

// SECURITY: Validate session
$sessionManager = new SessionManager($conn);
$sessionValidation = $sessionManager->validateSession($userId);

if (!$sessionValidation['valid']) {
    error_log("Invalid session detected - User ID: $userId, Reason: " . $sessionValidation['reason']);
    $sessionManager->forceLogout();
    header("Location: ../login.php?error=session_invalid");
    exit();
}

// MULTI-LAYER SECURITY CHECK: Verify user is actually a store owner
$storeManager = new StoreManager($conn);
$verification = $storeManager->verifyStoreOwner($userId);

if (!$verification['valid']) {
    error_log("Store Sub-Agent Top-ups Access Denied - User ID: $userId, Reason: " . $verification['reason']);
    header("Location: ../user_index.php");
    exit();
}

// Load store
$store = $storeManager->getStoreByOwnerId($userId);

if (!$store) {
    header("Location: store_dashboard.php");
    exit();
}

// Include reusable navigation
require_once 'includes/store_nav.php';

// Get filter parameters
$filterAgentId = isset($_GET['agent_id']) ? intval($_GET['agent_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;
$limit = 50;

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

// Build WHERE clause - only show top-ups for this store's sub-agents
$whereConditions = ["sat.store_id = ?"];
$params = [$store['id']];
$paramTypes = 'i';

// Filter by specific agent (must be a sub-agent of this store)
if ($filterAgentId > 0) {
    // Verify agent belongs to this store
    $verifyAgentStmt = $conn->prepare("SELECT id FROM agents WHERE id = ? AND store_id = ? AND is_store_owner = 0");
    $verifyAgentStmt->bind_param("ii", $filterAgentId, $store['id']);
    $verifyAgentStmt->execute();
    $verifyResult = $verifyAgentStmt->get_result();
    if ($verifyResult->num_rows > 0) {
        $whereConditions[] = "sat.user_id = ?";
        $params[] = $filterAgentId;
        $paramTypes .= 'i';
    }
    $verifyAgentStmt->close();
}

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 = 'WHERE ' . implode(' AND ', $whereConditions);

// Get total count
$countQuery = "SELECT COUNT(*) as total FROM subagent_topup_tracking sat $whereClause";
$countStmt = $conn->prepare($countQuery);
if ($countStmt) {
    $countStmt->bind_param($paramTypes, ...$params);
    $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.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
    FROM subagent_topup_tracking sat
    INNER JOIN agents a ON sat.user_id = a.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) {
    $summaryStmt->bind_param($paramTypes, ...$params);
    $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 sub-agents for this store for filter dropdown
$agents = $storeManager->getStoreAgents($store['id']);

// Base URL for store
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'];
$storeUrl = $baseUrl . "/store.php?slug=" . urlencode($store['store_slug']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <title>Sub-Agent Top-ups - <?php echo htmlspecialchars($store['store_name']); ?></title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
        }
        
        /* Mobile-first responsive styles */
        @media (max-width: 640px) {
            .container {
                padding-left: 0.75rem;
                padding-right: 0.75rem;
            }
        }
        
        /* Touch-friendly buttons */
        .btn-touch {
            min-height: 44px;
            min-width: 44px;
        }
        
        /* Smooth animations */
        * {
            transition: background-color 0.2s, transform 0.2s;
        }
    </style>
</head>
<body class="bg-gray-900">
    <?php renderStoreNav($store, 'history'); ?>

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

        <!-- Filters -->
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700 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="" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Sub-Agent</label>
                    <select name="agent_id" class="w-full bg-gray-700 text-white rounded-lg px-4 py-2 border border-gray-600 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20">
                        <option value="0">All Sub-Agents</option>
                        <?php foreach ($agents as $agent): ?>
                            <option value="<?php echo $agent['id']; ?>" <?php echo $filterAgentId == $agent['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($agent['username']); ?>
                            </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 text-white rounded-lg px-4 py-2 border border-gray-600 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20">
                        <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 text-white rounded-lg px-4 py-2 border border-gray-600 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20">
                </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 text-white rounded-lg px-4 py-2 border border-gray-600 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20">
                </div>
                <div class="sm:col-span-2 lg:col-span-4 flex gap-2">
                    <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors btn-touch">
                        <i class="fas fa-filter mr-2"></i>Apply Filters
                    </button>
                    <a href="store_subagent_topups.php" class="bg-gray-700 text-white px-6 py-2 rounded-lg hover:bg-gray-600 transition-colors btn-touch">
                        <i class="fas fa-times mr-2"></i>Clear
                    </a>
                </div>
            </form>
        </div>

        <!-- Top-ups Table -->
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700">
            <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">Date</th>
                            <th class="text-left py-3 px-2 text-gray-300 font-semibold">Sub-Agent</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>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($topups)): ?>
                            <tr>
                                <td colspan="8" class="text-center text-gray-400 py-8">
                                    <i class="fas fa-inbox fa-3x 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 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-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>
                                </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="?page_num=<?php echo $pageNum - 1; ?><?php echo $filterAgentId ? '&agent_id=' . $filterAgentId : ''; ?><?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' : ''; ?> btn-touch"
                       <?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="?page_num=<?php echo $pageNum + 1; ?><?php echo $filterAgentId ? '&agent_id=' . $filterAgentId : ''; ?><?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' : ''; ?> btn-touch"
                       <?php echo $pageNum >= $totalPages ? 'onclick="return false;"' : ''; ?>>
                        Next<i class="fas fa-chevron-right ml-2"></i>
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Mobile menu toggle
        document.getElementById('mobileMenuBtn').addEventListener('click', function() {
            const menu = document.getElementById('mobileMenu');
            menu.classList.toggle('hidden');
        });
        
        // Close mobile menu when clicking outside
        document.addEventListener('click', function(e) {
            const menu = document.getElementById('mobileMenu');
            const btn = document.getElementById('mobileMenuBtn');
            if (!menu.contains(e.target) && !btn.contains(e.target)) {
                menu.classList.add('hidden');
            }
        });
    </script>
</body>
</html>

