<?php
session_start();

if (!isset($_SESSION['username'])) {
    $_SESSION['username'] = "Guest"; 
}

include 'includes/header.php'; 
include 'includes/user-sidebar.php'; 

error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_SESSION['user_id'])) {
    echo "User not logged in!";
    exit;
}

require 'config.php';

$user_id = $_SESSION['user_id']; 
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Fetch user data
$query = "SELECT username, balance FROM users WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

$username = isset($user['username']) ? htmlspecialchars($user['username']) : 'Guest';


// Get total deposit amount and transaction count
$query = "SELECT COUNT(*) AS total, SUM(amount) AS total_deposit FROM tbl_deposits WHERE user_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$total_deposit_transactions = $result['total'];
$total_deposit = $result['total_deposit'] ? $result['total_deposit'] : 0;

// Get total withdrawal amount and transaction count
$query = "SELECT COUNT(*) AS total, SUM(amount) AS total_withdrawal FROM tbl_withdrawals WHERE user_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$total_withdrawal_transactions = $result['total'];
$total_withdrawal = $result['total_withdrawal'] ? $result['total_withdrawal'] : 0;

// Get total amount transferred (sent)
$query = "SELECT COUNT(*) AS total, SUM(amount) AS total_transfer_amount FROM tbl_transfers WHERE sender_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$transfer_result = $stmt->get_result()->fetch_assoc();
$total_transfer_transactions = $transfer_result['total'];
$total_transfer_amount = $transfer_result['total_transfer_amount'] ?? 0;

// Get total amount received
$query = "SELECT COUNT(*) AS total_received, SUM(amount) AS total_received_amount FROM tbl_transfers WHERE recipient_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$received_result = $stmt->get_result()->fetch_assoc();
$total_received_transactions = $received_result['total_received'];
$total_received_amount = $received_result['total_received_amount'] ?? 0;

// Calculate updated balance
$updated_balance = $total_deposit - $total_withdrawal - $total_transfer_amount + $total_received_amount;

// Total transactions
$total_transactions = $total_deposit_transactions + $total_withdrawal_transactions + $total_transfer_transactions + $total_received_transactions;

// Pagination logic
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Count total transactions
$countQuery = "
    SELECT COUNT(*) AS total FROM (
        SELECT created_at FROM tbl_deposits WHERE user_id = ?
        UNION ALL
        SELECT created_at FROM tbl_withdrawals WHERE user_id = ?
        UNION ALL
        SELECT created_at FROM tbl_transfers WHERE sender_id = ?
        UNION ALL
        SELECT created_at FROM tbl_transfers WHERE recipient_id = ?
    ) AS combined";
$stmt = $conn->prepare($countQuery);
$stmt->bind_param("iiii", $user_id, $user_id, $user_id, $user_id);
$stmt->execute();
$totalResult = $stmt->get_result()->fetch_assoc();
$totalRows = $totalResult['total'];
$totalPages = ceil($totalRows / $limit);

// Fetch combined transaction history
$query = "
    SELECT 'Deposit' AS type, amount, status, created_at 
    FROM tbl_deposits 
    WHERE user_id = ? 
    UNION ALL 
    SELECT 'Withdrawal' AS type, amount, status, created_at 
    FROM tbl_withdrawals 
    WHERE user_id = ? 
    UNION ALL
    SELECT 'Transfer' AS type, amount, 'sent' AS status, created_at 
    FROM tbl_transfers 
    WHERE sender_id = ? 
    UNION ALL
    SELECT 'Transfer' AS type, amount, 'received' AS status, created_at 
    FROM tbl_transfers 
    WHERE recipient_id = ? 
    ORDER BY created_at DESC 
    LIMIT ? OFFSET ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("iiiiii", $user_id, $user_id, $user_id, $user_id, $limit, $offset);
$stmt->execute();
$transactions = $stmt->get_result();

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="stylesheet" href="includes/css/style.css">
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-10 content">       
            <div class="row">
                <div class="col-md-4">
                    <div class="card deposit p-3">
                        <h5>Deposits</h5>
                        <h3>GHS <?php echo number_format($total_deposit, 2); ?></h3>
                        <p style="font-size: 14px; color: #555;"><?php echo $total_deposit_transactions; ?> Transactions</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card withdraw p-3">
                        <h5>Withdrawals</h5>
                        <h3>GHS <?php echo number_format($total_withdrawal, 2); ?></h3>
                        <p style="font-size: 14px; color: #555;"><?php echo $total_withdrawal_transactions; ?> Transactions</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card balance p-3">
                        <h5>Total Balance</h5>
                        <h3>GHS <?php echo number_format($updated_balance, 2); ?></h3>
                    </div>
                </div>
            </div>

            <!-- Deposit & Withdraw Buttons -->
            <div class="row mt-4">
                <div class="col-md-6 text-center">
                    <h4>Deposit Money</h4>
                    <a href="deposit.php" class="btn btn-success mt-2 w-100">Deposit</a>
                </div>
                <div class="col-md-6 text-center">
                    <h4>Withdraw Money</h4>
                    <a href="withdraw.php" class="btn btn-danger mt-2 w-100">Withdraw</a>
                </div>
            </div>

            <!-- Transaction History Table -->
            <h4 class="mt-4">Transaction History</h4>
            <div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row = $transactions->fetch_assoc()): ?>
                            <tr>
                                <td><?php echo $row['created_at']; ?></td>
                                <td>
                                    <span class="btn 
                                        <?php 
                                            echo ($row['type'] == 'Deposit') ? 'btn-success' : 
                                                 (($row['type'] == 'Withdrawal') ? 'btn-danger' : 'btn-warning'); 
                                        ?> btn-sm">
                                        <?php echo $row['type']; ?>
                                    </span>
                                </td>
                                <td>GHS <?php echo number_format($row['amount'], 2); ?></td>
                                <td><?php echo ucfirst($row['status']); ?></td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <nav class="d-flex justify-content-center">
    <ul class="pagination">
        <?php if ($page > 1): ?>
            <li class="page-item"><a class="page-link" href="?page=<?php echo $page - 1; ?>">Previous</a></li>
        <?php endif; ?>
        <?php for ($i = 1; $i <= ceil($total_transactions / $limit); $i++): ?>
            <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
            </li>
        <?php endfor; ?>
        <?php if ($page < ceil($total_transactions / $limit)): ?>
            <li class="page-item"><a class="page-link" href="?page=<?php echo $page + 1; ?>">Next</a></li>
        <?php endif; ?>
    </ul>
</nav>
        </div>
    </div>
</div>
</body>
</html>
