<?php
/**
 * Store Daily Transaction History - For Store Owners
 * Shows all transactions (orders and balance changes) for today
 */

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

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

$userId = $_SESSION['user_id'];
$today = date('Y-m-d');

// 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 today's orders from orders table (direct customer orders) with balance history
// IMPORTANT: Orders debit the STORE OWNER's balance, so balance_history should be joined with store owner ID
$todayOrders = [];
$directOrdersStmt = $conn->prepare("
    SELECT 
        o.id,
        o.order_reference,
        o.network_type,
        o.package_size,
        o.beneficiary_number as recipient_number,
        o.amount,
        o.status,
        o.created_at,
        a.username as agent_username,
        'direct' as order_type,
        'order' as transaction_type,
        (bh.balance_after - bh.change_amount) as balance_before,
        bh.balance_after
    FROM orders o
    LEFT JOIN agents a ON o.agent_id = a.id
    LEFT JOIN balance_history bh ON bh.ref_id = o.id AND bh.reason = 'order' AND bh.agent_id = ?
    WHERE o.store_id = ? AND DATE(o.created_at) = ?
    ORDER BY o.created_at DESC
");
$directOrdersStmt->bind_param("iis", $userId, $store['id'], $today);
$directOrdersStmt->execute();
$directResult = $directOrdersStmt->get_result();
while ($row = $directResult->fetch_assoc()) {
    $todayOrders[] = $row;
}
$directOrdersStmt->close();

// Get today's orders from agent_orders table (agent orders) with balance history
// This includes orders placed by agents through the regular page who belong to this store
// IMPORTANT: Orders debit the STORE OWNER's balance, so balance_history should be joined with store owner ID
$agentOrdersStmt = $conn->prepare("
    SELECT 
        ao.id,
        NULL as order_reference,
        ao.network_type,
        ao.package_size,
        ao.beneficiary_number as recipient_number,
        ao.amount,
        ao.status,
        ao.created_at,
        a.username as agent_username,
        'agent' as order_type,
        'order' as transaction_type,
        (bh.balance_after - bh.change_amount) as balance_before,
        bh.balance_after
    FROM agent_orders ao
    INNER JOIN agents a ON ao.agent_id = a.id
    LEFT JOIN balance_history bh ON bh.ref_id = ao.id AND bh.reason = 'order' AND bh.agent_id = ?
    WHERE (ao.store_id = ? OR (ao.store_id IS NULL AND a.store_id = ?)) AND DATE(ao.created_at) = ?
    ORDER BY ao.created_at DESC
");
$agentOrdersStmt->bind_param("iiis", $userId, $store['id'], $store['id'], $today);
$agentOrdersStmt->execute();
$agentResult = $agentOrdersStmt->get_result();
while ($row = $agentResult->fetch_assoc()) {
    $todayOrders[] = $row;
}
$agentOrdersStmt->close();

// Get today's balance history for store owner
$balanceHistoryStmt = $conn->prepare("
    SELECT 
        bh.id,
        NULL as order_reference,
        NULL as network_type,
        NULL as package_size,
        bh.beneficiary_number as recipient_number,
        bh.change_amount as amount,
        CASE 
            WHEN bh.change_amount > 0 THEN 'credit'
            WHEN bh.change_amount < 0 THEN 'debit'
            ELSE 'neutral'
        END as status,
        bh.created_at,
        NULL as agent_username,
        NULL as order_type,
        bh.reason as transaction_type,
        (bh.balance_after - bh.change_amount) as balance_before,
        bh.balance_after,
        bh.ref_id
    FROM balance_history bh
    WHERE bh.agent_id = ? AND DATE(bh.created_at) = ? AND bh.reason != 'order'
    ORDER BY bh.created_at DESC
");
$balanceHistoryStmt->bind_param("is", $userId, $today);
$balanceHistoryStmt->execute();
$balanceResult = $balanceHistoryStmt->get_result();
$balanceHistory = [];
while ($row = $balanceResult->fetch_assoc()) {
    $balanceHistory[] = $row;
}
$balanceHistoryStmt->close();

// Combine all transactions and sort by time
$allTransactions = array_merge($todayOrders, $balanceHistory);
usort($allTransactions, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

// Calculate summary statistics
$totalOrders = count($todayOrders);
$totalRevenue = array_sum(array_column($todayOrders, 'amount'));
$totalCredits = array_sum(array_filter(array_column($balanceHistory, 'amount'), function($amt) { return $amt > 0; }));
$totalDebits = abs(array_sum(array_filter(array_column($balanceHistory, 'amount'), function($amt) { return $amt < 0; })));
$totalBalanceChanges = count($balanceHistory);
$completedOrders = count(array_filter($todayOrders, function($o) { return $o['status'] == 'completed'; }));
$pendingOrders = count(array_filter($todayOrders, function($o) { return $o['status'] == 'pending'; }));

// Get current balance
$balanceStmt = $conn->prepare("SELECT balance FROM agents WHERE id = ?");
$balanceStmt->bind_param("i", $userId);
$balanceStmt->execute();
$balanceResult = $balanceStmt->get_result();
$currentBalance = $balanceResult->fetch_assoc()['balance'] ?? 0;
$balanceStmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <title>Today's Transactions - <?php echo htmlspecialchars($store['store_name']); ?></title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <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">
        <!-- Summary Statistics -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
            <div class="bg-gradient-to-r from-blue-800 to-blue-900 rounded-lg p-6 border border-blue-700">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-blue-200 text-sm mb-1">Today's Orders</p>
                        <p class="text-3xl font-bold text-white"><?php echo $totalOrders; ?></p>
                        <p class="text-xs text-blue-300 mt-2">
                            <?php echo $completedOrders; ?> completed, <?php echo $pendingOrders; ?> pending
                        </p>
                    </div>
                    <div class="w-12 h-12 bg-blue-700 rounded-lg flex items-center justify-center">
                        <i class="fas fa-shopping-cart text-blue-200 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-gradient-to-r from-green-800 to-green-900 rounded-lg p-6 border border-green-700">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-green-200 text-sm mb-1">Today's Revenue</p>
                        <p class="text-3xl font-bold text-white">GH₵ <?php echo number_format($totalRevenue, 2); ?></p>
                        <p class="text-xs text-green-300 mt-2">From all orders</p>
                    </div>
                    <div class="w-12 h-12 bg-green-700 rounded-lg flex items-center justify-center">
                        <i class="fas fa-money-bill-wave text-green-200 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-gradient-to-r from-purple-800 to-purple-900 rounded-lg p-6 border border-purple-700">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-purple-200 text-sm mb-1">Balance Changes</p>
                        <p class="text-3xl font-bold text-white"><?php echo $totalBalanceChanges; ?></p>
                        <p class="text-xs text-purple-300 mt-2">
                            GH₵ <?php echo number_format($totalCredits, 2); ?> in, GH₵ <?php echo number_format($totalDebits, 2); ?> out
                        </p>
                    </div>
                    <div class="w-12 h-12 bg-purple-700 rounded-lg flex items-center justify-center">
                        <i class="fas fa-exchange-alt text-purple-200 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-gradient-to-r from-amber-800 to-amber-900 rounded-lg p-6 border border-amber-700">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-amber-200 text-sm mb-1">Current Balance</p>
                        <p class="text-3xl font-bold text-white">GH₵ <?php echo number_format($currentBalance, 2); ?></p>
                        <p class="text-xs text-amber-300 mt-2">As of now</p>
                    </div>
                    <div class="w-12 h-12 bg-amber-700 rounded-lg flex items-center justify-center">
                        <i class="fas fa-wallet text-amber-200 text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Transaction History -->
        <div class="bg-gray-800 rounded-lg p-6 border border-gray-700">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-2xl font-bold text-white">
                    <i class="fas fa-list mr-2"></i>
                    Transaction History for <?php echo date('F d, Y'); ?>
                </h2>
                <div class="flex items-center gap-2">
                    <button onclick="filterTransactions('all')" id="filter-all" 
                            class="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700">
                        All
                    </button>
                    <button onclick="filterTransactions('order')" id="filter-order"
                            class="px-3 py-1 bg-gray-700 text-gray-300 rounded text-sm hover:bg-gray-600">
                        Orders
                    </button>
                    <button onclick="filterTransactions('balance')" id="filter-balance"
                            class="px-3 py-1 bg-gray-700 text-gray-300 rounded text-sm hover:bg-gray-600">
                        Balance
                    </button>
                </div>
            </div>

            <?php if (empty($allTransactions)): ?>
            <div class="text-center py-12">
                <i class="fas fa-calendar-times text-5xl text-gray-600 mb-4"></i>
                <p class="text-gray-400 text-lg mb-2">No transactions today</p>
                <p class="text-gray-500 text-sm">All transactions for today will appear here</p>
            </div>
            <?php else: ?>
            <div class="overflow-x-auto table-wrapper -mx-4 sm:mx-0 px-4 sm:px-0">
                <table class="w-full min-w-[900px]">
                    <thead>
                        <tr class="border-b border-gray-700 text-left">
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Time</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Type</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Details</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Amount</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Status</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Balance Before</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Balance After</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($allTransactions as $transaction): ?>
                        <tr class="border-b border-gray-700 hover:bg-gray-700/30 transaction-row" 
                            data-type="<?php echo $transaction['transaction_type'] == 'order' ? 'order' : 'balance'; ?>">
                            <td class="py-2 sm:py-3 text-gray-300 text-xs sm:text-sm px-2">
                                <?php echo date('H:i:s', strtotime($transaction['created_at'])); ?>
                            </td>
                            <td class="py-2 sm:py-3 px-2">
                                <?php if ($transaction['transaction_type'] == 'order'): ?>
                                    <?php if ($transaction['order_type'] == 'agent'): ?>
                                    <span class="px-2 py-1 bg-blue-900 text-blue-300 rounded text-xs">
                                        <i class="fas fa-user-tie mr-1"></i><span class="hidden sm:inline">Agent Order</span><span class="sm:hidden">Agent</span>
                                    </span>
                                    <?php else: ?>
                                    <span class="px-2 py-1 bg-purple-900 text-purple-300 rounded text-xs">
                                        <i class="fas fa-shopping-bag mr-1"></i><span class="hidden sm:inline">Customer Order</span><span class="sm:hidden">Customer</span>
                                    </span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="px-2 py-1 bg-amber-900 text-amber-300 rounded text-xs">
                                        <i class="fas fa-exchange-alt mr-1"></i><span class="hidden sm:inline"><?php echo ucfirst(str_replace('_', ' ', $transaction['transaction_type'])); ?></span><span class="sm:hidden"><?php echo ucfirst(substr(str_replace('_', ' ', $transaction['transaction_type']), 0, 5)); ?></span>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="py-2 sm:py-3 text-white text-xs sm:text-sm px-2">
                                <?php if ($transaction['transaction_type'] == 'order'): ?>
                                    <div>
                                        <div class="font-medium">
                                            <?php if ($transaction['order_reference']): ?>
                                                <span class="hidden sm:inline">Ref: </span><?php echo htmlspecialchars($transaction['order_reference']); ?>
                                            <?php else: ?>
                                                #<?php echo $transaction['id']; ?>
                                            <?php endif; ?>
                                        </div>
                                        <div class="text-xs text-gray-400 mt-0.5 sm:mt-1">
                                            <?php if ($transaction['agent_username']): ?>
                                                <span class="hidden sm:inline">Agent: </span><?php echo htmlspecialchars($transaction['agent_username']); ?>
                                            <?php else: ?>
                                                <span class="hidden sm:inline">Direct Customer</span><span class="sm:hidden">Direct</span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="text-xs text-gray-400 hidden sm:block">
                                            <?php echo htmlspecialchars($transaction['package_size'] ?? ''); ?> - <?php echo strtoupper($transaction['network_type'] ?? ''); ?>
                                        </div>
                                        <?php if ($transaction['recipient_number']): ?>
                                        <div class="text-xs text-gray-500 hidden sm:block">
                                            <i class="fas fa-phone mr-1"></i><?php echo htmlspecialchars($transaction['recipient_number']); ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <div>
                                        <div class="font-medium">
                                            <?php echo ucfirst(str_replace('_', ' ', $transaction['transaction_type'])); ?>
                                        </div>
                                        <?php if ($transaction['recipient_number']): ?>
                                        <div class="text-xs text-gray-400 mt-0.5 sm:mt-1">
                                            <?php echo htmlspecialchars($transaction['recipient_number']); ?>
                                        </div>
                                        <?php endif; ?>
                                        <?php if ($transaction['ref_id']): ?>
                                        <div class="text-xs text-gray-500 hidden sm:block">
                                            Ref ID: <?php echo $transaction['ref_id']; ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td class="py-2 sm:py-3 px-2">
                                <?php if ($transaction['transaction_type'] == 'order'): ?>
                                    <span class="font-bold text-white text-xs sm:text-sm">GH₵ <?php echo number_format($transaction['amount'], 2); ?></span>
                                <?php else: ?>
                                    <span class="font-bold <?php echo $transaction['amount'] >= 0 ? 'text-green-400' : 'text-red-400'; ?> text-xs sm:text-sm">
                                        <?php echo $transaction['amount'] >= 0 ? '+' : ''; ?>GH₵ <?php echo number_format($transaction['amount'], 2); ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="py-2 sm:py-3 px-2">
                                <?php if ($transaction['transaction_type'] == 'order'): ?>
                                    <span class="px-2 sm:px-3 py-1 rounded-full text-xs font-medium 
                                        <?php 
                                        if ($transaction['status'] == 'completed') echo 'bg-green-900 text-green-300';
                                        elseif ($transaction['status'] == 'pending') echo 'bg-yellow-900 text-yellow-300';
                                        else echo 'bg-red-900 text-red-300';
                                        ?>">
                                        <span class="hidden sm:inline"><?php echo ucfirst($transaction['status']); ?></span>
                                        <span class="sm:hidden"><?php echo strtoupper(substr($transaction['status'], 0, 1)); ?></span>
                                    </span>
                                <?php else: ?>
                                    <span class="px-2 sm:px-3 py-1 rounded-full text-xs font-medium 
                                        <?php 
                                        if ($transaction['status'] == 'credit') echo 'bg-green-900 text-green-300';
                                        elseif ($transaction['status'] == 'debit') echo 'bg-red-900 text-red-300';
                                        else echo 'bg-gray-700 text-gray-300';
                                        ?>">
                                        <span class="hidden sm:inline"><?php echo ucfirst($transaction['status']); ?></span>
                                        <span class="sm:hidden"><?php echo strtoupper(substr($transaction['status'], 0, 1)); ?></span>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="py-2 sm:py-3 text-gray-300 text-xs sm:text-sm px-2">
                                <?php if (isset($transaction['balance_before']) && $transaction['balance_before'] !== null): ?>
                                    <div class="text-white font-medium">GH₵ <?php echo number_format($transaction['balance_before'], 2); ?></div>
                                <?php else: ?>
                                    <span class="text-gray-500">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-2 sm:py-3 text-gray-300 text-xs sm:text-sm px-2">
                                <?php if (isset($transaction['balance_after']) && $transaction['balance_after'] !== null): ?>
                                    <div class="text-white font-bold">GH₵ <?php echo number_format($transaction['balance_after'], 2); ?></div>
                                <?php else: ?>
                                    <span class="text-gray-500">-</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function filterTransactions(type) {
            const rows = document.querySelectorAll('.transaction-row');
            const buttons = document.querySelectorAll('[id^="filter-"]');
            
            // Reset all button styles
            buttons.forEach(btn => {
                btn.classList.remove('bg-blue-600', 'text-white');
                btn.classList.add('bg-gray-700', 'text-gray-300');
            });
            
            // Highlight active filter
            const activeBtn = document.getElementById('filter-' + type);
            if (activeBtn) {
                activeBtn.classList.remove('bg-gray-700', 'text-gray-300');
                activeBtn.classList.add('bg-blue-600', 'text-white');
            }
            
            // Filter rows
            rows.forEach(row => {
                if (type === 'all') {
                    row.style.display = '';
                } else {
                    row.style.display = row.dataset.type === type ? '' : 'none';
                }
            });
        }
    </script>
    
    <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>

