<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Apply for Property';

if (!$auth->isLoggedIn() || $auth->isAdmin()) {
    header('Location: ../login.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Check if profile is verified
if ($current_user['status'] !== 'active') {
    $_SESSION['error'] = "Please complete and verify your profile before applying";
    header('Location: complete-profile.php');
    exit;
}

// Get user's profile data
$sql = "SELECT * FROM user_profile_data WHERE user_id = ?";
$profile_data = $db->fetchOne($sql, [$current_user['id']]);

// Get available packages
$sql = "SELECT * FROM rental_packages WHERE status = 'active' ORDER BY display_order";
$packages = $db->fetchAll($sql);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_application'])) {
    $errors = [];
    
    // Get form data
    $package_id = !empty($_POST['package_id']) ? (int)$_POST['package_id'] : null;
    $property_address = trim($_POST['property_address']);
    $landlord_name = trim($_POST['landlord_name']);
    $annual_rent = (float)$_POST['annual_rent'];
    $lease_duration = (int)$_POST['lease_duration'];
    $move_in_date = $_POST['move_in_date'];
    $payment_frequency = $_POST['payment_frequency'];
    $comments = trim($_POST['comments']);
    
    // Validate
    if (empty($property_address)) $errors[] = "Property address is required";
    if (empty($landlord_name)) $errors[] = "Landlord name is required";
    if ($annual_rent <= 0) $errors[] = "Valid annual rent is required";
    if ($lease_duration < 6) $errors[] = "Lease duration must be at least 6 months";
    if (empty($move_in_date)) $errors[] = "Move-in date is required";
    
    if (empty($errors)) {
        try {
            $db->beginTransaction();
            
            // Generate application number
            $app_number = 'APP-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            
            // Calculate monthly rent and commission
            $monthly_rent = $annual_rent / 12;
            $commission_rate = $package_id ? 
                $db->fetchOne("SELECT commission_percentage FROM rental_packages WHERE id = ?", [$package_id])['commission_percentage'] 
                : COMMISSION_RATE;
            $commission_amount = ($monthly_rent * $commission_rate) / 100;
            $total_monthly_payment = $monthly_rent + $commission_amount;
            
            // Insert application
            $sql = "INSERT INTO rental_applications (
                    application_number, user_id, package_id, full_name, email, phone,
                    date_of_birth, nationality, address, state_of_origin,
                    next_of_kin_name, next_of_kin_phone, bvn, nin,
                    id_type, id_number, id_front_image, id_back_image, passport_photo,
                    employment_status, company_name, company_address, job_title,
                    monthly_income, employment_letter, bank_statement, business_registration,
                    property_address, landlord_name, annual_rent, monthly_rent,
                    commission_amount, total_monthly_payment, lease_duration,
                    move_in_date, payment_frequency, comments,
                    guarantor1_name, guarantor1_relationship, guarantor1_phone,
                    guarantor1_email, guarantor1_address, guarantor1_occupation, guarantor1_income,
                    guarantor2_name, guarantor2_relationship, guarantor2_phone,
                    guarantor2_email, guarantor2_address, guarantor2_occupation, guarantor2_income,
                    guarantor_form, status, payment_status, verification_status
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'unpaid', 'verified')";
            
            $db->execute($sql, [
                $app_number,
                $current_user['id'],
                $package_id,
                $current_user['first_name'] . ' ' . $current_user['last_name'],
                $current_user['email'],
                $current_user['phone'],
                $profile_data['date_of_birth'],
                'Nigerian',
                $current_user['address'],
                $profile_data['state_of_origin'],
                $profile_data['next_of_kin_name'],
                $profile_data['next_of_kin_phone'],
                $current_user['bvn'],
                $current_user['nin'],
                $profile_data['id_type'],
                $profile_data['id_number'],
                $profile_data['id_front_image'],
                $profile_data['id_back_image'],
                $profile_data['passport_photo'],
                $profile_data['employment_status'],
                $profile_data['company_name'],
                $profile_data['company_address'],
                $profile_data['job_title'],
                $profile_data['monthly_income'],
                $profile_data['employment_letter'],
                $profile_data['bank_statement'],
                $profile_data['business_registration'],
                $property_address,
                $landlord_name,
                $annual_rent,
                $monthly_rent,
                $commission_amount,
                $total_monthly_payment,
                $lease_duration,
                $move_in_date,
                $payment_frequency,
                $comments,
                $profile_data['guarantor1_name'],
                $profile_data['guarantor1_relationship'],
                $profile_data['guarantor1_phone'],
                $profile_data['guarantor1_email'],
                $profile_data['guarantor1_address'],
                $profile_data['guarantor1_occupation'],
                $profile_data['guarantor1_income'],
                $profile_data['guarantor2_name'],
                $profile_data['guarantor2_relationship'],
                $profile_data['guarantor2_phone'],
                $profile_data['guarantor2_email'],
                $profile_data['guarantor2_address'],
                $profile_data['guarantor2_occupation'],
                $profile_data['guarantor2_income'],
                $profile_data['guarantor_form']
            ]);
            
            $application_id = $db->lastInsertId();
            
            // Create notification for admin
            $sql = "INSERT INTO notifications (user_id, type, title, message, link) 
                    VALUES (1, 'info', 'New Rental Application', 'New application {$app_number} submitted', '/admin/rental-applications.php?view={$application_id}')";
            $db->execute($sql);
            
            // Log activity
            $sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                    VALUES (?, 'application_submit', 'rental_application', ?, 'Application submitted: {$app_number}', ?, ?)";
            $db->execute($sql, [
                $current_user['id'],
                $application_id,
                Security::getClientIP(),
                $_SERVER['HTTP_USER_AGENT'] ?? ''
            ]);
            
            $db->commit();
            
            $_SESSION['success'] = "Application submitted successfully! Application Number: {$app_number}";
            header('Location: application-details.php?id=' . $application_id);
            exit;
            
        } catch (Exception $e) {
            $db->rollBack();
            $errors[] = "Failed to submit application. Please try again.";
            error_log("Application submission error: " . $e->getMessage());
        }
    }
}

