<?php
/**
 * Store Agents Balance History - For Store Owners to view their agents' balance history
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';

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

$userId = $_SESSION['user_id'];

// Load store
$storeManager = new StoreManager($conn);
$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;
$filterStartDate = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$filterEndDate = isset($_GET['end_date']) ? $_GET['end_date'] : '';
$filterReason = isset($_GET['reason']) ? $_GET['reason'] : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 50; // Records per page

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

// Get all agents for this store
$agents = $storeManager->getStoreAgents($store['id']);

// Build WHERE clause - only show balance history for agents in this store
$agentIds = array_column($agents, 'id');
if (empty($agentIds)) {
    $agentIds = [0]; // No agents, so no results
}

$placeholders = str_repeat('?,', count($agentIds) - 1) . '?';
$whereConditions = ["bh.agent_id IN ($placeholders)"];
$params = $agentIds;
$paramTypes = str_repeat('i', count($agentIds));

// Filter by specific agent
if ($filterAgentId > 0 && in_array($filterAgentId, $agentIds)) {
    $whereConditions = ["bh.agent_id = ?"];
    $params = [$filterAgentId];
    $paramTypes = 'i';
}

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

// Reason filter
if ($filterReason) {
    $whereConditions[] = "bh.reason = ?";
    $params[] = $filterReason;
    $paramTypes .= 's';
}

$whereClause = 'WHERE ' . implode(' AND ', $whereConditions);

// Get total count for pagination
$countQuery = "SELECT COUNT(*) as total FROM balance_history bh $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 balance history records
$query = "
    SELECT 
        bh.id,
        bh.agent_id,
        a.username as agent_username,
        a.email as agent_email,
        bh.change_amount,
        bh.balance_after,
        (bh.balance_after - bh.change_amount) as balance_before,
        bh.reason,
        bh.ref_id,
        bh.beneficiary_number,
        bh.created_at
    FROM balance_history bh
    INNER JOIN agents a ON bh.agent_id = a.id
    $whereClause
    ORDER BY bh.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();
    $balanceHistory = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} else {
    $balanceHistory = [];
}

// Get summary statistics
$summaryQuery = "
    SELECT 
        COUNT(*) as total_transactions,
        SUM(CASE WHEN bh.change_amount > 0 THEN bh.change_amount ELSE 0 END) as total_credits,
        SUM(CASE WHEN bh.change_amount < 0 THEN ABS(bh.change_amount) ELSE 0 END) as total_debits
    FROM balance_history bh
    $whereClause
";

$summaryStmt = $conn->prepare($summaryQuery);
if ($summaryStmt) {
    $summaryStmt->bind_param($paramTypes, ...$params);
    $summaryStmt->execute();
    $summaryResult = $summaryStmt->get_result();
    $summary = $summaryResult->fetch_assoc();
    $summaryStmt->close();
    
    // Ensure all values are not null (SUM returns NULL when no rows match)
    $summary['total_transactions'] = isset($summary['total_transactions']) ? (int)$summary['total_transactions'] : 0;
    $summary['total_credits'] = isset($summary['total_credits']) && $summary['total_credits'] !== null ? (float)$summary['total_credits'] : 0.00;
    $summary['total_debits'] = isset($summary['total_debits']) && $summary['total_debits'] !== null ? (float)$summary['total_debits'] : 0.00;
} else {
    $summary = ['total_transactions' => 0, 'total_credits' => 0.00, 'total_debits' => 0.00];
}

// Get unique reasons for filter dropdown
$reasonsQuery = "
    SELECT DISTINCT reason 
    FROM balance_history bh
    WHERE bh.agent_id IN ($placeholders)
    ORDER BY reason
";
$reasonsStmt = $conn->prepare($reasonsQuery);
$reasonsStmt->bind_param(str_repeat('i', count($agentIds)), ...$agentIds);
$reasonsStmt->execute();
$reasonsResult = $reasonsStmt->get_result();
$reasons = [];
while ($row = $reasonsResult->fetch_assoc()) {
    $reasons[] = $row['reason'];
}
$reasonsStmt->close();

?>
<!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>Agents Balance History - <?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;
        }
    </style>
</head>

<body class="bg-gray-900">
    <?php renderStoreNav($store, 'history'); ?>
    
    <!-- Back to Dashboard Button (Mobile) -->
    <div class="md:hidden bg-gray-800 border-b border-gray-700 px-3 py-2">
        <a href="store_dashboard.php" class="inline-flex items-center gap-2 text-blue-400 hover:text-blue-300 text-sm font-medium btn-touch">
            <i class="fas fa-arrow-left"></i>
            <span>Back to Dashboard</span>
        </a>
    </div>

    <div class="container mx-auto px-4 py-8">
        <!-- Page Header -->
        <div class="mb-8">
            <h2 class="text-3xl font-bold text-white mb-2">
                <i class="fas fa-history mr-2"></i>
                Agents Balance History
            </h2>
            <p class="text-gray-400">View balance transactions for all your store agents</p>
        </div>

        <!-- Summary Cards -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <div class="bg-gray-800 rounded-lg p-6 border border-gray-700">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-400 text-sm mb-1">Total Transactions</p>
                        <p class="text-2xl font-bold text-white"><?php echo number_format($summary['total_transactions'] ?? 0); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-blue-600 rounded-lg flex items-center justify-center">
                        <i class="fas fa-list text-white"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-gray-800 rounded-lg p-6 border border-gray-700">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-400 text-sm mb-1">Total Credits</p>
                        <p class="text-2xl font-bold text-green-400">GH₵ <?php echo number_format($summary['total_credits'] ?? 0.00, 2); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-green-600 rounded-lg flex items-center justify-center">
                        <i class="fas fa-arrow-up text-white"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-gray-800 rounded-lg p-6 border border-gray-700">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-400 text-sm mb-1">Total Debits</p>
                        <p class="text-2xl font-bold text-red-400">GH₵ <?php echo number_format($summary['total_debits'] ?? 0.00, 2); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-red-600 rounded-lg flex items-center justify-center">
                        <i class="fas fa-arrow-down text-white"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="bg-gray-800 rounded-lg p-6 border border-gray-700 mb-6">
            <h3 class="text-lg font-bold text-white mb-4">
                <i class="fas fa-filter mr-2"></i>Filters
            </h3>
            <form method="GET" action="" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Agent</label>
                    <select name="agent_id" class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                        <option value="0">All 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 text-gray-400 mb-2">Start Date</label>
                    <input type="date" name="start_date" value="<?php echo htmlspecialchars($filterStartDate); ?>" 
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">End Date</label>
                    <input type="date" name="end_date" value="<?php echo htmlspecialchars($filterEndDate); ?>" 
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Reason</label>
                    <select name="reason" class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                        <option value="">All Reasons</option>
                        <?php foreach ($reasons as $reason): ?>
                        <option value="<?php echo htmlspecialchars($reason); ?>" <?php echo $filterReason == $reason ? 'selected' : ''; ?>>
                            <?php echo ucfirst(str_replace('_', ' ', $reason)); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="md: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">
                        <i class="fas fa-search mr-2"></i>Apply Filters
                    </button>
                    <a href="store_agents_balance_history.php" class="bg-gray-600 text-white px-6 py-2 rounded-lg hover:bg-gray-700">
                        <i class="fas fa-redo mr-2"></i>Reset
                    </a>
                </div>
            </form>
        </div>

        <!-- Balance History Table -->
        <div class="bg-gray-800 rounded-lg p-6 border border-gray-700">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-gray-700 text-left">
                            <th class="pb-3 text-gray-400 font-medium">Date & Time</th>
                            <th class="pb-3 text-gray-400 font-medium">Agent</th>
                            <th class="pb-3 text-gray-400 font-medium">Reason</th>
                            <th class="pb-3 text-gray-400 font-medium">Change Amount</th>
                            <th class="pb-3 text-gray-400 font-medium">Balance Before</th>
                            <th class="pb-3 text-gray-400 font-medium">Balance After</th>
                            <th class="pb-3 text-gray-400 font-medium">Reference</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($balanceHistory)): ?>
                        <tr>
                            <td colspan="7" class="py-8 text-center text-gray-400">
                                <i class="fas fa-inbox text-4xl mb-2"></i>
                                <p>No balance history found</p>
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($balanceHistory as $record): ?>
                        <tr class="border-b border-gray-700 hover:bg-gray-700/50">
                            <td class="py-3 text-gray-300 text-sm">
                                <?php echo date('Y-m-d H:i:s', strtotime($record['created_at'])); ?>
                            </td>
                            <td class="py-3">
                                <div>
                                    <div class="text-white font-medium"><?php echo htmlspecialchars($record['agent_username']); ?></div>
                                    <div class="text-gray-400 text-xs"><?php echo htmlspecialchars($record['agent_email'] ?? 'N/A'); ?></div>
                                </div>
                            </td>
                            <td class="py-3">
                                <span class="px-2 py-1 rounded-full text-xs font-medium
                                    <?php
                                    switch($record['reason']) {
                                        case 'order': echo 'bg-red-900 text-red-300'; break;
                                        case 'payment': echo 'bg-green-900 text-green-300'; break;
                                        case 'refund': echo 'bg-blue-900 text-blue-300'; break;
                                        case 'manual_adjustment': echo 'bg-yellow-900 text-yellow-300'; break;
                                        default: echo 'bg-gray-700 text-gray-300';
                                    }
                                    ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $record['reason'])); ?>
                                </span>
                            </td>
                            <td class="py-3">
                                <span class="font-bold <?php echo $record['change_amount'] >= 0 ? 'text-green-400' : 'text-red-400'; ?>">
                                    <?php 
                                    $changeAmount = isset($record['change_amount']) && $record['change_amount'] !== null ? (float)$record['change_amount'] : 0.00;
                                    echo $changeAmount >= 0 ? '+' : '';
                                    ?>GH₵ <?php echo number_format($changeAmount, 2); ?>
                                </span>
                            </td>
                            <td class="py-3 text-gray-300">
                                <?php 
                                $balanceBefore = isset($record['balance_before']) && $record['balance_before'] !== null ? (float)$record['balance_before'] : 0.00;
                                ?>GH₵ <?php echo number_format($balanceBefore, 2); ?>
                            </td>
                            <td class="py-3 text-white font-bold">
                                <?php 
                                $balanceAfter = isset($record['balance_after']) && $record['balance_after'] !== null ? (float)$record['balance_after'] : 0.00;
                                ?>GH₵ <?php echo number_format($balanceAfter, 2); ?>
                            </td>
                            <td class="py-3 text-gray-300 text-sm">
                                <?php if ($record['ref_id']): ?>
                                    <div>ID: <?php echo $record['ref_id']; ?></div>
                                <?php endif; ?>
                                <?php if ($record['beneficiary_number']): ?>
                                    <div class="text-xs"><?php echo htmlspecialchars($record['beneficiary_number']); ?></div>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
            <div class="mt-6 flex items-center justify-between">
                <div class="text-gray-400 text-sm">
                    Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $limit, $totalRecords); ?> of <?php echo number_format($totalRecords); ?> records
                </div>
                <div class="flex gap-2">
                    <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&agent_id=<?php echo $filterAgentId; ?>&start_date=<?php echo htmlspecialchars($filterStartDate); ?>&end_date=<?php echo htmlspecialchars($filterEndDate); ?>&reason=<?php echo htmlspecialchars($filterReason); ?>" 
                       class="bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600">
                        <i class="fas fa-chevron-left mr-1"></i> Previous
                    </a>
                    <?php endif; ?>
                    
                    <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                    <a href="?page=<?php echo $i; ?>&agent_id=<?php echo $filterAgentId; ?>&start_date=<?php echo htmlspecialchars($filterStartDate); ?>&end_date=<?php echo htmlspecialchars($filterEndDate); ?>&reason=<?php echo htmlspecialchars($filterReason); ?>" 
                       class="px-4 py-2 rounded-lg <?php echo $i == $page ? 'bg-blue-600 text-white' : 'bg-gray-700 text-white hover:bg-gray-600'; ?>">
                        <?php echo $i; ?>
                    </a>
                    <?php endfor; ?>
                    
                    <?php if ($page < $totalPages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&agent_id=<?php echo $filterAgentId; ?>&start_date=<?php echo htmlspecialchars($filterStartDate); ?>&end_date=<?php echo htmlspecialchars($filterEndDate); ?>&reason=<?php echo htmlspecialchars($filterReason); ?>" 
                       class="bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600">
                        Next <i class="fas fa-chevron-right ml-1"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </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>
    
    <style>
        .btn-touch {
            min-height: 44px;
            min-width: 44px;
        }
    </style>
</body>
</html>


