<?php
session_start();

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

require_once 'admin/config/database.php';

// Format currency display - currency field now contains the actual symbol
function formatCurrency($amount, $currencySymbol) {
    return $currencySymbol . number_format($amount, 2);
}

$database = new Database();
$conn = $database->getConnection();

// Get user data
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Check if user exists, if not redirect to login
if (!$user) {
    session_destroy();
    header('Location: login.php');
    exit();
}

// Get filter parameters
$status_filter = $_GET['status'] ?? '';
$type_filter = $_GET['type'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$where_conditions = ["user_id = ?"];
$params = [$user_id];

if ($status_filter) {
    $where_conditions[] = "status = ?";
    $params[] = $status_filter;
}

if ($type_filter) {
    $where_conditions[] = "transaction_type = ?";
    $params[] = $type_filter;
}

if ($search) {
    $where_conditions[] = "(description LIKE ? OR reference_number LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = implode(' AND ', $where_conditions);

// Get transactions
$query = "SELECT * FROM transactions WHERE $where_clause ORDER BY created_at DESC LIMIT 50";
$stmt = $conn->prepare($query);
$stmt->execute($params);
$transactions = $stmt->fetchAll();

// Get general settings for site name
$siteName = 'TrustBNK';
try {
    $stmt = $conn->prepare("SELECT site_name FROM general_settings WHERE id = 1");
    $stmt->execute();
    $settings = $stmt->fetch();
    
    if ($settings && $settings['site_name']) {
        $siteName = $settings['site_name'];
    }
} catch (Exception $e) {
    // Use default site name if database query fails
    $siteName = 'TrustBNK';
}

$database->closeConnection();

// Get current date and time
$current_date = date('l, F j, Y');
$current_time = date('H:i:s');
$greeting = 'Good Morning';
$hour = (int)date('H');
if ($hour >= 12 && $hour < 17) {
    $greeting = 'Good Afternoon';
} elseif ($hour >= 17) {
    $greeting = 'Good Evening';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Transactions - <?php echo htmlspecialchars($siteName); ?> Credit</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .transactions-container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .page-header {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
        }

        .page-header .header-content h1 {
            color: #2c3e50;
            margin: 0 0 10px 0;
            font-size: 2rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .page-header .header-content h1 i {
            color: #667eea;
        }

        .page-header .header-content p {
            color: #5a6c7d;
            margin: 0;
            font-size: 1.1rem;
        }

        .filters-section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
            margin-bottom: 30px;
        }

        .filters-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            align-items: end;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
        }

        .filter-group label {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            font-size: 0.95rem;
        }

        .filter-group select,
        .filter-group input {
            padding: 12px 15px;
            border: 2px solid #e0e6ed;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
            background: white;
        }

        .filter-group select:focus,
        .filter-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .filter-actions {
            display: flex;
            gap: 10px;
        }

        .btn-filter {
            background: #667eea;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .btn-filter:hover {
            background: #5a6fd8;
        }

        .btn-clear {
            background: #6c757d;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .btn-clear:hover {
            background: #5a6268;
        }

        .transactions-section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
        }

        .transactions-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f8f9fa;
        }

        .transactions-header h2 {
            color: #2c3e50;
            margin: 0;
            font-size: 1.5rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .transactions-header h2 i {
            color: #667eea;
        }

        .results-count {
            color: #6c757d;
            font-size: 0.95rem;
            font-weight: 500;
        }

        .transactions-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.95rem;
        }

        .transactions-table th {
            background: #f8f9fa;
            color: #2c3e50;
            font-weight: 600;
            padding: 15px 12px;
            text-align: left;
            border-bottom: 2px solid #e0e6ed;
        }

        .transactions-table td {
            padding: 15px 12px;
            border-bottom: 1px solid #f0f0f0;
            vertical-align: middle;
        }

        .transactions-table tbody tr:hover {
            background: #f8f9fa;
        }

        .transaction-date {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .transaction-date .date {
            font-weight: 600;
            color: #2c3e50;
        }

        .transaction-date .time {
            font-size: 0.85rem;
            color: #6c757d;
        }

        .transaction-type {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.85rem;
        }

        .transaction-type.credit {
            background: #d4edda;
            color: #155724;
        }

        .transaction-type.debit {
            background: #f8d7da;
            color: #721c24;
        }

        .transaction-description {
            font-weight: 500;
            color: #2c3e50;
        }

        .reference-number {
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            color: #6c757d;
            background: #f8f9fa;
            padding: 4px 8px;
            border-radius: 4px;
        }

        .amount {
            font-weight: 700;
            font-size: 1.1rem;
        }

        .amount.positive {
            color: #28a745;
        }

        .amount.negative {
            color: #dc3545;
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.85rem;
            text-align: center;
        }

        .status-completed {
            background: #d4edda;
            color: #155724;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }

        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            color: #dee2e6;
        }

        .empty-state h3 {
            font-size: 1.3rem;
            margin-bottom: 10px;
            color: #2c3e50;
        }

        .empty-state p {
            font-size: 1rem;
            margin: 0;
        }

        /* Mobile responsive */
        @media (max-width: 768px) {
            .filters-row {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            
            .filter-actions {
                flex-direction: column;
            }
            
            .transactions-table {
                font-size: 0.85rem;
            }
            
            .transactions-table th,
            .transactions-table td {
                padding: 10px 8px;
            }
            
            .transaction-type {
                font-size: 0.75rem;
                padding: 4px 8px;
            }
            
            .status-badge {
                font-size: 0.75rem;
                padding: 4px 8px;
            }
        }
    </style>
</head>
<body class="dashboard-page">
    <!-- Top Header Bar -->
    <div class="dashboard-header">
        <div class="header-left">
            <div class="current-balance">
                <span class="balance-label">Current Balance</span>
                <span class="balance-amount"><?php echo formatCurrency($user['balance'], $_SESSION['currency'] ?? '$'); ?></span>
            </div>
        </div>
        <div class="header-center">
            <div class="current-date"><?php echo $current_date; ?></div>
        </div>
        <div class="header-right">
            <div class="header-actions">
                <button class="notification-btn">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge">3</span>
                </button>
                <div class="user-profile">
                    <div class="user-avatar">
                        <?php if ($user['profile_photo']): ?>
                            <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                        <?php else: ?>
                            <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="user-info">
                        <span class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></span>
                        <span class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></span>
                        <span class="kyc-badge">KYC Verified</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="dashboard-container">
        <!-- Mobile Menu Toggle -->
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="fas fa-bars"></i>
        </button>
        
        <!-- Sidebar Overlay -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        
        <!-- Sidebar -->
        <aside class="dashboard-sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <div class="logo-emblem">
                        <span class="logo-t">T</span>
                        <span class="logo-b">B</span>
                    </div>
                    <div class="logo-text">
                        <div class="logo-main"><?php echo htmlspecialchars($siteName); ?></div>
                        <div class="logo-sub">Credit</div>
                    </div>
                </div>
            </div>
            
            <div class="user-profile-sidebar">
                <div class="user-avatar-sidebar">
                    <?php if ($user['profile_photo']): ?>
                        <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                    <?php else: ?>
                        <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                    <?php endif; ?>
                </div>
                <div class="user-details">
                    <div class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></div>
                    <div class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></div>
                    <span class="kyc-badge">KYC Verified</span>
                </div>
                <div class="profile-actions">
                    <a href="profile.php" class="btn-profile">
                        <i class="fas fa-user"></i> Profile
                    </a>
                    <a href="logout.php" class="btn-logout">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
            
            <nav class="sidebar-nav">
                <div class="nav-section">
                    <h3>Main Menu</h3>
                    <ul>
                        <li><a href="dashboard.php"><i class="fas fa-home"></i> Dashboard</a></li>
                        <li><a href="transactions.php" class="active"><i class="fas fa-exchange-alt"></i> Transactions</a></li>
                        <li><a href="transfer.php"><i class="fas fa-paper-plane"></i> Transfer Funds</a></li>
                        <li><a href="cards.php"><i class="fas fa-credit-card"></i> Cards</a></li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>Services</h3>
                    <ul>
                        <li><a href="loan-request.php"><i class="fas fa-hand-holding-usd"></i> Loan Request</a></li>
                        <li><a href="loan-history.php"><i class="fas fa-history"></i> Loan History</a></li>
                        <li><a href="irs-refund.php"><i class="fas fa-file-invoice-dollar"></i> IRS Refund</a></li>
                        <li><a href="apply-card.php"><i class="fas fa-id-card"></i> Apply for Card</a></li>
                    </ul>
                </div>
            </nav>
            
            <div class="sidebar-footer">
                <div class="support-info">
                    <h4>Need Help?</h4>
                    <p>Contact our 24/7 support team</p>
                    <a href="mailto:support@trustbeamcredit.com" class="support-link">
                        <i class="fas fa-envelope"></i> support@trustbeamcredit.com
                    </a>
                </div>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="dashboard-main">
            <div class="transactions-container">
                <!-- Page Header -->
                <div class="page-header">
                    <div class="header-content">
                        <h1><i class="fas fa-exchange-alt"></i> My Transactions</h1>
                        <p>View and manage all your transaction history</p>
                    </div>
                </div>

                <!-- Filters Section -->
                <div class="filters-section">
                    <form method="GET" class="filters-form">
                        <div class="filters-row">
                            <div class="filter-group">
                                <label for="status">Status</label>
                                <select name="status" id="status">
                                    <option value="">All Statuses</option>
                                    <option value="Completed" <?php echo $status_filter === 'Completed' ? 'selected' : ''; ?>>Completed</option>
                                    <option value="Pending" <?php echo $status_filter === 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="Failed" <?php echo $status_filter === 'Failed' ? 'selected' : ''; ?>>Failed</option>
                                </select>
                            </div>
                            
                            <div class="filter-group">
                                <label for="type">Type</label>
                                <select name="type" id="type">
                                    <option value="">All Types</option>
                                    <option value="Credit" <?php echo $type_filter === 'Credit' ? 'selected' : ''; ?>>Credit</option>
                                    <option value="Debit" <?php echo $type_filter === 'Debit' ? 'selected' : ''; ?>>Debit</option>
                                    <option value="Transfer" <?php echo $type_filter === 'Transfer' ? 'selected' : ''; ?>>Transfer</option>
                                </select>
                            </div>
                            
                            <div class="filter-group">
                                <label for="search">Search</label>
                                <input type="text" name="search" id="search" placeholder="Search transactions..." value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                            
                            <div class="filter-actions">
                                <button type="submit" class="btn-filter">
                                    <i class="fas fa-search"></i> Filter
                                </button>
                                <a href="transactions.php" class="btn-clear">
                                    <i class="fas fa-times"></i> Clear
                                </a>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- Transactions Section -->
                <div class="transactions-section">
                    <div class="transactions-header">
                        <h2><i class="fas fa-list"></i> Transaction History</h2>
                        <div class="results-count">Showing <?php echo count($transactions); ?> transactions</div>
                    </div>

                    <?php if (empty($transactions)): ?>
                        <div class="empty-state">
                            <i class="fas fa-inbox"></i>
                            <h3>No Transactions Found</h3>
                            <p>No transactions match your current filters. Try adjusting your search criteria.</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="transactions-table">
                                <thead>
                                    <tr>
                                        <th>Date & Time</th>
                                        <th>Type</th>
                                        <th>Description</th>
                                        <th>Reference</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($transactions as $transaction): ?>
                                        <tr>
                                            <td>
                                                <div class="transaction-date">
                                                    <span class="date"><?php echo date('M d, Y', strtotime($transaction['created_at'])); ?></span>
                                                    <span class="time"><?php echo date('h:i A', strtotime($transaction['created_at'])); ?></span>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="transaction-type <?php echo strtolower($transaction['transaction_type']); ?>">
                                                    <i class="fas fa-<?php echo $transaction['transaction_type'] === 'Credit' ? 'arrow-down' : 'arrow-up'; ?>"></i>
                                                    <?php echo htmlspecialchars($transaction['transaction_type']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <div class="transaction-description">
                                                    <?php echo htmlspecialchars($transaction['description']); ?>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="reference-number"><?php echo htmlspecialchars($transaction['reference_number']); ?></span>
                                            </td>
                                            <td>
                                                <span class="amount <?php echo $transaction['transaction_type'] === 'Credit' ? 'positive' : 'negative'; ?>">
                                                    <?php echo $transaction['transaction_type'] === 'Credit' ? '+' : '-'; ?>
                                                    <?php echo formatCurrency($transaction['amount'], $_SESSION['currency'] ?? '$'); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="status-badge status-<?php echo strtolower($transaction['status']); ?>">
                                                    <?php echo htmlspecialchars($transaction['status']); ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Mobile menu toggle
        document.addEventListener('DOMContentLoaded', function() {
            const mobileMenuToggle = document.getElementById('mobileMenuToggle');
            const sidebar = document.querySelector('.dashboard-sidebar');
            const overlay = document.getElementById('sidebarOverlay');

            mobileMenuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('active');
                overlay.classList.toggle('active');
            });

            overlay.addEventListener('click', function() {
                sidebar.classList.remove('active');
                overlay.classList.remove('active');
            });
        });
    </script>
    <script src="assets/js/logout-confirmation.js"></script>
</body>
</html>