<?php
// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/otp.php';
require_once '../includes/session_manager.php';

redirectIfNotLoggedIn();

$userId = $_SESSION['user_id'];
$error = '';
$success = '';
$balance = 0;

// Get sender's account
$stmt = $pdo->prepare("SELECT * FROM accounts WHERE user_id = ?");
$stmt->execute([$userId]);
$fromAccount = $stmt->fetch();

if (!$fromAccount) {
    $error = "Your account could not be found.";
} else {
    $accountId = $fromAccount['account_id'];
    $accountNumber = $fromAccount['account_number'];

    // Get latest balance
    $stmt = $pdo->prepare("SELECT balance FROM accounts WHERE account_id = ?");
    $stmt->execute([$accountId]);
    $balance = $stmt->fetchColumn();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $toAccount = trim($_POST['to_account'] ?? '');
    $amount = floatval($_POST['amount'] ?? 0);
    $description = trim($_POST['description'] ?? '');

    if ($amount <= 0) {
        $error = "Please enter a valid amount.";
    } elseif ($amount > $balance) {
        $error = "Insufficient balance for this transfer.";
    } elseif ($toAccount === $accountNumber) {
        $error = "You cannot transfer to your own account.";
    } else {
        // Check if recipient exists
        $stmt = $pdo->prepare("SELECT account_id FROM accounts WHERE account_number = ?");
        $stmt->execute([$toAccount]);
        $recipientAccount = $stmt->fetch();

        if (!$recipientAccount) {
            $error = "Recipient account not found.";
        } else {
            // Get user's email
            $stmt = $pdo->prepare("SELECT email FROM users WHERE user_id = ?");
            $stmt->execute([$userId]);
            $user = $stmt->fetch();
            $email = $user['email'] ?? '';

            if ($email && generateOTP($email)) {
                // Store the pending transfer in session for OTP verification
                $_SESSION['pending_transfer'] = [
                    'amount' => $amount,
                    'to_account' => $toAccount,
                    'description' => $description
                ];

                header("Location: ../otp-verification.php?type=transfer");
                exit();
            } else {
                $error = "Failed to send OTP. Please try again.";
            }
        }
    }
}

// Get user account information
$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("
    SELECT u.*, a.account_number, a.balance 
    FROM users u 
    JOIN accounts a ON u.user_id = a.user_id 
    WHERE u.user_id = ?
");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    die('User account not found.');
}

// Check if the user has a profile picture
$stmt = $pdo->prepare("SELECT profile_picture FROM users WHERE user_id = ?");
$profilePic = $user['profile_picture'] ? '../uploads/' . $user['profile_picture'] : '../assets/images/default-avatars.png';

// Get transactions for the user's transfer history
$typeFilter = $_GET['type'] ?? '';

// Get total number of transactions for pagination
$countSql = "
    SELECT COUNT(*) FROM transactions 
    WHERE account_id = (SELECT account_id FROM accounts WHERE user_id = ?)
      AND type IN ('transfer_in', 'transfer_out')
";

$countParams = [$userId];

if ($typeFilter === 'transfer_in' || $typeFilter === 'transfer_out') {
    $countSql .= " AND type = ?";
    $countParams[] = $typeFilter;
}

$stmt = $pdo->prepare($countSql);
$stmt->execute($countParams);
$totalTransactions = $stmt->fetchColumn();

// Calculate pagination
$transactionsPerPage = 10;
$totalPages = ceil($totalTransactions / $transactionsPerPage);
$currentPage = isset($_GET['page']) ? max(1, min($totalPages, intval($_GET['page']))) : 1;
$offset = ($currentPage - 1) * $transactionsPerPage;

$sql = "
    SELECT t.*, 
           CASE 
               WHEN t.type = 'transfer_in' THEN 'Incoming'
               WHEN t.type = 'transfer_out' THEN 'Outgoing'
               ELSE t.type
           END as display_type,
           CASE 
               WHEN t.type = 'transfer_in' THEN 'positive'
               WHEN t.type = 'transfer_out' THEN 'negative'
               ELSE ''
           END as amount_class
    FROM transactions t
    WHERE t.account_id = (SELECT account_id FROM accounts WHERE user_id = ?)
      AND t.type IN ('transfer_in', 'transfer_out')