include 'includes/header.php';
?>

<style>
    .package-card {
        transition: all 0.3s;
        cursor: pointer;
        border: 2px solid transparent;
    }
    
    .package-card:hover {
        border-color: var(--primary);
        box-shadow: 0 8px 20px rgba(212, 160, 23, 0.2);
        transform: translateY(-5px);
    }
    
    .package-card.selected {
        border-color: var(--primary);
        background: rgba(212, 160, 23, 0.05);
    }
    
    .package-badge {
        position: absolute;
        top: 15px;
        right: 15px;
        background: var(--primary);
        color: white;
        padding: 5px 15px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    
    .feature-list {
        list-style: none;
        padding: 0;
    }
    
    .feature-list li {
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .feature-list li:last-child {
        border-bottom: none;
    }
    
    .feature-list li i {
        color: var(--primary);
        margin-right: 10px;
    }
</style>

<div class="page-header">
    <h1>Apply for Property</h1>
    <p class="text-muted">Submit your rental application in minutes</p>
</div>

<?php if (!empty($errors)): ?>
<div class="alert alert-danger alert-dismissible fade show">
    <ul class="mb-0">
        <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
        <?php endforeach; ?>
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Profile Verified Banner -->
<div class="alert alert-success">
    <div class="row align-items-center">
        <div class="col-md-8">
            <i class="fas fa-check-circle"></i>
            <strong>Your Profile is Verified!</strong> 
            You can now submit rental applications instantly. All your information is pre-filled from your verified profile.
        </div>
        <div class="col-md-4 text-md-end">
            <a href="profile.php" class="btn btn-sm btn-outline-success">
                <i class="fas fa-user"></i> View Profile
            </a>
        </div>
    </div>
</div>

<form method="POST" data-validate="true">
    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
    
    <div class="row">
        <!-- Main Form -->
        <div class="col-lg-8">
            <!-- Package Selection -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Step 1: Choose Your Package (Optional)</h5>
                </div>
                <div class="card-body">
                    <p class="text-muted mb-4">
                        Select a package that matches your needs, or skip to continue without a package.
                    </p>
                    
                    <div class="row">
                        <?php foreach ($packages as $package): ?>
                        <div class="col-md-4 mb-3">
                            <div class="card package-card h-100" data-package="<?php echo $package['id']; ?>">
                                <div class="card-body position-relative">
                                    <?php if ($package['name'] === 'Premium Plan'): ?>
                                    <span class="package-badge">Popular</span>
                                    <?php endif; ?>
                                    
                                    <h5 class="mb-3"><?php echo htmlspecialchars($package['name']); ?></h5>
                                    <p class="text-muted small"><?php echo htmlspecialchars($package['description']); ?></p>
                                    
                                    <div class="my-3">
                                        <h3 class="mb-0" style="color: var(--primary);">
                                            <?php echo $package['down_payment_percentage']; ?>%
                                        </h3>
                                        <small class="text-muted">Down Payment</small>
                                    </div>
                                    
                                    <ul class="feature-list">
                                        <?php 
                                        $features = json_decode($package['features'], true);
                                        foreach (array_slice($features, 0, 4) as $feature): 
                                        ?>
                                        <li><i class="fas fa-check"></i> <?php echo htmlspecialchars($feature); ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                    
                                    <input type="radio" name="package_id" value="<?php echo $package['id']; ?>" 
                                           class="d-none package-radio">
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="mt-3">
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="skipPackage">
                            Skip Package Selection
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- Property Details -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Step 2: Property Information</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Property Address <span class="text-danger">*</span></label>
                        <textarea name="property_address" class="form-control" rows="2" required
                                  placeholder="Full property address"><?php echo htmlspecialchars($_POST['property_address'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Landlord Name <span class="text-danger">*</span></label>
                            <input type="text" name="landlord_name" class="form-control" required
                                   value="<?php echo htmlspecialchars($_POST['landlord_name'] ?? ''); ?>"
                                   placeholder="Property owner's name">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Annual Rent (₦) <span class="text-danger">*</span></label>
                            <input type="number" name="annual_rent" class="form-control" required min="0" step="1000"
                                   value="<?php echo htmlspecialchars($_POST['annual_rent'] ?? ''); ?>"
                                   placeholder="e.g., 1200000" id="annualRent">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Lease Duration (Months) <span class="text-danger">*</span></label>
                            <select name="lease_duration" class="form-select" required>
                                <option value="">Select Duration</option>
                                <option value="6">6 Months</option>
                                <option value="12" selected>12 Months (1 Year)</option>
                                <option value="24">24 Months (2 Years)</option>
                                <option value="36">36 Months (3 Years)</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Move-In Date <span class="text-danger">*</span></label>
                            <input type="date" name="move_in_date" class="form-control" required
                                   min="<?php echo date('Y-m-d'); ?>"
                                   value="<?php echo htmlspecialchars($_POST['move_in_date'] ?? ''); ?>">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Payment Frequency <span class="text-danger">*</span></label>
                        <select name="payment_frequency" class="form-select" required>
                            <option value="monthly">Monthly</option>
                            <option value="quarterly">Quarterly (Every 3 Months)</option>
                            <option value="annually">Annually (Once a Year)</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Additional Comments</label>
                        <textarea name="comments" class="form-control" rows="3"
                                  placeholder="Any special requests or information you'd like to share"><?php echo htmlspecialchars($_POST['comments'] ?? ''); ?></textarea>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Summary Sidebar -->
        <div class="col-lg-4">
            <!-- Application Summary -->
            <div class="card sticky-top" style="top: 90px;">
                <div class="card-header" style="background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);">
                    <h5 class="mb-0 text-white">Application Summary</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3 pb-3 border-bottom">
                        <h6 class="text-muted mb-2">Annual Rent</h6>
                        <h4 class="mb-0" id="displayAnnualRent">₦0</h4>
                    </div>
                    
                    <div class="mb-3 pb-3 border-bottom">
                        <h6 class="text-muted mb-2">Monthly Breakdown</h6>
                        <div class="d-flex justify-content-between mb-2">
                            <span>Monthly Rent:</span>
                            <strong id="displayMonthlyRent">₦0</strong>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span>Commission (15%):</span>
                            <strong id="displayCommission">₦0</strong>
                        </div>
                        <div class="d-flex justify-content-between">
                            <span><strong>Total Monthly:</strong></span>
                            <strong style="color: var(--primary);" id="displayTotal">₦0</strong>
                        </div>
                    </div>
                    
                    <div class="alert alert-info small mb-3">
                        <i class="fas fa-info-circle"></i>
                        Your verified profile information will be automatically included in this application.
                    </div>
                    
                    <button type="submit" name="submit_application" class="btn btn-primary w-100 btn-lg">
                        <i class="fas fa-paper-plane"></i> Submit Application
                    </button>
                    
                    <a href="calculator.php" class="btn btn-outline-secondary w-100 mt-2">
                        <i class="fas fa-calculator"></i> Use Rent Calculator
                    </a>
                </div>
            </div>
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    // Package selection
    $('.package-card').click(function() {
        $('.package-card').removeClass('selected');
        $(this).addClass('selected');
        $(this).find('.package-radio').prop('checked', true);
    });
    
    $('#skipPackage').click(function() {
        $('.package-card').removeClass('selected');
        $('.package-radio').prop('checked', false);
    });
    
    // Calculate totals
    function calculateTotals() {
        const annualRent = parseFloat($('#annualRent').val()) || 0;
        const monthlyRent = annualRent / 12;
        const commission = (monthlyRent * 15) / 100;
        const totalMonthly = monthlyRent + commission;
        
        $('#displayAnnualRent').text('₦' + annualRent.toLocaleString());
        $('#displayMonthlyRent').text('₦' + monthlyRent.toLocaleString(undefined, {minimumFractionDigits: 2}));
        $('#displayCommission').text('₦' + commission.toLocaleString(undefined, {minimumFractionDigits: 2}));
        $('#displayTotal').text('₦' + totalMonthly.toLocaleString(undefined, {minimumFractionDigits: 2}));
    }
    
    $('#annualRent').on('input', calculateTotals);
    calculateTotals();
});
</script>

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