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

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

$success_message = '';
$error_message = '';

// Handle loan application submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_application'])) {
    // Get form data
    $loan_type = trim($_POST['loan_type'] ?? '');
    $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
    $purpose = trim($_POST['purpose'] ?? '');
    $term_months = filter_input(INPUT_POST, 'term_months', FILTER_VALIDATE_INT);
    $monthly_income = filter_input(INPUT_POST, 'monthly_income', FILTER_VALIDATE_FLOAT);
    $employment_status = trim($_POST['employment_status'] ?? '');
    
    // Validate inputs
    $errors = [];
    
    if (empty($loan_type)) {
        $errors[] = "Loan type is required.";
    }
    
    if ($amount <= 0) {
        $errors[] = "Loan amount must be greater than zero.";
    }
    
    if (empty($purpose)) {
        $errors[] = "Loan purpose is required.";
    }
    
    if ($term_months <= 0) {
        $errors[] = "Loan term must be greater than zero.";
    }
    
    if ($monthly_income <= 0) {
        $errors[] = "Monthly income must be greater than zero.";
    }
    
    if (empty($employment_status)) {
        $errors[] = "Employment status is required.";
    }
    
    // If no errors, insert into database
    if (empty($errors)) {
        try {
            $stmt = $db->prepare("
                INSERT INTO loan_applications 
                (user_id, loan_type, amount, purpose, term_months, monthly_income, employment_status) 
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $_SESSION['user_id'],
                $loan_type,
                $amount,
                $purpose,
                $term_months,
                $monthly_income,
                $employment_status
            ]);
            
            $success_message = "Your loan application has been submitted successfully! We will review it shortly.";
        } catch (PDOException $e) {
            $error_message = "An error occurred while submitting your application. Please try again.";
            error_log("Loan Application Error: " . $e->getMessage());
        }
    } else {
        $error_message = implode("<br>", $errors);
    }
}

// Get user's existing loan applications
$stmt = $db->prepare("SELECT * FROM loan_applications WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$_SESSION['user_id']]);
$applications = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<style>
/* Redesigned Loan Application Page Styles */
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --primary-dark: #4338ca;
    --border-color: #e2e8f0;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --danger-color: #ef4444;
    --gray-100: #f3f4f6;
    --gray-200: #e5e7eb;
    --gray-300: #d1d5db;
    --gray-600: #4b5563;
    --gray-700: #374151;
    --gray-800: #1f2937;
}

.main-content { 
    background-color: #f8fafc; 
    min-height: 100vh;
}

/* Card Styles */
.app-card {
    background-color: white;
    border-radius: 1rem;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.app-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.app-card-header {
    padding: 1.25rem 1.5rem;
    border-bottom: 1px solid var(--border-color);
    background-color: white;
}

.app-card-body {
    padding: 1.5rem;
    flex-grow: 1;
}

.app-card-footer {
    padding: 1.25rem 1.5rem;
    background-color: var(--gray-100);
    border-top: 1px solid var(--border-color);
}

/* Status Badge Styles */
.status-badge {
    display: inline-block;
    padding: 0.35em 0.65em;
    font-size: 0.75em;
    font-weight: 700;
    line-height: 1;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    border-radius: 0.375rem;
}

.status-badge.pending { 
    background-color: var(--warning-color); 
    color: white; 
}

.status-badge.approved { 
    background-color: var(--success-color); 
    color: white; 
}

.status-badge.rejected { 
    background-color: var(--danger-color); 
    color: white; 
}

/* Form Styles */
.form-section {
    margin-bottom: 2rem;
    padding-bottom: 2rem;
    border-bottom: 1px solid var(--border-color);
}

.form-section:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
}

.form-section-title {
    font-size: 1.25rem;
    font-weight: 600;
    margin-bottom: 1.5rem;
    color: var(--primary-color);
    display: flex;
    align-items: center;
}

.form-section-title i {
    margin-right: 0.75rem;
    font-size: 1.5rem;
}

/* Application List Styles */
.application-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.application-item {
    background-color: white;
    border-radius: 0.75rem;
    padding: 1.25rem;
    border: 1px solid var(--border-color);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.application-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.05);
}