";

$params = [$userId];

if ($typeFilter === 'transfer_in' || $typeFilter === 'transfer_out') {
    $sql .= " AND t.type = ?";
    $params[] = $typeFilter;
}

$sql .= " ORDER BY t.created_at DESC LIMIT ? OFFSET ?";
$params[] = $transactionsPerPage;
$params[] = $offset;

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$transactions = $stmt->fetchAll();

$type = $_GET['type'] ?? 'transfer_in'; // Default to transfer_in if not set

// Monthly total
$stmt = $pdo->prepare("
    SELECT SUM(amount) FROM transactions 
    WHERE account_id = ? 
      AND type = ? 
      AND MONTH(created_at) = MONTH(CURRENT_DATE()) 
      AND YEAR(created_at) = YEAR(CURRENT_DATE())
");
$stmt->execute([$accountId, $type]);
$monthlyTotal = $stmt->fetchColumn() ?: 0;

// Largest transfer
$stmt = $pdo->prepare("
    SELECT MAX(amount) FROM transactions 
    WHERE account_id = ? AND type = ?
");
$stmt->execute([$accountId, $type]);
$largestTransfer = $stmt->fetchColumn() ?: 0;

// Average weekly transfer (last 4 weeks)
$stmt = $pdo->prepare("
    SELECT SUM(amount) / 4 FROM transactions 
    WHERE account_id = ? 
      AND type = ? 
      AND created_at >= NOW() - INTERVAL 28 DAY
");
$stmt->execute([$accountId, $type]);
$averageWeeklyTransfer = $stmt->fetchColumn() ?: 0;

// This week's transfer total (7 days)
$stmt = $pdo->prepare("
    SELECT SUM(amount) FROM transactions 
    WHERE account_id = ? 
      AND type = ? 
      AND created_at >= NOW() - INTERVAL 7 DAY
");
$stmt->execute([$accountId, $type]);
$weeklyTransfers = $stmt->fetchColumn() ?: 0;

$typeLabel = $type === 'transfer_out' ? 'Transfer Out' : 'Transfer In';
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Oakshire Finance - Transfer Funds</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --accent-blue: #2c7da0;
            --success-green: #2e7d32;
            --warning-orange: #f39c12;
            --error-red: #dc3545;
            --info-blue: #17a2b8;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 12px 28px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: var(--gray-50);
            color: var(--gray-800);
            line-height: 1.5;
            overflow-x: hidden;
        }

        /* Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 280px;
            background: var(--white);
            border-right: 1px solid var(--gray-200);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 20px;
            color: white;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
            letter-spacing: -0.3px;
        }

        .profile-section {
            padding: 24px;
            text-align: center;
            border-bottom: 1px solid var(--gray-200);
        }

        .profile-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto 12px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .profile-avatar i {
            font-size: 40px;
            color: white;
        }

        .profile-section h5 {
            font-size: 16px;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 4px;
        }

        .profile-section p {
            font-size: 12px;
            color: var(--gray-500);
        }

        .nav-menu {
            padding: 16px;
        }

        .nav-item {
            margin-bottom: 4px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .nav-link.active i {
            color: white;
        }

        .logout-section {
            padding: 16px;
            border-top: 1px solid var(--gray-200);
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            transition: var(--transition);
            font-weight: 500;
        }

        .logout-btn:hover {
            background: rgba(220, 53, 69, 0.1);
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        /* Top Header */
        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-900);
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .notification-btn {
            position: relative;
            background: none;
            border: none;
            font-size: 20px;
            color: var(--gray-600);
            cursor: pointer;
            transition: var(--transition);
        }

        .notification-btn:hover {
            color: var(--primary-blue);
        }

        /* Content Area */
        .content-area {
            padding: 32px;
        }

        /* Balance Card */
        .balance-card {
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-dark));
            border-radius: 20px;
            padding: 24px;
            margin-bottom: 32px;
            color: white;
        }

        .balance-card h3 {
            font-size: 14px;
            font-weight: 500;
            opacity: 0.8;
            margin-bottom: 8px;
        }

        .balance-amount {
            font-size: 36px;
            font-weight: 700;
        }

        /* Transfer Card */
        .transfer-card {
            background: var(--white);
            border-radius: 24px;
            border: 1px solid var(--gray-200);
            padding: 32px;
            margin-bottom: 32px;
        }

        /* Form */
        .form-group {
            margin-bottom: 24px;
        }

        .form-group label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: var(--gray-700);
            margin-bottom: 8px;
        }

        .form-group input {
            width: 100%;
            padding: 14px 16px;
            font-size: 16px;
            font-family: 'Inter', sans-serif;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            transition: var(--transition);
            outline: none;
        }

        .form-group input:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .btn-primary {
            width: 100%;
            padding: 14px;
            background: var(--primary-navy);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
        }

        /* Summary Cards */
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 32px;
        }

        .summary-card {
            background: var(--white);
            border-radius: 16px;
            padding: 20px;
            border: 1px solid var(--gray-200);
        }

        .summary-card h4 {
            font-size: 12px;
            font-weight: 500;
            color: var(--gray-600);
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .summary-value {
            font-size: 20px;
            font-weight: 700;
            color: var(--gray-900);
        }

        /* Chart Grid */
        .charts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 24px;
            margin-bottom: 32px;
        }

        .chart-card {
            background: var(--white);
            border-radius: 20px;
            padding: 24px;
            border: 1px solid var(--gray-200);
        }

        .chart-card h3 {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        /* Table */
        .table-container {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 500px;
        }

        .data-table th,
        .data-table td {
            padding: 16px 20px;
            text-align: left;
            border-bottom: 1px solid var(--gray-200);
        }

        .data-table th {
            background: var(--gray-50);
            font-weight: 600;
            font-size: 12px;
            color: var(--gray-700);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .data-table td {
            font-size: 13px;
        }

        .badge-positive {
            color: var(--success-green);
            font-weight: 600;
        }

        .badge-negative {
            color: var(--error-red);
            font-weight: 600;
        }

        .btn-download {
            background: none;
            border: none;
            color: var(--primary-blue);
            cursor: pointer;
            font-size: 12px;
        }

        .btn-download:hover {
            text-decoration: underline;
        }

        /* Filter Bar */
        .filter-bar {
            background: var(--white);
            border-radius: 20px;
            padding: 16px 24px;
            margin-bottom: 24px;
            border: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }

        .filter-select {
            padding: 10px 14px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            border: 1.5px solid var(--gray-200);
            border-radius: 10px;
            transition: var(--transition);
            outline: none;
        }

        .filter-select:focus {
            border-color: var(--primary-blue);
        }

        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            gap: 8px;
            padding: 20px;
            flex-wrap: wrap;
        }

        .pagination a {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 36px;
            height: 36px;
            padding: 0 12px;
            border-radius: 8px;
            background: var(--white);
            border: 1px solid var(--gray-200);
            color: var(--gray-700);
            text-decoration: none;
            font-size: 14px;
            transition: var(--transition);
        }

        .pagination a:hover {
            background: var(--gray-100);
        }

        .pagination a.active {
            background: var(--primary-navy);
            border-color: var(--primary-navy);
            color: white;
        }

        /* Alerts */
        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        /* Hamburger Menu */
        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--gray-700);
        }

        /* Mobile Responsive */
        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .balance-amount {
                font-size: 28px;
            }

            .transfer-card {
                padding: 20px;
            }

            .summary-grid {
                grid-template-columns: 1fr 1fr;
                gap: 12px;
            }

            .summary-value {
                font-size: 16px;
            }

            .charts-grid {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .filter-bar {
                flex-direction: column;
                align-items: stretch;
            }

            .data-table th,
            .data-table td {
                padding: 12px 16px;
            }
        }

        @media (max-width: 480px) {
            .summary-grid {
                grid-template-columns: 1fr;
            }

            .balance-amount {
                font-size: 24px;
            }

            .pagination a {
                min-width: 32px;
                height: 32px;
                font-size: 12px;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <!-- Sidebar Navigation -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon">
                        <i class="fas fa-building-columns"></i>
                    </div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>

            <div class="profile-section">
                <div class="profile-avatar">
                    <?php if ($user['profile_picture']): ?>
                        <img src="<?= $profilePic ?>" alt="Profile Picture">
                    <?php else: ?>
                        <i class="fas fa-user-circle"></i>
                    <?php endif; ?>
                </div>
                <h5><?= htmlspecialchars($user['full_name']) ?></h5>
                <p><?= htmlspecialchars($user['account_number']) ?></p>
            </div>

            <nav class="nav-menu">
                <div class="nav-item">
                    <a href="dashboard.php" class="nav-link">
                        <i class="fas fa-chart-line"></i>
                        <span>Dashboard</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="deposit.php" class="nav-link">
                        <i class="fas fa-arrow-down"></i>
                        <span>Deposit</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="withdraw.php" class="nav-link">
                        <i class="fas fa-arrow-up"></i>
                        <span>Withdraw</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="transfer.php" class="nav-link active">
                        <i class="fas fa-exchange-alt"></i>
                        <span>Transfer</span>
                    </a>
                </div>
                <div class="nav-item"><a href="cards.php" class="nav-link "><i class="fas fa-credit-card"></i> My
                        Cards</a></div>
                <div class="nav-item">
                    <a href="transactions.php" class="nav-link">
                        <i class="fas fa-receipt"></i>
                        <span>Transactions</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="investment.php" class="nav-link">
                        <i class="fas fa-chart-pie"></i>
                        <span>Investment</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="loan.php" class="nav-link">
                        <i class="fas fa-hand-holding-usd"></i>
                        <span>Loans</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="profile.php" class="nav-link">
                        <i class="fas fa-user-circle"></i>
                        <span>Settings</span>
                    </a>
                </div>
            </nav>

            <div class="logout-section">
                <a href="../logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Header -->
            <header class="top-header">
                <button class="hamburger" id="hamburger">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="page-title">
                    <h1>Transfer Funds</h1>
                </div>
                <div class="user-menu">
                    <button class="notification-btn">
                        <i class="fas fa-bell"></i>
                    </button>
                </div>
            </header>

            <!-- Content Area -->
            <div class="content-area">
                <!-- Balance Card -->
                <div class="balance-card">
                    <h3>Available Balance</h3>
                    <div class="balance-amount">$<?= number_format($balance, 2) ?></div>
                </div>

                <!-- Transfer Form Card -->
                <div class="transfer-card">
                    <?php if ($error): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle"></i>
                            <span><?= htmlspecialchars($error) ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if ($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i>
                            <span><?= htmlspecialchars($success) ?></span>
                        </div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="form-group">
                            <label for="to_account">Recipient Account Number</label>
                            <input type="text" name="to_account" id="to_account"
                                placeholder="Enter recipient's account number" required>
                        </div>

                        <div class="form-group">
                            <label for="amount">Amount</label>
                            <input type="number" name="amount" id="amount" step="0.01" min="0.01"
                                placeholder="Enter amount" required>
                        </div>

                        <div class="form-group">
                            <label for="description">Description (Optional)</label>
                            <input type="text" name="description" id="description" placeholder="Add a note">
                        </div>

                        <button type="submit" class="btn-primary">
                            <i class="fas fa-exchange-alt"></i> Send OTP & Proceed
                        </button>
                    </form>
                </div>

                <!-- Summary Cards -->
                <div class="summary-grid">
                    <div class="summary-card">
                        <h4>Total <?= $typeLabel ?> (This Month)</h4>
                        <div class="summary-value">$<?= number_format($monthlyTotal, 2) ?></div>
                    </div>
                    <div class="summary-card">
                        <h4>Largest <?= $typeLabel ?></h4>
                        <div class="summary-value">$<?= number_format($largestTransfer, 2) ?></div>
                    </div>
                    <div class="summary-card">
                        <h4>Average Weekly <?= $typeLabel ?></h4>
                        <div class="summary-value">$<?= number_format($averageWeeklyTransfer, 2) ?></div>
                    </div>
                </div>

                <!-- Charts Grid -->
                <div class="charts-grid">
                    <div class="chart-card">
                        <h3><i class="fas fa-arrow-down"></i> Transfer In History</h3>
                        <div id="monthlyTransferIn" style="height: 350px;"></div>
                    </div>
                    <div class="chart-card">
                        <h3><i class="fas fa-arrow-up"></i> Transfer Out History</h3>
                        <div id="monthlyTransferOut" style="height: 350px;"></div>
                    </div>
                </div>

                <!-- Transfer History -->
                <div class="chart-card" style="padding: 0; overflow: hidden;">
                    <div
                        style="padding: 20px 24px; border-bottom: 1px solid var(--gray-200); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                        <h3><i class="fas fa-history"></i> Transfer History</h3>
                        <form method="GET" id="filterForm" style="margin: 0;">
                            <select name="type" id="typeFilter" class="filter-select"
                                onchange="document.getElementById('filterForm').submit()">
                                <option value="">All Transfers</option>
                                <option value="transfer_in" <?= ($_GET['type'] ?? '') === 'transfer_in' ? 'selected' : '' ?>>Transfer In</option>
                                <option value="transfer_out" <?= ($_GET['type'] ?? '') === 'transfer_out' ? 'selected' : '' ?>>Transfer Out</option>
                            </select>
                        </form>
                    </div>
                    <div class="table-container" style="margin: 0; border-radius: 0;">
                        <?php if (empty($transactions)): ?>
                            <div style="text-align: center; padding: 48px; color: var(--gray-500);">
                                <i class="fas fa-exchange-alt"
                                    style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;"></i>
                                <p>No transfer transactions found</p>
                            </div>
                        <?php else: ?>
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Transaction ID</th>
                                        <th>Type</th>
                                        <th>Amount</th>
                                        <th>Receipt</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($transactions as $txn): ?>
                                        <tr>
                                            <td><?= date('M d, Y h:i A', strtotime($txn['created_at'])) ?></td>
                                            <td><code>#<?= $txn['transaction_id'] ?></code></td>
                                            <td>
                                                <?php if ($txn['type'] === 'transfer_in'): ?>
                                                    <span class="badge-positive"><i class="fas fa-arrow-down"></i> Incoming</span>
                                                <?php else: ?>
                                                    <span class="badge-negative"><i class="fas fa-arrow-up"></i> Outgoing</span>
                                                <?php endif; ?>
                                            </td>
                                            <td
                                                class="<?= $txn['type'] === 'transfer_in' ? 'badge-positive' : 'badge-negative' ?>">
                                                <?= $txn['type'] === 'transfer_in' ? '+' : '-' ?>
                                                $<?= number_format($txn['amount'], 2) ?>
                                            </td>
                                            <td>
                                                <button
                                                    onclick="window.open('generate_receipt.php?transaction_id=<?= $txn['transaction_id'] ?>', '_blank')"
                                                    class="btn-download">
                                                    <i class="fas fa-download"></i> Receipt
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>

                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                        <div class="pagination">
                            <?php if ($currentPage > 1): ?>
                                <a
                                    href="?page=<?= $currentPage - 1 ?><?= $typeFilter ? '&type=' . urlencode($typeFilter) : '' ?>">&laquo;
                                    Prev</a>
                            <?php endif; ?>
                            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                <a href="?page=<?= $i ?><?= $typeFilter ? '&type=' . urlencode($typeFilter) : '' ?>"
                                    class="<?= $i == $currentPage ? 'active' : '' ?>"><?= $i ?></a>
                            <?php endfor; ?>
                            <?php if ($currentPage < $totalPages): ?>
                                <a
                                    href="?page=<?= $currentPage + 1 ?><?= $typeFilter ? '&type=' . urlencode($typeFilter) : '' ?>">Next
                                    &raquo;</a>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Mobile sidebar toggle
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');

        if (hamburger) {
            hamburger.addEventListener('click', function () {
                sidebar.classList.toggle('mobile-open');
            });
        }

        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function (event) {
            if (window.innerWidth <= 1024) {
                const isClickInside = sidebar.contains(event.target) || hamburger.contains(event.target);
                if (!isClickInside && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });

        // Monthly Transfer In Chart
        document.addEventListener("DOMContentLoaded", () => {
            fetch('get_monthly_transfer_in.php')
                .then(res => res.json())
                .then(data => {
                    const transferMap = data.reduce((acc, { month, total_deposit }) => {
                        acc[month] = parseFloat(total_deposit);
                        return acc;
                    }, {});

                    const year = new Date().getFullYear();
                    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                    const totals = monthNames.map((_, idx) => {
                        const key = `${year}-${String(idx + 1).padStart(2, '0')}`;
                        return transferMap[key] || 0;
                    });

                    const options = {
                        chart: { type: 'bar', height: 350, toolbar: { show: true, tools: { download: true } }, fontFamily: 'Inter, sans-serif' },
                        plotOptions: { bar: { borderRadius: 8, columnWidth: '50%' } },
                        dataLabels: { enabled: false },
                        colors: ['#2e7d32'],
                        series: [{ name: 'Transfer In', data: totals }],
                        xaxis: { categories: monthNames, labels: { rotate: -45, style: { fontSize: '11px' } } },
                        yaxis: { title: { text: 'Amount ($)' }, labels: { formatter: val => '$' + val.toLocaleString() } },
                        tooltip: { y: { formatter: val => '$' + val.toLocaleString() } },
                        responsive: [
                            { breakpoint: 768, options: { plotOptions: { bar: { columnWidth: '70%' } }, xaxis: { labels: { rotate: -60, style: { fontSize: '10px' } } } } },
                            { breakpoint: 480, options: { plotOptions: { bar: { columnWidth: '90%' } }, xaxis: { labels: { rotate: -90, style: { fontSize: '9px' } } } } }
                        ]
                    };
                    const chartEl = document.querySelector("#monthlyTransferIn");
                    if (chartEl) new ApexCharts(chartEl, options).render();
                })
                .catch(err => console.error('Error fetching transfer in data:', err));
        });

        // Monthly Transfer Out Chart
        document.addEventListener("DOMContentLoaded", () => {
            fetch('get_monthly_transfer_out.php')
                .then(res => res.json())
                .then(data => {
                    const transferMap = data.reduce((acc, { month, total_deposit }) => {
                        acc[month] = parseFloat(total_deposit);
                        return acc;
                    }, {});

                    const year = new Date().getFullYear();
                    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                    const totals = monthNames.map((_, idx) => {
                        const key = `${year}-${String(idx + 1).padStart(2, '0')}`;
                        return transferMap[key] || 0;
                    });

                    const options = {
                        chart: { type: 'bar', height: 350, toolbar: { show: true, tools: { download: true } }, fontFamily: 'Inter, sans-serif' },
                        plotOptions: { bar: { borderRadius: 8, columnWidth: '50%' } },
                        dataLabels: { enabled: false },
                        colors: ['#dc3545'],
                        series: [{ name: 'Transfer Out', data: totals }],
                        xaxis: { categories: monthNames, labels: { rotate: -45, style: { fontSize: '11px' } } },
                        yaxis: { title: { text: 'Amount ($)' }, labels: { formatter: val => '$' + val.toLocaleString() } },
                        tooltip: { y: { formatter: val => '$' + val.toLocaleString() } },
                        responsive: [
                            { breakpoint: 768, options: { plotOptions: { bar: { columnWidth: '70%' } }, xaxis: { labels: { rotate: -60, style: { fontSize: '10px' } } } } },
                            { breakpoint: 480, options: { plotOptions: { bar: { columnWidth: '90%' } }, xaxis: { labels: { rotate: -90, style: { fontSize: '9px' } } } } }
                        ]
                    };
                    const chartEl = document.querySelector("#monthlyTransferOut");
                    if (chartEl) new ApexCharts(chartEl, options).render();
                })
                .catch(err => console.error('Error fetching transfer out data:', err));
        });
    </script>
</body>

</html>