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

$page_title = 'My Applications';

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

$current_user = $auth->getCurrentUser();

// Get filter parameters
$status_filter = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';

// Build query
$sql = "SELECT * FROM rental_applications WHERE user_id = ?";
$params = [$current_user['id']];

if ($status_filter !== 'all') {
    $sql .= " AND status = ?";
    $params[] = $status_filter;
}

if (!empty($search)) {
    $sql .= " AND (application_number LIKE ? OR property_address LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$sql .= " ORDER BY created_at DESC";

$applications = $db->fetchAll($sql, $params);

// Get statistics
$stats = [
    'total' => count($db->fetchAll("SELECT id FROM rental_applications WHERE user_id = ?", [$current_user['id']])),
    'pending' => count($db->fetchAll("SELECT id FROM rental_applications WHERE user_id = ? AND status = 'pending'", [$current_user['id']])),
    'approved' => count($db->fetchAll("SELECT id FROM rental_applications WHERE user_id = ? AND status = 'approved'", [$current_user['id']])),
    'rejected' => count($db->fetchAll("SELECT id FROM rental_applications WHERE user_id = ? AND status = 'rejected'", [$current_user['id']]))
];

include 'includes/header.php';
?>

<style>
    .filter-tabs {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        flex-wrap: wrap;
    }
    
    .filter-tab {
        padding: 10px 20px;
        border: 2px solid #e0e0e0;
        border-radius: 25px;
        background: white;
        cursor: pointer;
        transition: all 0.3s;
        text-decoration: none;
        color: #666;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .filter-tab:hover {
        border-color: var(--primary);
        color: var(--primary);
    }
    
    .filter-tab.active {
        background: var(--primary);
        border-color: var(--primary);
        color: white;
    }
    
    .application-card {
        transition: all 0.3s;
        border-left: 4px solid transparent;
    }
    
    .application-card:hover {
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        transform: translateY(-3px);
    }
    
    .application-card.status-pending {
        border-left-color: #ffc107;
    }
    
    .application-card.status-approved {
        border-left-color: #28a745;
    }
    
    .application-card.status-rejected {
        border-left-color: #dc3545;
    }
    
    .application-card.status-under_review {
        border-left-color: #17a2b8;
    }
    
    .stat-badge {
        font-size: 1.5rem;
        font-weight: bold;
    }
</style>

<div class="page-header d-flex justify-content-between align-items-center">
    <div>
        <h1>My Applications</h1>
        <p class="text-muted mb-0">Track and manage your rental applications</p>
    </div>
    <a href="apply.php" class="btn btn-primary">
        <i class="fas fa-plus-circle"></i> New Application
    </a>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card">
            <div class="card-body text-center">
                <i class="fas fa-file-alt fa-2x text-primary mb-2"></i>
                <div class="stat-badge text-primary"><?php echo $stats['total']; ?></div>
                <div class="text-muted">Total Applications</div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body text-center">
                <i class="fas fa-clock fa-2x text-warning mb-2"></i>
                <div class="stat-badge text-warning"><?php echo $stats['pending']; ?></div>
                <div class="text-muted">Pending</div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body text-center">
                <i class="fas fa-check-circle fa-2x text-success mb-2"></i>
                <div class="stat-badge text-success"><?php echo $stats['approved']; ?></div>
                <div class="text-muted">Approved</div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body text-center">
                <i class="fas fa-times-circle fa-2x text-danger mb-2"></i>
                <div class="stat-badge text-danger"><?php echo $stats['rejected']; ?></div>
                <div class="text-muted">Rejected</div>
            </div>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <div class="row align-items-center">
            <div class="col-md-8">
                <div class="filter-tabs">
                    <a href="?status=all" class="filter-tab <?php echo $status_filter === 'all' ? 'active' : ''; ?>">
                        <i class="fas fa-list"></i> All
                    </a>
                    <a href="?status=pending" class="filter-tab <?php echo $status_filter === 'pending' ? 'active' : ''; ?>">
                        <i class="fas fa-clock"></i> Pending
                    </a>
                    <a href="?status=under_review" class="filter-tab <?php echo $status_filter === 'under_review' ? 'active' : ''; ?>">
                        <i class="fas fa-search"></i> Under Review
                    </a>
                    <a href="?status=approved" class="filter-tab <?php echo $status_filter === 'approved' ? 'active' : ''; ?>">
                        <i class="fas fa-check-circle"></i> Approved
                    </a>
                    <a href="?status=rejected" class="filter-tab <?php echo $status_filter === 'rejected' ? 'active' : ''; ?>">
                        <i class="fas fa-times-circle"></i> Rejected
                    </a>
                </div>
            </div>
            
            <div class="col-md-4">
                <form method="GET" class="d-flex gap-2">
                    <input type="hidden" name="status" value="<?php echo htmlspecialchars($status_filter); ?>">
                    <input type="text" name="search" class="form-control" 
                           placeholder="Search applications..." 
                           value="<?php echo htmlspecialchars($search); ?>">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search"></i>
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Applications List -->
<?php if (empty($applications)): ?>
<div class="card">
    <div class="card-body text-center py-5">
        <i class="fas fa-file-alt fa-5x text-muted mb-4"></i>
        <h4 class="text-muted">No Applications Found</h4>
        <p class="text-muted mb-4">
            <?php if ($status_filter !== 'all'): ?>
                No <?php echo ucfirst($status_filter); ?> applications at the moment.
            <?php else: ?>
                You haven't submitted any rental applications yet.
            <?php endif; ?>
        </p>
        <a href="apply.php" class="btn btn-primary btn-lg">
            <i class="fas fa-plus-circle"></i> Submit Your First Application
        </a>
    </div>
</div>
<?php else: ?>
<div class="row">
    <?php foreach ($applications as $app): ?>
    <div class="col-md-6 mb-4">
        <div class="card application-card status-<?php echo $app['status']; ?> h-100">
            <div class="card-body">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-start mb-3">
                    <div>
                        <h5 class="mb-1">
                            <a href="application-details.php?id=<?php echo $app['id']; ?>" 
                               class="text-decoration-none text-dark">
                                <?php echo htmlspecialchars($app['application_number']); ?>
                            </a>
                        </h5>
                        <small class="text-muted">
                            <i class="far fa-calendar"></i>
                            <?php echo date('F d, Y', strtotime($app['created_at'])); ?>
                        </small>
                    </div>
                    
                    <?php
                    $badge_class = [
                        'pending' => 'warning',
                        'under_review' => 'info',
                        'approved' => 'success',
                        'rejected' => 'danger',
                        'cancelled' => 'secondary'
                    ][$app['status']] ?? 'secondary';
                    ?>
                    <span class="badge bg-<?php echo $badge_class; ?>">
                        <?php echo ucfirst(str_replace('_', ' ', $app['status'])); ?>
                    </span>
                </div>
                
                <!-- Property Details -->
                <div class="mb-3">
                    <h6 class="text-muted mb-2">
                        <i class="fas fa-map-marker-alt"></i> Property
                    </h6>
                    <p class="mb-0"><?php echo htmlspecialchars($app['property_address']); ?></p>
                </div>
                
                <!-- Financial Details -->
                <div class="row mb-3">
                    <div class="col-6">
                        <div class="p-2 bg-light rounded">
                            <small class="text-muted d-block">Annual Rent</small>
                            <strong class="text-primary">₦<?php echo number_format($app['annual_rent']); ?></strong>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="p-2 bg-light rounded">
                            <small class="text-muted d-block">Monthly Payment</small>
                            <strong class="text-success">₦<?php echo number_format($app['total_monthly_payment']); ?></strong>
                        </div>
                    </div>
                </div>
                
                <!-- Landlord -->
                <div class="mb-3">
                    <small class="text-muted">
                        <i class="fas fa-user"></i> Landlord: 
                        <strong><?php echo htmlspecialchars($app['landlord_name']); ?></strong>
                    </small>
                </div>
                
                <!-- Payment Status -->
                <div class="mb-3">
                    <?php
                    $payment_badge = [
                        'unpaid' => 'danger',
                        'partial' => 'warning',
                        'paid' => 'success'
                    ][$app['payment_status']] ?? 'secondary';
                    ?>
                    <small class="text-muted">Payment: </small>
                    <span class="badge bg-<?php echo $payment_badge; ?>">
                        <?php echo ucfirst($app['payment_status']); ?>
                    </span>
                </div>
                
                <!-- Actions -->
                <div class="d-flex gap-2">
                    <a href="application-details.php?id=<?php echo $app['id']; ?>" 
                       class="btn btn-primary btn-sm flex-grow-1">
                        <i class="fas fa-eye"></i> View Details
                    </a>
                    
                    <?php if ($app['status'] === 'pending'): ?>
                    <button class="btn btn-outline-danger btn-sm cancel-application" 
                            data-id="<?php echo $app['id']; ?>"
                            data-number="<?php echo htmlspecialchars($app['application_number']); ?>">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                    <?php endif; ?>
                    
                    <?php if ($app['payment_status'] !== 'paid' && $app['status'] === 'approved'): ?>
                    <a href="payments.php?application=<?php echo $app['id']; ?>" 
                       class="btn btn-success btn-sm">
                        <i class="fas fa-credit-card"></i> Pay
                    </a>
                    <?php endif; ?>
                </div>
                
                <!-- Progress Bar for Approved Applications -->
                <?php if ($app['status'] === 'approved'): ?>
                <div class="mt-3">
                    <small class="text-muted d-block mb-1">Move-in Date</small>
                    <?php
                    $move_in = strtotime($app['move_in_date']);
                    $now = time();
                    $days_remaining = ceil(($move_in - $now) / 86400);
                    ?>
                    <div class="progress" style="height: 8px;">
                        <div class="progress-bar bg-success" 
                             style="width: <?php echo max(0, min(100, 100 - ($days_remaining / 30 * 100))); ?>%">
                        </div>
                    </div>
                    <small class="text-muted">
                        <?php if ($days_remaining > 0): ?>
                            <?php echo $days_remaining; ?> days until move-in
                        <?php else: ?>
                            Move-in date reached
                        <?php endif; ?>
                    </small>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Cancel Application Modal -->
<div class="modal fade" id="cancelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Cancel Application</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to cancel application <strong id="cancelAppNumber"></strong>?</p>
                <p class="text-danger mb-0">
                    <i class="fas fa-exclamation-triangle"></i>
                    This action cannot be undone. You will need to submit a new application if you change your mind.
                </p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No, Keep It</button>
                <button type="button" class="btn btn-danger" id="confirmCancel">Yes, Cancel Application</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    let cancelApplicationId = null;
    
    // Cancel application
    $('.cancel-application').click(function() {
        cancelApplicationId = $(this).data('id');
        const appNumber = $(this).data('number');
        
        $('#cancelAppNumber').text(appNumber);
        $('#cancelModal').modal('show');
    });
    
    $('#confirmCancel').click(function() {
        if (!cancelApplicationId) return;
        
        $.ajax({
            url: 'ajax/cancel-application.php',
            type: 'POST',
            data: {
                application_id: cancelApplicationId,
                csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
            },
            dataType: 'json',
            success: function(response) {
                $('#cancelModal').modal('hide');
                
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Application Cancelled',
                        text: response.message,
                        timer: 2000
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message || 'Failed to cancel application'
                    });
                }
            },
            error: function() {
                $('#cancelModal').modal('hide');
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred. Please try again.'
                });
            }
        });
    });
});
</script>

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