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

$page_title = 'Rent Calculator';

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

$current_user = $auth->getCurrentUser();

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

// Get pre-filled rent if from URL
$prefill_rent = isset($_GET['rent']) ? (float)$_GET['rent'] : 0;

include 'includes/header.php';
?>

<style>
    .calculator-card {
        max-width: 900px;
        margin: 0 auto;
    }
    
    .calc-input {
        font-size: 1.5rem;
        font-weight: 600;
        text-align: center;
    }
    
    .result-card {
        background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
        color: white;
        border-radius: 15px;
        padding: 25px;
        margin: 20px 0;
    }
    
    .result-value {
        font-size: 2.5rem;
        font-weight: bold;
    }
    
    .breakdown-item {
        padding: 15px;
        background: #f8f9fa;
        border-radius: 10px;
        margin-bottom: 10px;
        transition: all 0.3s;
    }
    
    .breakdown-item:hover {
        background: rgba(212, 160, 23, 0.1);
        transform: translateX(5px);
    }
    
    .package-option {
        padding: 20px;
        border: 2px solid #e0e0e0;
        border-radius: 10px;
        cursor: pointer;
        transition: all 0.3s;
        margin-bottom: 15px;
    }
    
    .package-option:hover {
        border-color: var(--primary);
        box-shadow: 0 5px 15px rgba(212, 160, 23, 0.2);
    }
    
    .package-option.selected {
        border-color: var(--primary);
        background: rgba(212, 160, 23, 0.05);
    }
</style>

