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

$page_title = 'Application Details';

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

$current_user = $auth->getCurrentUser();

// Get application ID
$application_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Get application details
$sql = "SELECT * FROM rental_applications WHERE id = ? AND user_id = ?";
$application = $db->fetchOne($sql, [$application_id, $current_user['id']]);

if (!$application) {
    $_SESSION['error'] = "Application not found";
    header('Location: applications.php');
    exit;
}

// Get payment history for this application
$sql = "SELECT * FROM rent_payments WHERE rental_application_id = ? ORDER BY due_date";
$payments = $db->fetchAll($sql, [$application_id]);

include 'includes/header.php';
?>

<style>
    .detail-row {
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .detail-row:last-child {
        border-bottom: none;
    }
    
    .detail-label {
        font-weight: 600;
        color: #666;
    }
    
    .timeline {
        position: relative;
        padding-left: 30px;
    }
    
    .timeline::before {
        content: '';
        position: absolute;
        left: 8px;
        top: 0;
        bottom: 0;
        width: 2px;
        background: #e0e0e0;
    }
    
    .timeline-item {
        position: relative;
        margin-bottom: 20px;
    }
    
    .timeline-item::before {
        content: '';
        position: absolute;
        left: -26px;
        top: 4px;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background: white;
        border: 3px solid #e0e0e0;
    }
    
    .timeline-item.completed::before {
        background: #28a745;
        border-color: #28a745;
    }
    
    .timeline-item.active::before {
        background: #ffc107;
        border-color: #ffc107;
    }
    
    .document-badge {
        display: inline-block;
        padding: 8px 15px;
        background: #f8f9fa;
        border-radius: 8px;
        margin: 5px;
    }
</style>

<div class="mb-4">
    <a href="applications.php" class="btn btn-outline-secondary">
        <i class="fas fa-arrow-left"></i> Back to Applications
    </a>
</div>

<!-- Application Header -->
<div class="card mb-4" style="background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);">
    <div class="card-body text-white p-4">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h2 class="mb-2"><?php echo htmlspecialchars($application['application_number']); ?></h2>
                <p class="mb-0 opacity-75">
                    <i class="far fa-calendar"></i>
                    Submitted on <?php echo date('F d, Y \a\t H:i', strtotime($application['created_at'])); ?>
                </p>
            </div>
            <div class="col-md-4 text-md-end">
                <?php
                $badge_class = [
                    'pending' => 'warning',
                    'under_review' => 'info',
                    'approved' => 'success',
                    'rejected' => 'danger',
                    'cancelled' => 'secondary'
                ][$application['status']] ?? 'secondary';
                ?>
                <h3>
                    <span class="badge bg-<?php echo $badge_class; ?> p-3">
                        <?php echo ucfirst(str_replace('_', ' ', $application['status'])); ?>
                    </span>
                </h3>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Left Column -->
    <div class="col-lg-8">
        <!-- Property Information -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-home"></i> Property Details</h5>
            </div>
            <div class="card-body">
                <div class="detail-row">
                    <div class="detail-label mb-1">Property Address</div>
                    <div><?php echo nl2br(htmlspecialchars($application['property_address'])); ?></div>
                </div>
                
                <div class="detail-row">
                    <div class="detail-label mb-1">Landlord</div>
                    <div><?php echo htmlspecialchars($application['landlord_name']); ?></div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-md-6">
                        <div class="p-3 bg-light rounded">
                            <small class="text-muted d-block">Annual Rent</small>
                            <h4 class="mb-0 text-primary">₦<?php echo number_format($application['annual_rent']); ?></h4>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="p-3 bg-light rounded">
                            <small class="text-muted d-block">Monthly Payment</small>
                            <h4 class="mb-0 text-success">₦<?php echo number_format($application['total_monthly_payment']); ?></h4>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-3">
                    <div class="col-md-4">
                        <div class="detail-label">Monthly Rent</div>
                        <div>₦<?php echo number_format($application['monthly_rent']); ?></div>
                    </div>
                    <div class="col-md-4">
                        <div class="detail-label">Commission</div>
                        <div>₦<?php echo number_format($application['commission_amount']); ?></div>
                    </div>
                    <div class="col-md-4">
                        <div class="detail-label">Lease Duration</div>
                        <div><?php echo $application['lease_duration']; ?> months</div>
                    </div>
                </div>
                
                <div class="detail-row mt-3">
                    <div class="detail-label mb-1">Move-in Date</div>
                    <div>
                        <i class="far fa-calendar"></i>
                        <?php echo date('F d, Y', strtotime($application['move_in_date'])); ?>
                        <?php
                        $days_remaining = ceil((strtotime($application['move_in_date']) - time()) / 86400);
                        if ($days_remaining > 0):
                        ?>
                        <span class="badge bg-info ms-2"><?php echo $days_remaining; ?> days to go</span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="detail-row">
                    <div class="detail-label mb-1">Payment Frequency</div>
                    <div><?php echo ucfirst($application['payment_frequency']); ?></div>
                </div>
                
                <?php if (!empty($application['comments'])): ?>
                <div class="detail-row">
                    <div class="detail-label mb-1">Additional Comments</div>
                    <div class="text-muted"><?php echo nl2br(htmlspecialchars($application['comments'])); ?></div>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Employment & Guarantor Info -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-briefcase"></i> Employment & Income</h5>
            </div>
            <div class="card-body">
                <div class="detail-row">
                    <div class="detail-label">Employment Status</div>
                    <div><?php echo ucwords(str_replace('_', ' ', $application['employment_status'])); ?></div>
                </div>
                
                <?php if (!empty($application['company_name'])): ?>
                <div class="detail-row">
                    <div class="detail-label">Company</div>
                    <div><?php echo htmlspecialchars($application['company_name']); ?></div>
                </div>
                <?php endif; ?>
                
                <div class="detail-row">
                    <div class="detail-label">Monthly Income</div>
                    <div>₦<?php echo number_format($application['monthly_income']); ?></div>
                </div>
                
                <div class="detail-row">
                    <div class="detail-label">Guarantor 1</div>
                    <div>
                        <strong><?php echo htmlspecialchars($application['guarantor1_name']); ?></strong>
                        <br>
                        <small class="text-muted">
                            <?php echo htmlspecialchars($application['guarantor1_phone']); ?> •
                            <?php echo ucwords($application['guarantor1_relationship']); ?>
                        </small>
                    </div>
                </div>
                
                <?php if (!empty($application['guarantor2_name'])): ?>
                <div class="detail-row">
                    <div class="detail-label">Guarantor 2</div>
                    <div>
                        <strong><?php echo htmlspecialchars($application['guarantor2_name']); ?></strong>
                        <br>
                        <small class="text-muted">
                            <?php echo htmlspecialchars($application['guarantor2_phone']); ?> •
                            <?php echo ucwords($application['guarantor2_relationship']); ?>
                        </small>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Submitted Documents -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-file-alt"></i> Submitted Documents</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <?php
                    $documents = [
                        'id_front_image' => 'ID Card (Front)',
                        'id_back_image' => 'ID Card (Back)',
                        'passport_photo' => 'Passport Photo',
                        'employment_letter' => 'Employment Letter',
                        'bank_statement' => 'Bank Statement',
                        'business_registration' => 'Business Registration',
                        'guarantor_form' => 'Guarantor Form'
                    ];
                    
                    foreach ($documents as $field => $label):
                        if (!empty($application[$field])):
                    ?>
                    <div class="col-md-6 mb-2">
                        <div class="document-badge">
                            <i class="fas fa-check-circle text-success"></i>
                            <?php echo $label; ?>
                        </div>
                    </div>
                    <?php
                        endif;
                    endforeach;
                    ?>
                </div>
            </div>
        </div>
        
        <!-- Admin Notes (if any) -->
        <?php if (!empty($application['admin_notes'])): ?>
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-sticky-note"></i> Admin Notes</h5>
            </div>
            <div class="card-body">
                <div class="alert alert-info mb-0">
                    <?php echo nl2br(htmlspecialchars($application['admin_notes'])); ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Rejection Reason (if rejected) -->
        <?php if ($application['status'] === 'rejected' && !empty($application['rejection_reason'])): ?>
        <div class="card mb-4 border-danger">
            <div class="card-header bg-danger text-white">
                <h5 class="mb-0"><i class="fas fa-exclamation-triangle"></i> Rejection Reason</h5>
            </div>
            <div class="card-body">
                <p class="mb-0"><?php echo nl2br(htmlspecialchars($application['rejection_reason'])); ?></p>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Right Column -->
    <div class="col-lg-4">
        <!-- Payment Status -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-credit-card"></i> Payment Status</h5>
            </div>
            <div class="card-body">
                <?php
                $payment_badge = [
                    'unpaid' => 'danger',
                    'partial' => 'warning',
                    'paid' => 'success'
                ][$application['payment_status']] ?? 'secondary';
                ?>
                <div class="text-center mb-3">
                    <h3>
                        <span class="badge bg-<?php echo $payment_badge; ?> p-3">
                            <?php echo ucfirst($application['payment_status']); ?>
                        </span>
                    </h3>
                </div>
                
                <?php if ($application['payment_status'] !== 'paid'): ?>
                <a href="payments.php?application=<?php echo $application['id']; ?>" 
                   class="btn btn-success w-100 mb-2">
                    <i class="fas fa-credit-card"></i> Make Payment
                </a>
                <?php endif; ?>
                
                <a href="payments.php" class="btn btn-outline-primary w-100">
                    <i class="fas fa-history"></i> Payment History
                </a>
            </div>
        </div>
        
        <!-- Application Timeline -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-history"></i> Application Timeline</h5>
            </div>
            <div class="card-body">
                <div class="timeline">
                    <div class="timeline-item completed">
                        <strong>Application Submitted</strong>
                        <br>
                        <small class="text-muted">
                            <?php echo date('M d, Y H:i', strtotime($application['created_at'])); ?>
                        </small>
                    </div>
                    
                    <?php if ($application['reviewed_at']): ?>
                    <div class="timeline-item completed">
                        <strong>Reviewed by Admin</strong>
                        <br>
                        <small class="text-muted">
                            <?php echo date('M d, Y H:i', strtotime($application['reviewed_at'])); ?>
                        </small>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($application['status'] === 'approved'): ?>
                    <div class="timeline-item completed">
                        <strong>Application Approved</strong>
                        <br>
                        <small class="text-muted">
                            <?php echo date('M d, Y H:i', strtotime($application['updated_at'])); ?>
                        </small>
                    </div>
                    <?php elseif ($application['status'] === 'rejected'): ?>
                    <div class="timeline-item">
                        <strong class="text-danger">Application Rejected</strong>
                        <br>
                        <small class="text-muted">
                            <?php echo date('M d, Y H:i', strtotime($application['updated_at'])); ?>
                        </small>
                    </div>
                    <?php else: ?>
                    <div class="timeline-item active">
                        <strong>Under Review</strong>
                        <br>
                        <small class="text-muted">In progress</small>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($application['status'] === 'approved'): ?>
                    <div class="timeline-item <?php echo time() >= strtotime($application['move_in_date']) ? 'completed' : ''; ?>">
                        <strong>Move-in Date</strong>
                        <br>
                        <small class="text-muted">
                            <?php echo date('M d, Y', strtotime($application['move_in_date'])); ?>
                        </small>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Quick Actions -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-bolt"></i> Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="calculator.php?rent=<?php echo $application['annual_rent']; ?>" 
                       class="btn btn-outline-primary">
                        <i class="fas fa-calculator"></i> View in Calculator
                    </a>
                    
                    <a href="messages.php?new=1&ref=app_<?php echo $application['id']; ?>" 
                       class="btn btn-outline-info">
                        <i class="fas fa-envelope"></i> Contact Support
                    </a>
                    
                    <?php if ($application['status'] === 'pending'): ?>
                    <button class="btn btn-outline-danger" id="cancelApplication">
                        <i class="fas fa-times"></i> Cancel Application
                    </button>
                    <?php endif; ?>
                    
                    <button class="btn btn-outline-secondary" onclick="window.print()">
                        <i class="fas fa-print"></i> Print Details
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#cancelApplication').click(function() {
        Swal.fire({
            title: 'Cancel Application?',
            html: 'Are you sure you want to cancel <strong><?php echo htmlspecialchars($application['application_number']); ?></strong>?<br><br><span class="text-danger">This action cannot be undone.</span>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Cancel It',
            cancelButtonText: 'No, Keep It'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'ajax/cancel-application.php',
                    type: 'POST',
                    data: {
                        application_id: <?php echo $application['id']; ?>,
                        csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Application Cancelled',
                                text: response.message,
                                timer: 2000
                            }).then(() => {
                                window.location.href = 'applications.php';
                            });
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error', 'An error occurred. Please try again.', 'error');
                    }
                });
            }
        });
    });
});
</script>

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