<?php 
// Include session handling
try {
    include_once 'services/session.php';
} catch (Exception $e) {
    die("Error including session.php: " . $e->getMessage());
}

// Check if user is logged in
if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

// Include database connection
try {
    require_once 'layouts/dbconn.php';
} catch (Exception $e) {
    die("Error including database connection: " . $e->getMessage());
}

// Test database connection
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed: " . ($conn->connect_error ?? 'Connection object not found'));
}

// Function to safely execute queries
if (!function_exists('safeQuery')) {
    function safeQuery($conn, $query, $params = []) {
        try {
            $stmt = $conn->prepare($query);
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            if (!empty($params)) {
                $types = str_repeat('s', count($params));
                $stmt->bind_param($types, ...$params);
            }
            
            $stmt->execute();
            $result = $stmt->get_result();
            $data = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            return $data;
        } catch (Exception $e) {
            error_log("Query error: " . $e->getMessage());
            return [];
        }
    }
}

// Get current wallet balance
$wallet_balance = ['usd' => 0, 'ssp' => 0, 'kes' => 0, 'ugx' => 0];
$wallet_id = null;

try {
    $stmt = $conn->prepare("SELECT wallet_id, balance_usd, balance_ssp, balance_kes, balance_ugx FROM wallets WHERE user_id = ? AND status = 'ACTIVE'");
    if ($stmt) {
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $wallet = $result->fetch_assoc();
            $wallet_id = $wallet['wallet_id'];
            $wallet_balance = [
                'usd' => $wallet['balance_usd'],
                'ssp' => $wallet['balance_ssp'],
                'kes' => $wallet['balance_kes'],
                'ugx' => $wallet['balance_ugx']
            ];
        }
    }
} catch (Exception $e) {
    error_log("Error getting wallet: " . $e->getMessage());
}

