<?php
session_start();
require_once 'includes/auth_check.php';

$page = 'loans'; // For sidebar active state
$database = new Database();
$db = $database->getConnection();

// Fetch all loans for the logged-in user
$stmt = $db->prepare("SELECT * FROM loans WHERE user_id = ? ORDER BY status ASC, created_at DESC");
$stmt->execute([$_SESSION['user_id']]);
$loans = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate total loan balance
$total_balance = 0;
foreach ($loans as $loan) {
    if ($loan['status'] == 'active') {
        $total_balance += ($loan['total_amount'] - $loan['amount_paid']);
    }
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* My Loans Page Styles */
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --border-color: #e2e8f0;
    --success-color: #10b981;
    --warning-color: #f59e0b;
}
.main-content { background-color: #f8fafc; }

.loan-summary-card {
    background: linear-gradient(135deg, #4338ca, #6366F1);
    color: white;
    border-radius: 1rem;
    padding: 2rem;
    margin-bottom: 2rem;
}
.loan-summary-card h2 {
    font-size: 2.5rem;
    font-weight: 700;
}

.loan-card {
    background-color: white;
    border: 1px solid var(--border-color);
    border-radius: 1rem;
    margin-bottom: 1.5rem;
    transition: all 0.3s ease;
}
.loan-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.07);
}
.loan-card-header {
    padding: 1.25rem;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.loan-card-icon {
    font-size: 1.75rem;
    color: var(--primary-color);
}
.loan-card-body {
    padding: 1.5rem;
}
.progress-bar-container {
    height: 8px;
    background-color: #e9ecef;
    border-radius: 999px;
    overflow: hidden;
    margin-top: 0.5rem;
}
.progress-bar-fill {
    height: 100%;
    background-color: var(--primary-color);
    border-radius: 999px;
    transition: width 0.5s ease-in-out;
}
.loan-details-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 1rem;
    margin-top: 1.5rem;
}
.loan-detail-item {
    font-size: 0.875rem;
}
.loan-detail-item .label {
    color: #64748b;
    display: block;
}
.loan-detail-item .value {
    font-weight: 600;
}
.loan-card.paid-off {
    background-color: #f8f9fa;
    opacity: 0.8;
}
.loan-card.paid-off .progress-bar-fill {
    background-color: var(--success-color);
}
</style>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0">My Loans</h1>
            <a href="apply-loan.php" class="btn btn-primary"><i class='bx bx-plus me-1'></i> Apply for New Loan</a>
        </div>

        <!-- Loan Summary Card -->
        <div class="loan-summary-card text-center">
            <h5 class="text-white-50">Total Outstanding Loan Balance</h5>
            <h2><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($total_balance, 2); ?></h2>
        </div>

        <div class="row">
            <?php if (empty($loans)): ?>
                <div class="col-12">
                    <div class="card text-center py-5">
                        <div class="card-body">
                            <i class='bx bx-file-blank' style="font-size: 4rem; color: #cbd5e1;"></i>
                            <h5 class="mt-3">No Loans Found</h5>
                            <p class="text-muted">You do not have any active or past loans with us.</p>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($loans as $loan): ?>
                    <?php
                        $remaining_balance = $loan['total_amount'] - $loan['amount_paid'];
                        $progress_percentage = ($loan['total_amount'] > 0) ? ($loan['amount_paid'] / $loan['total_amount']) * 100 : 0;
                        $loan_icon = 'bx-money'; // Default
                        if (stripos($loan['loan_type'], 'auto') !== false) $loan_icon = 'bx-car';
                        if (stripos($loan['loan_type'], 'home') !== false || stripos($loan['loan_type'], 'mortgage') !== false) $loan_icon = 'bx-home';
                        if (stripos($loan['loan_type'], 'student') !== false) $loan_icon = 'bx-book';
                    ?>
                    <div class="col-md-6">
                        <div class="loan-card <?php echo ($loan['status'] == 'paid_off') ? 'paid-off' : ''; ?>">
                            <div class="loan-card-header">
                                <div>
                                    <h5 class="mb-0 d-flex align-items-center"><i class='bx <?php echo $loan_icon; ?> loan-card-icon me-2'></i> <?php echo htmlspecialchars($loan['loan_type']); ?></h5>
                                </div>
                                <span class="badge bg-<?php echo $loan['status'] == 'active' ? 'primary' : 'success'; ?>"><?php echo ucfirst($loan['status']); ?></span>
                            </div>
                            <div class="loan-card-body">
                                <div>
                                    <div class="d-flex justify-content-between mb-1">
                                        <span class="text-muted">Paid</span>
                                        <span class="fw-bold"><?php echo number_format($progress_percentage, 1); ?>%</span>
                                    </div>
                                    <div class="progress-bar-container">
                                        <div class="progress-bar-fill" style="width: <?php echo $progress_percentage; ?>%;"></div>
                                    </div>
                                </div>
                                <div class="loan-details-grid">
                                    <div class="loan-detail-item">
                                        <span class="label">Remaining Balance</span>
                                        <span class="value"><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($remaining_balance, 2); ?></span>
                                    </div>
                                    <div class="loan-detail-item">
                                        <span class="label">Interest Rate</span>
                                        <span class="value"><?php echo htmlspecialchars($loan['interest_rate']); ?>%</span>
                                    </div>
                                    <div class="loan-detail-item">
                                        <span class="label">Total Amount</span>
                                        <span class="value text-muted"><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($loan['total_amount'], 2); ?></span>
                                    </div>
                                    <div class="loan-detail-item">
                                        <span class="label">Next Payment</span>
                                        <span class="value"><?php echo $loan['next_payment_date'] ? date('M d, Y', strtotime($loan['next_payment_date'])) : 'N/A'; ?></span>
                                    </div>
                                </div>
                                <div class="mt-4 text-end">
                                    <a href="loan-details.php?id=<?php echo $loan['id']; ?>" class="btn btn-sm btn-outline-primary">View Details</a>

                                    <a href="#" class="btn btn-sm btn-primary">Make Payment</a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