/* Loan Info Card */
.loan-info-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.loan-info-list li {
    display: flex;
    justify-content: space-between;
    padding: 0.75rem 0;
    border-bottom: 1px solid var(--border-color);
}

.loan-info-list li:last-child {
    border-bottom: none;
}

.loan-info-list .rate-label {
    color: var(--gray-600);
}

.loan-info-list .rate-value {
    font-weight: 600;
    color: var(--gray-800);
}

/* Button Styles */
.btn-primary {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

.btn-primary:hover, .btn-primary:focus {
    background-color: var(--primary-dark);
    border-color: var(--primary-dark);
}

.btn-outline-secondary {
    color: var(--gray-700);
    border-color: var(--gray-300);
}

.btn-outline-secondary:hover {
    background-color: var(--gray-100);
    color: var(--gray-800);
}
</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">Apply for a Loan</h1>
            <a href="loans.php" class="btn btn-outline-secondary"><i class='bx bx-arrow-back me-1'></i> Back to Loans</a>
        </div>

        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $success_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="row g-4">
            <!-- Left Column: Application Form -->
            <div class="col-lg-8">
                <div class="app-card">
                    <div class="app-card-header">
                        <h5 class="mb-0">New Loan Application</h5>
                    </div>
                    <div class="app-card-body">
                        <form method="POST" action="apply-loan.php">
                            <div class="form-section">
                                <div class="form-section-title">
                                    <i class='bx bx-money'></i> Loan Details
                                </div>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label for="loan_type" class="form-label">Loan Type</label>
                                        <select class="form-select" id="loan_type" name="loan_type" required>
                                            <option value="">Select Loan Type</option>
                                            <option value="Personal Loan">Personal Loan</option>
                                            <option value="Auto Loan">Auto Loan</option>
                                            <option value="Home Loan">Home Loan</option>
                                            <option value="Student Loan">Student Loan</option>
                                            <option value="Business Loan">Business Loan</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="amount" class="form-label">Loan Amount</label>
                                        <div class="input-group">
                                            <span class="input-group-text"><?php echo htmlspecialchars($user['currency']); ?></span>
                                            <input type="number" class="form-control" id="amount" name="amount" min="100" step="100" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="term_months" class="form-label">Loan Term (Months)</label>
                                        <select class="form-select" id="term_months" name="term_months" required>
                                            <option value="">Select Term</option>
                                            <option value="6">6 months</option>
                                            <option value="12">12 months</option>
                                            <option value="24">24 months</option>
                                            <option value="36">36 months</option>
                                            <option value="48">48 months</option>
                                            <option value="60">60 months</option>
                                        </select>
                                    </div>
                                    <div class="col-12">
                                        <label for="purpose" class="form-label">Loan Purpose</label>
                                        <textarea class="form-control" id="purpose" name="purpose" rows="3" required></textarea>
                                        <div class="form-text">Please explain why you need this loan and how you plan to use it.</div>
                                    </div>
                                </div>
                            </div>

                            <div class="form-section">
                                <div class="form-section-title">
                                    <i class='bx bx-dollar-circle'></i> Financial Information
                                </div>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label for="monthly_income" class="form-label">Monthly Income</label>
                                        <div class="input-group">
                                            <span class="input-group-text"><?php echo htmlspecialchars($user['currency']); ?></span>
                                            <input type="number" class="form-control" id="monthly_income" name="monthly_income" min="0" step="100" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="employment_status" class="form-label">Employment Status</label>
                                        <select class="form-select" id="employment_status" name="employment_status" required>
                                            <option value="">Select Status</option>
                                            <option value="Full-time">Full-time</option>
                                            <option value="Part-time">Part-time</option>
                                            <option value="Self-employed">Self-employed</option>
                                            <option value="Unemployed">Unemployed</option>
                                            <option value="Retired">Retired</option>
                                            <option value="Student">Student</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="form-section">
                                <div class="form-section-title">
                                    <i class='bx bx-check-shield'></i> Terms & Conditions
                                </div>
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="terms_agree" required>
                                    <label class="form-check-label" for="terms_agree">
                                        I agree to the <a href="#" data-bs-toggle="modal" data-bs-target="#termsModal">terms and conditions</a> for loan applications.
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="credit_check" required>
                                    <label class="form-check-label" for="credit_check">
                                        I authorize a credit check as part of my loan application.
                                    </label>
                                </div>
                            </div>

                            <div class="text-end mt-4">
                                <button type="submit" name="submit_application" class="btn btn-primary btn-lg">Submit Application</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Right Column: Application Status and Info -->
            <div class="col-lg-4 d-flex flex-column">
                <!-- Application Status Card -->
                <div class="app-card mb-4">
                    <div class="app-card-header">
                        <h5 class="mb-0">Your Applications</h5>
                    </div>
                    <div class="app-card-body">
                        <?php if (empty($applications)): ?>
                            <div class="text-center py-4">
                                <i class='bx bx-file text-muted' style="font-size: 3rem;"></i>
                                <p class="text-muted mt-2 mb-0">You have not submitted any loan applications yet.</p>
                            </div>
                        <?php else: ?>
                            <div class="application-list">
                                <?php foreach ($applications as $application): ?>
                                    <div class="application-item">
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <h6 class="mb-0"><?php echo htmlspecialchars($application['loan_type']); ?></h6>
                                            <span class="status-badge <?php echo htmlspecialchars($application['status']); ?>"><?php echo ucfirst($application['status']); ?></span>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div class="text-muted small"><?php echo date('M j, Y', strtotime($application['created_at'])); ?></div>
                                            <div class="fw-bold"><?php echo htmlspecialchars($user['currency']); ?> <?php echo number_format($application['amount'], 2); ?></div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Loan Information Card -->
                <div class="app-card">
                    <div class="app-card-header">
                        <h5 class="mb-0">Loan Information</h5>
                    </div>
                    <div class="app-card-body">
                        <h6 class="mb-3">Current Interest Rates</h6>
                        <ul class="loan-info-list mb-4">
                            <li>
                                <span class="rate-label">Personal Loan</span>
                                <span class="rate-value">7.5% - 12.5%</span>
                            </li>
                            <li>
                                <span class="rate-label">Auto Loan</span>
                                <span class="rate-value">4.25% - 7.5%</span>
                            </li>
                            <li>
                                <span class="rate-label">Home Loan</span>
                                <span class="rate-value">3.5% - 6.0%</span>
                            </li>
                            <li>
                                <span class="rate-label">Student Loan</span>
                                <span class="rate-value">5.0% - 8.0%</span>
                            </li>
                            <li>
                                <span class="rate-label">Business Loan</span>
                                <span class="rate-value">8.0% - 15.0%</span>
                            </li>
                        </ul>
                        
                        <div class="alert alert-info d-flex align-items-center" role="alert">
                            <i class='bx bx-info-circle me-2 fs-5'></i>
                            <div>Applications are typically processed within 2-3 business days.</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Terms and Conditions Modal -->
<div class="modal fade" id="termsModal" tabindex="-1" aria-labelledby="termsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="termsModalLabel">Loan Terms & Conditions</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <h6>1. Loan Application</h6>
                <p>By submitting this application, you certify that all information provided is true and accurate. Providing false information may result in rejection of your application and possible legal action.</p>
                
                <h6>2. Credit Check</h6>
                <p>You authorize us to conduct a credit check as part of the application review process. This may affect your credit score.</p>
                
                <h6>3. Approval Process</h6>
                <p>Loan approval is subject to credit worthiness, income verification, and other factors determined by our lending policy. We reserve the right to approve or deny any application.</p>
                
                <h6>4. Interest Rates</h6>
                <p>Interest rates are determined based on your credit history, loan amount, and term. The final rate will be disclosed upon approval.</p>
                
                <h6>5. Repayment</h6>
                <p>You agree to repay the loan according to the terms established upon approval. Late payments may result in additional fees and negative credit reporting.</p>
                
                <h6>6. Early Repayment</h6>
                <p>You may repay the loan in full at any time without penalty.</p>
                
                <h6>7. Privacy</h6>
                <p>Your personal and financial information will be handled in accordance with our privacy policy.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">I Understand</button>
            </div>
        </div>
    </div>
</div>

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