<?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();

if (!$user) {
    header('Location: login.php');
    exit();
}

// Get loan applications for the user
$stmt = $conn->prepare("SELECT * FROM loan_applications WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$loan_applications = $stmt->fetchAll();

// Calculate loan statistics
$stmt = $conn->prepare("SELECT COUNT(*) as total_loans FROM loan_applications WHERE user_id = ?");
$stmt->execute([$user_id]);
$total_loans = $stmt->fetch()['total_loans'];

$stmt = $conn->prepare("SELECT SUM(loan_amount) as total_borrowed FROM loan_applications WHERE user_id = ? AND status IN ('Approved', 'Active', 'Completed')");
$stmt->execute([$user_id]);
$total_borrowed = $stmt->fetch()['total_borrowed'] ?? 0;

$stmt = $conn->prepare("SELECT SUM(monthly_payment) as total_monthly_payments FROM loan_applications WHERE user_id = ? AND status IN ('Active', 'Completed')");
$stmt->execute([$user_id]);
$total_monthly_payments = $stmt->fetch()['total_monthly_payments'] ?? 0;

$stmt = $conn->prepare("SELECT COUNT(*) as active_loans FROM loan_applications WHERE user_id = ? AND status = 'Active'");
$stmt->execute([$user_id]);
$active_loans = $stmt->fetch()['active_loans'];

// 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>Loan History - <?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>
        .loan-history-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .loan-card {
            background: white;
            border-radius: 15px;
            padding: 0;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: 1px solid #e0e6ed;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            overflow: hidden;
        }

        .loan-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0,0,0,0.15);
        }

        .loan-card .card-header {
            padding: 20px 25px;
            margin: 0;
            border-bottom: 1px solid #f1f3f4;
        }

        .loan-card .card-header h3 {
            margin: 0 0 5px 0;
            font-size: 1.1rem;
            font-weight: 600;
            color: #2c3e50;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .loan-card .card-header h3 .loan-type {
            font-size: 0.9rem;
            font-weight: 500;
            color: #667eea;
        }

        .loan-card .card-header .loan-amount {
            font-size: 1.5rem;
            font-weight: 700;
            color: #2c3e50;
            margin: 5px 0;
        }

        .loan-card .card-header .loan-date {
            font-size: 0.85rem;
            color: #5a6c7d;
        }

        .loan-card .card-content {
            padding: 20px 25px;
        }

        .loan-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 15px;
        }

        .loan-detail {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .loan-detail-label {
            font-size: 0.8rem;
            font-weight: 600;
            color: #5a6c7d;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .loan-detail-value {
            font-size: 0.95rem;
            font-weight: 500;
            color: #2c3e50;
        }

        .loan-purpose {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        .loan-purpose-label {
            font-size: 0.8rem;
            font-weight: 600;
            color: #5a6c7d;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 5px;
        }

        .loan-purpose-text {
            font-size: 0.9rem;
            color: #2c3e50;
            line-height: 1.4;
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

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

        .status-approved {
            background: #d1ecf1;
            color: #0c5460;
        }

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

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

        .status-completed {
            background: #e2e3e5;
            color: #383d41;
        }

        .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;
        }

        .no-loans {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
        }

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

        .no-loans h3 {
            color: #5a6c7d;
            margin: 0 0 10px 0;
            font-size: 1.5rem;
        }

        .no-loans p {
            color: #6c757d;
            margin: 0 0 20px 0;
        }

        .no-loans .btn {
            background: #667eea;
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
            transition: background 0.3s ease;
        }

        .no-loans .btn:hover {
            background: #5a67d8;
            color: white;
            text-decoration: none;
        }

        @media (max-width: 768px) {
            .loan-history-grid {
                grid-template-columns: 1fr;
            }
            
            .loan-details {
                grid-template-columns: 1fr;
            }
        }
    </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>
        
        <!-- Left 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 btn-profile">Profile</a>
                    <a href="logout.php" class="btn btn-logout">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>
                                <span>Dashboard</span>
                            </a>
                        </li>
                        <li>
                            <a href="transactions.php">
                                <i class="fas fa-exchange-alt"></i>
                                <span>Transactions</span>
                            </a>
                        </li>
                        <li>
                            <a href="cards.php">
                                <i class="fas fa-credit-card"></i>
                                <span>Cards</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>TRANSFERS</h3>
                    <ul>
                        <li>
                            <a href="transfer.php">
                                <i class="fas fa-paper-plane"></i>
                                <span>Transfer Funds</span>
                            </a>
                        </li>
                        <li>
                            <a href="deposit.php">
                                <i class="fas fa-arrow-down"></i>
                                <span>Deposit</span>
                            </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>
                                <span>Loan Request</span>
                            </a>
                        </li>
                        <li>
                            <a href="irs-refund.php">
                                <i class="fas fa-file-invoice-dollar"></i>
                                <span>IRS Tax Refund</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>ACCOUNT</h3>
                    <ul>
                        <li>
                            <a href="account-info.php">
                                <i class="fas fa-user-circle"></i>
                                <span>Account Info</span>
                            </a>
                        </li>
                        <li class="active">
                            <a href="loan-history.php">
                                <i class="fas fa-history"></i>
                                <span>Loan History</span>
                            </a>
                        </li>
                        <li>
                            <a href="settings.php">
                                <i class="fas fa-cog"></i>
                                <span>Settings</span>
                            </a>
                        </li>
                        <li>
                            <a href="support.php">
                                <i class="fas fa-headset"></i>
                                <span>Support Ticket</span>
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <div class="sidebar-footer">
                <div class="secure-banking">
                    <i class="fas fa-shield-alt"></i>
                    <span>Secure Banking</span>
                </div>
                <div class="version">v1.2.0</div>
            </div>
        </aside>

        <!-- Main Content Area -->
        <main class="dashboard-main">
            <!-- Page Header -->
            <div class="page-header">
                <div class="header-content">
                    <h1><i class="fas fa-history"></i> Loan History</h1>
                    <p>View all your loan applications and their current status</p>
                </div>
            </div>

            <!-- Loan Statistics -->
            <div class="overview-cards">
                <div class="overview-card">
                    <div class="card-icon">
                        <i class="fas fa-list"></i>
                    </div>
                    <div class="card-content">
                        <h3>Total Loans</h3>
                        <div class="card-amount"><?php echo number_format($total_loans); ?></div>
                    </div>
                </div>
                
                <div class="overview-card">
                    <div class="card-icon income">
                        <i class="fas fa-hand-holding-usd"></i>
                    </div>
                    <div class="card-content">
                        <h3>Total Borrowed</h3>
                        <div class="card-amount"><?php echo formatCurrency($total_borrowed, $_SESSION['currency'] ?? '$'); ?></div>
                    </div>
                </div>
                
                <div class="overview-card">
                    <div class="card-icon outgoing">
                        <i class="fas fa-calendar-alt"></i>
                    </div>
                    <div class="card-content">
                        <h3>Monthly Payments</h3>
                        <div class="card-amount"><?php echo formatCurrency($total_monthly_payments, $_SESSION['currency'] ?? '$'); ?></div>
                    </div>
                </div>
                
                <div class="overview-card">
                    <div class="card-icon limit">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="card-content">
                        <h3>Active Loans</h3>
                        <div class="card-amount"><?php echo number_format($active_loans); ?></div>
                    </div>
                </div>
            </div>

            <!-- Loan Applications -->
            <?php if (empty($loan_applications)): ?>
                <div class="no-loans">
                    <i class="fas fa-file-invoice"></i>
                    <h3>No Loan Applications Found</h3>
                    <p>You haven't applied for any loans yet. Start your loan journey today!</p>
                    <a href="loan-request.php" class="btn">
                        <i class="fas fa-plus"></i>
                        Apply for Loan
                    </a>
                </div>
            <?php else: ?>
                <div class="loan-history-grid">
                    <?php foreach ($loan_applications as $loan): ?>
                        <div class="loan-card">
                            <div class="card-header">
                                <h3>
                                    Loan #<?php echo str_pad($loan['id'], 6, '0', STR_PAD_LEFT); ?>
                                    <span class="loan-type"><?php echo htmlspecialchars($loan['loan_type']); ?></span>
                                </h3>
                                <div class="loan-amount"><?php echo formatCurrency($loan['loan_amount'], $_SESSION['currency'] ?? '$'); ?></div>
                                <div class="loan-date">
                                    Applied: <?php echo date('M j, Y', strtotime($loan['created_at'])); ?>
                                </div>
                                <div class="status-badge status-<?php echo strtolower($loan['status']); ?>">
                                    <i class="fas fa-circle"></i>
                                    <?php echo htmlspecialchars($loan['status']); ?>
                                </div>
                            </div>
                            <div class="card-content">
                                <div class="loan-details">
                                    <div class="loan-detail">
                                        <span class="loan-detail-label">Interest Rate</span>
                                        <span class="loan-detail-value">
                                            <?php echo $loan['interest_rate'] ? $loan['interest_rate'] . '%' : 'N/A'; ?>
                                        </span>
                                    </div>
                                    <div class="loan-detail">
                                        <span class="loan-detail-label">Term</span>
                                        <span class="loan-detail-value">
                                            <?php echo $loan['term_months'] ? $loan['term_months'] . ' months' : 'N/A'; ?>
                                        </span>
                                    </div>
                                    <div class="loan-detail">
                                        <span class="loan-detail-label">Monthly Payment</span>
                                        <span class="loan-detail-value">
                                            <?php echo $loan['monthly_payment'] ? formatCurrency($loan['monthly_payment'], $_SESSION['currency'] ?? '$') : 'N/A'; ?>
                                        </span>
                                    </div>
                                    <div class="loan-detail">
                                        <span class="loan-detail-label">Last Updated</span>
                                        <span class="loan-detail-value">
                                            <?php echo date('M j, Y', strtotime($loan['updated_at'])); ?>
                                        </span>
                                    </div>
                                </div>
                                
                                <?php if ($loan['purpose']): ?>
                                    <div class="loan-purpose">
                                        <div class="loan-purpose-label">Purpose</div>
                                        <div class="loan-purpose-text"><?php echo htmlspecialchars($loan['purpose']); ?></div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </main>
    </div>

    <script src="assets/js/main.js"></script>
</body>
</html>

