<?php 
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);

// Check if admin is authenticated
$adminAuth->requireAuth('admin_login.php');

// Get the selected date or default to today's date
date_default_timezone_set('GMT');
$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// Build query to fetch only agent deposits (credits to agent balance)
$whereConditions = ["bh.reason = 'payment'"];
$params = [];
$paramTypes = '';

// Add date filter
if ($date) {
    $whereConditions[] = "DATE(bh.created_at) = ?";
    $params[] = $date;
    $paramTypes .= 's';
}

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

// Query to fetch agent deposits (only positive balance changes with reason 'payment')
$query = "
    SELECT 
        bh.id,
        bh.agent_id,
        bh.change_amount,
        bh.balance_after,
        (bh.balance_after - bh.change_amount) as balance_before,
        bh.created_at,
        a.username,
        a.role
    FROM balance_history bh
    LEFT JOIN agents a ON bh.agent_id = a.id
    $whereClause
    ORDER BY bh.created_at DESC
";

// Execute query with prepared statement
if (!empty($params)) {
    $stmt = $conn->prepare($query);
    $stmt->bind_param($paramTypes, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = mysqli_query($conn, $query);
}

// Get total deposits for the selected date
$totalQuery = "
    SELECT 
        COUNT(*) as total_deposits,
        COALESCE(SUM(bh.change_amount), 0) as total_amount
    FROM balance_history bh
    $whereClause
";

if (!empty($params)) {
    $totalStmt = $conn->prepare($totalQuery);
    $totalStmt->bind_param($paramTypes, ...$params);
    $totalStmt->execute();
    $totalResult = $totalStmt->get_result();
} else {
    $totalResult = mysqli_query($conn, $totalQuery);
}

$totalStats = mysqli_fetch_assoc($totalResult);

// Set page variables for header
$page_title = 'Agent Deposits';
$page_description = 'View and manage agent balance deposits and credits';
?>

<div class="p-6">
        <!-- Page Header -->
    <div class="bg-gradient-to-br from-glass-800 to-glass-700 rounded-xl p-8 mb-8 border border-glass-600 shadow-2xl">
        <h1 class="text-4xl font-bold text-white mb-3 flex items-center">
            <i class="fas fa-money-bill-wave mr-4 text-green-400"></i>
            <span class="bg-gradient-to-r from-green-400 to-blue-400 bg-clip-text text-transparent">
                Agent Deposits
            </span>
        </h1>
        <p class="text-glass-300 text-lg">Monitor and track agent balance deposits and credits</p>
        </div>

        <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
        <div class="bg-gradient-to-br from-glass-800 to-glass-700 rounded-xl p-6 border border-glass-600 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
            <div class="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-blue-500 to-cyan-500"></div>
            <div class="flex items-center">
                <div class="p-3 bg-blue-500/20 rounded-xl">
                    <i class="fas fa-list text-blue-400 text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-glass-400 text-sm font-semibold uppercase tracking-wide">Total Deposits</p>
                    <p class="text-3xl font-bold text-white"><?= number_format($totalStats['total_deposits']) ?></p>
                </div>
            </div>
        </div>

        <div class="bg-gradient-to-br from-glass-800 to-glass-700 rounded-xl p-6 border border-glass-600 shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
            <div class="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-green-500 to-emerald-500"></div>
            <div class="flex items-center">
                <div class="p-3 bg-green-500/20 rounded-xl">
                    <i class="fas fa-money-bill text-green-400 text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-glass-400 text-sm font-semibold uppercase tracking-wide">Total Amount</p>
                    <p class="text-3xl font-bold text-white">GHC <?= number_format($totalStats['total_amount'] ?? 0, 2) ?></p>
                </div>
            </div>
        </div>
            </div>
            
    <!-- Date Filter -->
    <div class="bg-gradient-to-br from-glass-800 to-glass-700 rounded-xl mb-8 border border-glass-600 shadow-lg">
        <div class="px-6 py-4 border-b border-glass-600">
            <h2 class="text-xl font-bold text-white flex items-center">
                <i class="fas fa-calendar mr-3 text-blue-400"></i>Filter by Date
            </h2>
        </div>
        <div class="p-6">
            <form method="GET" action="index.php" class="max-w-md mx-auto">
                <input type="hidden" name="page" value="deposits">
                <div class="flex space-x-4">
                    <div class="flex-1">
                        <label for="date" class="block text-sm font-semibold text-glass-300 mb-2">
                            <i class="fas fa-calendar mr-2"></i>Select Date
                        </label>
                        <input 
                            type="date" 
                            id="date" 
                            name="date" 
                            class="w-full px-4 py-3 bg-glass-700 border border-glass-600 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors" 
                            value="<?= htmlspecialchars($date) ?>"
                        >
                    </div>
                    <div class="flex items-end">
                        <button type="submit" class="bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-200 hover:shadow-lg hover:-translate-y-0.5 flex items-center">
                            <i class="fas fa-search mr-2"></i>Filter
                        </button>
                    </div>
                </div>
            </form>
        </div>
        </div>

        <!-- Deposits Table -->
    <div class="bg-gradient-to-br from-glass-800 to-glass-700 rounded-xl border border-glass-600 shadow-lg overflow-hidden">
        <div class="px-6 py-4 border-b border-glass-600">
            <h2 class="text-xl font-bold text-white flex items-center">
                <i class="fas fa-table mr-3 text-green-400"></i>Agent Deposits
            </h2>
            <p class="text-glass-300 text-sm mt-1">
                    Deposits for <?= date('F j, Y', strtotime($date)) ?>
                </p>
            </div>

            <div class="overflow-x-auto">
            <?php if (mysqli_num_rows($result) > 0): ?>
                <table class="w-full">
                <thead class="bg-glass-700">
                    <tr>
                        <th class="px-6 py-4 text-left text-xs font-bold text-glass-300 uppercase tracking-wider">Agent</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-glass-300 uppercase tracking-wider">Agent ID</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-glass-300 uppercase tracking-wider">Deposit Amount</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-glass-300 uppercase tracking-wider">Balance Before</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-glass-300 uppercase tracking-wider">Balance After</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-glass-300 uppercase tracking-wider">Date & Time</th>
                        </tr>
                    </thead>
                <tbody class="divide-y divide-glass-600">
                    <?php while ($row = mysqli_fetch_assoc($result)): ?>
                    <tr class="hover:bg-glass-700/50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="w-10 h-10 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
                                        <i class="fas fa-user text-white text-sm"></i>
                                    </div>
                                <div class="ml-4">
                                    <div class="text-sm font-semibold text-white"><?= htmlspecialchars($row['username']) ?></div>
                                    <div class="text-sm text-glass-400"><?= ucfirst($row['role']) ?></div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-blue-500/20 text-blue-400 border border-blue-500/30">
                                #<?= htmlspecialchars($row['agent_id']) ?>
                            </span>
                            </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-green-500/20 text-green-400 border border-green-500/30">
                                <i class="fas fa-plus mr-1"></i>GHC <?= number_format($row['change_amount'] ?? 0, 2) ?>
                                </span>
                            </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-glass-300">
                            GHC <?= number_format($row['balance_before'] ?? 0, 2) ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-white">
                            GHC <?= number_format($row['balance_after'] ?? 0, 2) ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-glass-400">
                                <?= date('M j, Y g:i A', strtotime($row['created_at'])) ?>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            <?php else: ?>
            <div class="p-12 text-center">
                <div class="w-20 h-20 bg-glass-700 rounded-full flex items-center justify-center mx-auto mb-6">
                    <i class="fas fa-inbox text-glass-400 text-3xl"></i>
                </div>
                <h3 class="text-xl font-semibold text-glass-300 mb-2">No Deposits Found</h3>
                <p class="text-glass-400">No agent deposits found for <?= date('F j, Y', strtotime($date)) ?></p>
                <div class="mt-6">
                    <a href="index.php?page=deposits&date=<?= date('Y-m-d') ?>" class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors">
                        <i class="fas fa-calendar-day mr-2"></i>View Today's Deposits
                    </a>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
/* Professional Dark Theme for Agent Deposits with Glass Color */
body {
    background-color: #0a0a0a !important;
    color: #e5e5e5 !important;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* Professional Card Styling with Glass Color */
.bg-gradient-to-br {
    background: linear-gradient(135deg, #1F2937 0%, #374151 100%) !important;
}

.from-glass-800 {
    --tw-gradient-from: #1F2937 !important;
}

.to-glass-700 {
    --tw-gradient-to: #374151 !important;
}

.border-glass-600 {
    border-color: #4B5563 !important;
}

/* Professional Text Colors */
.text-white {
    color: #ffffff !important;
}

.text-glass-300 {
    color: #D1D5DB !important;
}

.text-glass-400 {
    color: #9CA3AF !important;
}

/* Professional Form Inputs */
.bg-glass-700 {
    background-color: #374151 !important;
    border-color: #4B5563 !important;
    color: #e5e5e5 !important;
}

.bg-glass-700:focus {
    border-color: #6B7280 !important;
    box-shadow: 0 0 0 2px rgba(107, 114, 128, 0.2) !important;
    outline: none !important;
}

/* Professional Buttons */
.bg-blue-600 {
    background-color: #404040 !important;
    border: 1px solid #505050 !important;
    color: #ffffff !important;
    transition: all 0.2s ease !important;
}

.bg-blue-600:hover {
    background-color: #505050 !important;
    border-color: #606060 !important;
}

.bg-blue-700 {
    background-color: #505050 !important;
}

.bg-blue-700:hover {
    background-color: #606060 !important;
}

/* Professional Table Styling */
.bg-glass-700 {
    background-color: #374151 !important;
}

.divide-glass-600 {
    border-color: #4B5563 !important;
}

.hover\:bg-glass-700\/50:hover {
    background-color: rgba(55, 65, 81, 0.5) !important;
}

/* Professional Status Badges */
.bg-green-500\/20 {
    background-color: rgba(16, 42, 16, 0.8) !important;
    color: #60d060 !important;
    border: 1px solid rgba(42, 74, 42, 0.5) !important;
}

.bg-blue-500\/20 {
    background-color: rgba(26, 35, 50, 0.8) !important;
    color: #80a0c0 !important;
    border: 1px solid rgba(42, 58, 74, 0.5) !important;
}

/* Professional Icon Colors */
.text-green-400 {
    color: #60d060 !important;
}

.text-blue-400 {
    color: #80a0c0 !important;
}

/* Professional Shadows */
.shadow-lg {
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2) !important;
}

.shadow-xl {
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.4), 0 10px 10px -5px rgba(0, 0, 0, 0.2) !important;
}

.shadow-2xl {
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5) !important;
}

/* Professional Hover Effects */
.hover\:-translate-y-1:hover {
    transform: translateY(-4px) !important;
}

.hover\:-translate-y-0\.5:hover {
    transform: translateY(-2px) !important;
}

/* Professional Transitions */
* {
    transition: all 0.2s ease !important;
}

/* Professional Typography */
h1, h2, h3, h4, h5, h6 {
    color: #ffffff !important;
    font-weight: 600 !important;
}

.text-4xl {
    font-size: 2.25rem !important;
    line-height: 2.5rem !important;
}

.text-xl {
    font-size: 1.25rem !important;
    line-height: 1.75rem !important;
}

/* Professional Focus States */
input:focus, select:focus, textarea:focus {
    outline: none !important;
    border-color: #606060 !important;
    box-shadow: 0 0 0 2px rgba(96, 96, 96, 0.2) !important;
}

/* Professional Responsive Design */
@media (max-width: 768px) {
    .grid-cols-1 {
        grid-template-columns: repeat(1, minmax(0, 1fr)) !important;
    }
}

@media (min-width: 768px) {
    .md\:grid-cols-2 {
        grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
    }
}
</style>