<div class="calculator-card">
    <div class="card">
        <div class="card-header text-center" style="background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);">
            <h2 class="mb-0 text-white">
                <i class="fas fa-calculator"></i> Rent Payment Calculator
            </h2>
            <p class="mb-0 text-white opacity-75">Calculate your monthly payments and total costs</p>
        </div>
        
        <div class="card-body p-4">
            <!-- Annual Rent Input -->
            <div class="mb-4">
                <label class="form-label text-center d-block mb-3">
                    <h5>Enter Annual Rent (₦)</h5>
                </label>
                <div class="input-group input-group-lg">
                    <span class="input-group-text">₦</span>
                    <input type="number" class="form-control calc-input" id="annualRent" 
                           placeholder="e.g., 1,200,000" min="0" step="10000"
                           value="<?php echo $prefill_rent > 0 ? $prefill_rent : ''; ?>">
                </div>
            </div>
            
            <!-- Package Selection -->
            <div class="mb-4">
                <h5 class="mb-3">Select Payment Plan (Optional)</h5>
                
                <div id="packageOptions">
                    <div class="package-option" data-down-payment="0" data-commission="15">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-1">No Package</h6>
                                <small class="text-muted">Standard 15% commission</small>
                            </div>
                            <div class="text-end">
                                <strong class="text-primary">0%</strong>
                                <br>
                                <small class="text-muted">Down Payment</small>
                            </div>
                        </div>
                    </div>
                    
                    <?php foreach ($packages as $package): ?>
                    <div class="package-option" 
                         data-down-payment="<?php echo $package['down_payment_percentage']; ?>"
                         data-commission="<?php echo $package['commission_percentage']; ?>"
                         data-duration="<?php echo $package['duration_months']; ?>">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="mb-1"><?php echo htmlspecialchars($package['name']); ?></h6>
                                <small class="text-muted"><?php echo htmlspecialchars($package['description']); ?></small>
                            </div>
                            <div class="text-end">
                                <strong class="text-primary"><?php echo $package['down_payment_percentage']; ?>%</strong>
                                <br>
                                <small class="text-muted">Down Payment</small>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <!-- Results -->
            <div id="results" style="display: none;">
                <!-- Main Result -->
                <div class="result-card text-center">
                    <h6 class="opacity-75 mb-2">Your Monthly Payment</h6>
                    <div class="result-value" id="monthlyPayment">₦0</div>
                    <small class="opacity-75">Including commission</small>
                </div>
                
                <!-- Breakdown -->
                <h5 class="mb-3">Payment Breakdown</h5>
                
                <div class="breakdown-item">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-home text-primary me-2"></i>
                            <strong>Annual Rent</strong>
                        </div>
                        <h5 class="mb-0" id="displayAnnualRent">₦0</h5>
                    </div>
                </div>
                
                <div class="breakdown-item" id="downPaymentRow" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-hand-holding-usd text-success me-2"></i>
                            <strong>Down Payment <span id="downPaymentPercent">(0%)</span></strong>
                        </div>
                        <h5 class="mb-0 text-success" id="downPaymentAmount">₦0</h5>
                    </div>
                </div>
                
                <div class="breakdown-item">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-calendar-alt text-info me-2"></i>
                            <strong>Monthly Rent</strong>
                            <br>
                            <small class="text-muted">Annual rent ÷ 12 months</small>
                        </div>
                        <h5 class="mb-0 text-info" id="monthlyRent">₦0</h5>
                    </div>
                </div>
                
                <div class="breakdown-item">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-percentage text-warning me-2"></i>
                            <strong>Commission <span id="commissionPercent">(15%)</span></strong>
                            <br>
                            <small class="text-muted">Service charge per month</small>
                        </div>
                        <h5 class="mb-0 text-warning" id="commissionAmount">₦0</h5>
                    </div>
                </div>
                
                <div class="breakdown-item bg-primary text-white">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <i class="fas fa-money-bill-wave me-2"></i>
                            <strong>Total Monthly Payment</strong>
                            <br>
                            <small class="opacity-75">Monthly rent + Commission</small>
                        </div>
                        <h4 class="mb-0" id="totalMonthly">₦0</h4>
                    </div>
                </div>
                
                <!-- Summary Table -->
                <div class="mt-4">
                    <h5 class="mb-3">Payment Summary</h5>
                    <table class="table table-bordered">
                        <tbody>
                            <tr>
                                <td><strong>First Payment (with down payment)</strong></td>
                                <td class="text-end"><strong id="firstPayment">₦0</strong></td>
                            </tr>
                            <tr>
                                <td><strong>Subsequent Monthly Payments</strong></td>
                                <td class="text-end"><strong id="subsequentPayment">₦0</strong></td>
                            </tr>
                            <tr class="table-primary">
                                <td><strong>Total for 12 Months</strong></td>
                                <td class="text-end"><strong id="yearlyTotal">₦0</strong></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- Actions -->
                <div class="d-grid gap-2 mt-4">
                    <a href="apply.php" class="btn btn-primary btn-lg">
                        <i class="fas fa-paper-plane"></i> Apply with These Figures
                    </a>
                    <button class="btn btn-outline-secondary" onclick="window.print()">
                        <i class="fas fa-print"></i> Print Calculation
                    </button>
                </div>
            </div>
            
            <!-- Help Section -->
            <div class="alert alert-info mt-4">
                <h6><i class="fas fa-info-circle"></i> How It Works</h6>
                <ul class="mb-0 small">
                    <li><strong>Monthly Rent:</strong> Your annual rent divided by 12 months</li>
                    <li><strong>Commission:</strong> A percentage charged for property management services (typically 15%)</li>
                    <li><strong>Down Payment:</strong> Optional upfront payment that reduces your initial monthly costs</li>
                    <li><strong>Total Monthly:</strong> The amount you'll pay each month (rent + commission)</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    let selectedDownPayment = 0;
    let selectedCommission = 15;
    
    // Package selection
    $('.package-option').click(function() {
        $('.package-option').removeClass('selected');
        $(this).addClass('selected');
        
        selectedDownPayment = parseFloat($(this).data('down-payment')) || 0;
        selectedCommission = parseFloat($(this).data('commission')) || 15;
        
        calculate();
    });
    
    // Calculate on input
    $('#annualRent').on('input', function() {
        calculate();
    });
    
    // Select first option by default
    $('.package-option').first().click();
    
    function calculate() {
        const annualRent = parseFloat($('#annualRent').val()) || 0;
        
        if (annualRent <= 0) {
            $('#results').hide();
            return;
        }
        
        // Calculations
        const monthlyRent = annualRent / 12;
        const commission = (monthlyRent * selectedCommission) / 100;
        const totalMonthly = monthlyRent + commission;
        const downPayment = (annualRent * selectedDownPayment) / 100;
        const firstPayment = totalMonthly + downPayment;
        const yearlyTotal = (totalMonthly * 12) + downPayment;
        
        // Update display
        $('#displayAnnualRent').text('₦' + annualRent.toLocaleString());
        $('#monthlyRent').text('₦' + monthlyRent.toLocaleString(undefined, {minimumFractionDigits: 2}));
        $('#commissionPercent').text('(' + selectedCommission + '%)');
        $('#commissionAmount').text('₦' + commission.toLocaleString(undefined, {minimumFractionDigits: 2}));
        $('#monthlyPayment').text('₦' + totalMonthly.toLocaleString(undefined, {minimumFractionDigits: 2}));
        $('#totalMonthly').text('₦' + totalMonthly.toLocaleString(undefined, {minimumFractionDigits: 2}));
        
        // Down payment section
        if (selectedDownPayment > 0) {
            $('#downPaymentRow').show();
            $('#downPaymentPercent').text('(' + selectedDownPayment + '%)');
            $('#downPaymentAmount').text('₦' + downPayment.toLocaleString(undefined, {minimumFractionDigits: 2}));
        } else {
            $('#downPaymentRow').hide();
        }
        
        // Summary
        $('#firstPayment').text('₦' + firstPayment.toLocaleString(undefined, {minimumFractionDigits: 2}));
        $('#subsequentPayment').text('₦' + totalMonthly.toLocaleString(undefined, {minimumFractionDigits: 2}));
        $('#yearlyTotal').text('₦' + yearlyTotal.toLocaleString(undefined, {minimumFractionDigits: 2}));
        
        $('#results').fadeIn();
    }
    
    // Trigger calculation if prefilled
    <?php if ($prefill_rent > 0): ?>
    calculate();
    <?php endif; ?>
});
</script>

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