// Get transaction statistics
$stats = ['total_credit' => 0, 'total_debit' => 0, 'total_transactions' => 0];
if ($wallet_id) {
    try {
        $stats_result = safeQuery($conn, "
            SELECT 
                COUNT(*) as total_transactions,
                COALESCE(SUM(CASE WHEN transaction_type = 'CREDIT' THEN amount ELSE 0 END), 0) as total_credit,
                COALESCE(SUM(CASE WHEN transaction_type = 'DEBIT' THEN amount ELSE 0 END), 0) as total_debit
            FROM wallet_transactions
            WHERE wallet_id = ? AND status = 'COMPLETED'
        ", [$wallet_id]);
        
        if (!empty($stats_result)) {
            $stats = $stats_result[0];
        }
    } catch (Exception $e) {
        error_log("Error getting stats: " . $e->getMessage());
    }
}

// Get recent transactions
$transactions = [];
if ($wallet_id) {
    try {
        $transactions = safeQuery($conn, "
            SELECT 
                transaction_id,
                transaction_type,
                amount,
                currency,
                category,
                description,
                reference_type,
                reference_id,
                status,
                created_at
            FROM wallet_transactions
            WHERE wallet_id = ?
            ORDER BY created_at DESC
            LIMIT 10
        ", [$wallet_id]);
    } catch (Exception $e) {
        error_log("Error getting transactions: " . $e->getMessage());
    }
}

// Get recent topups
$recent_topups = [];
if ($wallet_id) {
    try {
        $recent_topups = safeQuery($conn, "
            SELECT amount, currency, status, created_at, payment_method, provider_reference
            FROM wallet_topups
            WHERE wallet_id = ?
            ORDER BY created_at DESC
            LIMIT 5
        ", [$wallet_id]);
    } catch (Exception $e) {
        error_log("Error getting topups: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php 
    $title = "Wallet Overview";
    if (file_exists('partials/title-meta.php')) {
        try {
            include_once 'partials/title-meta.php';
        } catch (Exception $e) {
            echo "<title>Wallet Overview - ConnectPay</title>\n";
        }
    } else {
        echo "<title>Wallet Overview - ConnectPay</title>\n";
    }
    ?>
    
    <?php 
    if (file_exists('partials/head-css.php')) {
        try {
            include_once 'partials/head-css.php';
        } catch (Exception $e) {
            echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
            echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
        }
    } else {
        echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
        echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
    }
    ?>
    
    <style>
        body {
            background-color: #f8f9fa;
        }
        
        .wallet-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .balance-card {
            background: rgba(255,255,255,0.1);
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            backdrop-filter: blur(10px);
        }
        
        .currency-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .currency-item:last-child {
            border-bottom: none;
        }
        
        .stats-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }
        
        .stat-item {
            text-align: center;
            padding: 1rem;
        }
        
        .stat-number {
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .transaction-card {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 12px;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .transaction-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            border-color: #007bff;
        }
        
        .transaction-credit {
            border-left: 4px solid #28a745;
        }
        
        .transaction-debit {
            border-left: 4px solid #dc3545;
        }
        
        .amount-credit {
            color: #28a745;
            font-weight: 600;
        }
        
        .amount-debit {
            color: #dc3545;
            font-weight: 600;
        }
    </style>
</head>

<body>

<div id="wrapper">
    <?php 
    $pagetitle = "Wallet Overview"; 
    if (file_exists('partials/menu.php')) {
        try {
            include_once 'partials/menu.php';
        } catch (Exception $e) {
            echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                    <div class="container">
                        <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                        <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                    </div>
                  </nav>';
        }
    } else {
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                    <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                </div>
              </nav>';
    }
    ?>

    <div class="content-page">
        <div class="content">
            <div class="container-fluid">
                
                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box mb-4">
                            <h4 class="page-title">
                                <i class="fas fa-wallet me-2"></i>
                                Wallet Overview
                            </h4>
                            <nav aria-label="breadcrumb">
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="customer-dashboard.php">Dashboard</a></li>
                                    <li class="breadcrumb-item active">Wallet Overview</li>
                                </ol>
                            </nav>
                        </div>
                    </div>
                </div>

                <!-- Wallet Header -->
                <div class="row">
                    <div class="col-12">
                        <div class="wallet-header">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h3 class="mb-3">
                                        <i class="fas fa-wallet me-2"></i>
                                        My Wallet
                                    </h3>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="balance-card">
                                                <h5 class="mb-3">Available Balance</h5>
                                                
                                                <div class="currency-item">
                                                    <div>
                                                        <i class="fas fa-dollar-sign me-2"></i>
                                                        <strong>USD</strong>
                                                    </div>
                                                    <div class="text-end">
                                                        <h4 class="mb-0">$<?php echo number_format($wallet_balance['usd'], 2); ?></h4>
                                                    </div>
                                                </div>
                                                
                                                <?php if ($wallet_balance['ssp'] > 0): ?>
                                                <div class="currency-item">
                                                    <div>
                                                        <i class="fas fa-coins me-2"></i>
                                                        <strong>SSP</strong>
                                                    </div>
                                                    <div class="text-end">
                                                        <h5 class="mb-0"><?php echo number_format($wallet_balance['ssp'], 0); ?></h5>
                                                    </div>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <?php if ($wallet_balance['kes'] > 0): ?>
                                                <div class="currency-item">
                                                    <div>
                                                        <i class="fas fa-coins me-2"></i>
                                                        <strong>KES</strong>
                                                    </div>
                                                    <div class="text-end">
                                                        <h5 class="mb-0"><?php echo number_format($wallet_balance['kes'], 0); ?></h5>
                                                    </div>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <?php if ($wallet_balance['ugx'] > 0): ?>
                                                <div class="currency-item">
                                                    <div>
                                                        <i class="fas fa-coins me-2"></i>
                                                        <strong>UGX</strong>
                                                    </div>
                                                    <div class="text-end">
                                                        <h5 class="mb-0"><?php echo number_format($wallet_balance['ugx'], 0); ?></h5>
                                                    </div>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-4 text-md-end">
                                    <div class="d-grid gap-2">
                                        <a href="topup-wallet.php" class="btn btn-light btn-lg">
                                            <i class="fas fa-plus me-2"></i>
                                            Top Up Wallet
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Transaction Statistics -->
                <div class="row">
                    <div class="col-12">
                        <div class="stats-card">
                            <h5 class="mb-4">
                                <i class="fas fa-chart-line me-2"></i>
                                Transaction Statistics
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="stat-item">
                                        <div class="stat-number text-primary"><?php echo $stats['total_transactions']; ?></div>
                                        <div class="text-muted">Total Transactions</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="stat-item">
                                        <div class="stat-number text-success">$<?php echo number_format($stats['total_credit'], 2); ?></div>
                                        <div class="text-muted">Total Credits</div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="stat-item">
                                        <div class="stat-number text-danger">$<?php echo number_format($stats['total_debit'], 2); ?></div>
                                        <div class="text-muted">Total Debits</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Transactions List -->
                <div class="row">
                    <div class="col-xl-8">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="header-title">
                                    <i class="fas fa-list me-2"></i>
                                    Recent Transactions
                                </h4>
                            </div>
                            <div class="card-body">
                                <?php if (empty($transactions)): ?>
                                <div class="text-center py-5">
                                    <i class="fas fa-history fa-4x mb-3 text-muted"></i>
                                    <h5>No transactions found</h5>
                                    <p class="text-muted mb-4">
                                        Your transaction history will appear here as you use your wallet.
                                    </p>
                                    <a href="topup-wallet.php" class="btn btn-primary">
                                        <i class="fas fa-plus me-2"></i>
                                        Add Your First Transaction
                                    </a>
                                </div>
                                <?php else: ?>
                                    <?php foreach ($transactions as $transaction): ?>
                                    <div class="transaction-card transaction-<?php echo strtolower($transaction['transaction_type']); ?>">
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div class="flex-grow-1">
                                                    <div class="d-flex align-items-center mb-2">
                                                        <i class="fas fa-<?php echo $transaction['transaction_type'] === 'CREDIT' ? 'arrow-down text-success' : 'arrow-up text-danger'; ?> fa-lg me-3"></i>
                                                        <div>
                                                            <h6 class="mb-1">
                                                                <?php echo ucfirst(str_replace('_', ' ', strtolower($transaction['category'] ?? 'Transaction'))); ?>
                                                            </h6>
                                                            <p class="text-muted mb-0">
                                                                <?php echo htmlspecialchars($transaction['description'] ?? 'No description'); ?>
                                                            </p>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="d-flex align-items-center">
                                                        <small class="text-muted me-3">
                                                            <i class="fas fa-calendar me-1"></i>
                                                            <?php echo date('M j, Y g:i A', strtotime($transaction['created_at'])); ?>
                                                        </small>
                                                        
                                                        <?php if (!empty($transaction['reference_type'])): ?>
                                                        <small class="text-muted me-3">
                                                            <i class="fas fa-link me-1"></i>
                                                            <?php echo ucfirst($transaction['reference_type']); ?> #<?php echo $transaction['reference_id']; ?>
                                                        </small>
                                                        <?php endif; ?>
                                                        
                                                        <span class="badge bg-<?php echo $transaction['status'] === 'COMPLETED' ? 'success' : ($transaction['status'] === 'PENDING' ? 'warning' : 'danger'); ?>">
                                                            <?php echo ucfirst(strtolower($transaction['status'])); ?>
                                                        </span>
                                                    </div>
                                                </div>
                                                
                                                <div class="text-end">
                                                    <h5 class="mb-1 amount-<?php echo strtolower($transaction['transaction_type']); ?>">
                                                        <?php echo $transaction['transaction_type'] === 'CREDIT' ? '+' : '-'; ?>
                                                        <?php echo $transaction['currency']; ?> <?php echo number_format($transaction['amount'], 2); ?>
                                                    </h5>
                                                    <small class="text-muted">
                                                        ID: <?php echo $transaction['transaction_id']; ?>
                                                    </small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Top-ups Sidebar -->
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="header-title">
                                    <i class="fas fa-plus-circle me-2"></i>
                                    Recent Top-ups
                                </h4>
                            </div>
                            <div class="card-body">
                                <?php if (empty($recent_topups)): ?>
                                <div class="text-center py-3">
                                    <i class="fas fa-plus-circle fa-2x mb-2 text-muted"></i>
                                    <p class="text-muted">No recent top-ups</p>
                                    <a href="topup-wallet.php" class="btn btn-sm btn-primary">
                                        Add Funds Now
                                    </a>
                                </div>
                                <?php else: ?>
                                    <?php foreach ($recent_topups as $topup): ?>
                                    <div class="d-flex justify-content-between align-items-center mb-3 pb-3 border-bottom">
                                        <div>
                                            <h6 class="mb-1">
                                                +<?php echo htmlspecialchars($topup['currency']); ?> <?php echo number_format($topup['amount'], 2); ?>
                                            </h6>
                                            <small class="text-muted d-block">
                                                <?php echo ucfirst(str_replace('_', ' ', strtolower($topup['payment_method']))); ?>
                                            </small>
                                            <small class="text-muted">
                                                <?php echo date('M j, Y', strtotime($topup['created_at'])); ?>
                                            </small>
                                        </div>
                                        <span class="badge bg-<?php echo $topup['status'] === 'COMPLETED' ? 'success' : ($topup['status'] === 'PENDING' ? 'warning' : 'danger'); ?>">
                                            <?php echo ucfirst(strtolower($topup['status'])); ?>
                                        </span>
                                    </div>
                                    <?php endforeach; ?>
                                    
                                    <div class="text-center">
                                        <a href="topup-wallet.php" class="btn btn-sm btn-primary">
                                            <i class="fas fa-plus me-1"></i>
                                            Add More Funds
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <?php 
        if (file_exists('partials/footer.php')) {
            try {
                include_once 'partials/footer.php';
            } catch (Exception $e) {
                echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
            }
        } else {
            echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
        }
        ?>
    </div>
</div>

<?php 
if (file_exists('partials/footer-scripts.php')) {
    try {
        include_once 'partials/footer-scripts.php';
    } catch (Exception $e) {
        echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
    }
} else {
    echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
}
?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Any wallet-specific JavaScript functionality can go here
    console.log('Wallet overview page loaded successfully');
});
</script>

</body>
</html>