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

$page_title = 'Rental Applications';
$current_user = $auth->getCurrentUser();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    $action = $_POST['action'] ?? '';
    $app_id = (int)($_POST['app_id'] ?? 0);
    
    if ($action === 'approve' && ($auth->hasPermission('can_edit') || $auth->hasRole('super_admin'))) {
        $sql = "UPDATE rental_applications SET status = 'approved', reviewed_by = ?, reviewed_at = NOW() WHERE id = ?";
        $db->execute($sql, [$current_user['id'], $app_id]);
        
        // Send notification
        $app = $db->fetchOne("SELECT * FROM rental_applications WHERE id = ?", [$app_id]);
        $notif_sql = "INSERT INTO notifications (user_id, type, title, message) VALUES (?, 'application', 'Application Approved', ?)";
        $db->execute($notif_sql, [$app['user_id'], "Your rental application #{$app['application_number']} has been approved!"]);
        
        echo json_encode(['success' => true, 'message' => 'Application approved successfully']);
        exit;
    }
    
    if ($action === 'reject' && ($auth->hasPermission('can_edit') || $auth->hasRole('super_admin'))) {
        $reason = $_POST['reason'] ?? 'Not specified';
        $sql = "UPDATE rental_applications SET status = 'rejected', rejection_reason = ?, reviewed_by = ?, reviewed_at = NOW() WHERE id = ?";
        $db->execute($sql, [$reason, $current_user['id'], $app_id]);
        
        // Send notification
        $app = $db->fetchOne("SELECT * FROM rental_applications WHERE id = ?", [$app_id]);
        $notif_sql = "INSERT INTO notifications (user_id, type, title, message) VALUES (?, 'application', 'Application Rejected', ?)";
        $db->execute($notif_sql, [$app['user_id'], "Your rental application #{$app['application_number']} has been rejected. Reason: $reason"]);
        
        echo json_encode(['success' => true, 'message' => 'Application rejected']);
        exit;
    }
    
    if ($action === 'request_documents' && ($auth->hasPermission('can_edit') || $auth->hasRole('super_admin'))) {
        $documents = $_POST['documents'] ?? '';
        $sql = "UPDATE rental_applications SET status = 'documents_requested', admin_notes = ? WHERE id = ?";
        $db->execute($sql, [$documents, $app_id]);
        
        echo json_encode(['success' => true, 'message' => 'Document request sent']);
        exit;
    }
}

// Filters
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$package_filter = $_GET['package'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$sort = $_GET['sort'] ?? 'created_at';
$order = $_GET['order'] ?? 'DESC';
$page_num = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 15;
$offset = ($page_num - 1) * $limit;

// Build query
$where = [];
$params = [];

if ($search) {
    $where[] = "(application_number LIKE ? OR full_name LIKE ? OR email LIKE ? OR phone LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status_filter) {
    $where[] = "ra.status = ?";
    $params[] = $status_filter;
}

if ($package_filter) {
    $where[] = "ra.package_id = ?";
    $params[] = $package_filter;
}

if ($date_from) {
    $where[] = "DATE(ra.created_at) >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $where[] = "DATE(ra.created_at) <= ?";
    $params[] = $date_to;
}

$where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Get total
$count_sql = "SELECT COUNT(*) as total FROM rental_applications ra $where_sql";
$total = $db->fetchOne($count_sql, $params)['total'];
$total_pages = ceil($total / $limit);

// Get applications
$sql = "SELECT ra.*, u.email as user_email, rp.name as package_name,
        CONCAT(reviewer.first_name, ' ', reviewer.last_name) as reviewer_name
        FROM rental_applications ra
        LEFT JOIN users u ON ra.user_id = u.id
        LEFT JOIN rental_packages rp ON ra.package_id = rp.id
        LEFT JOIN users reviewer ON ra.reviewed_by = reviewer.id
        $where_sql
        ORDER BY $sort $order
        LIMIT $limit OFFSET $offset";

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

// Get packages for filter
$packages = $db->fetchAll("SELECT * FROM rental_packages WHERE status = 'active'");

// Statistics
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected,
    SUM(CASE WHEN status = 'under_review' THEN 1 ELSE 0 END) as under_review,
    SUM(annual_rent) as total_value
    FROM rental_applications";
$stats = $db->fetchOne($stats_sql);

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Rental Applications</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Rental Applications</li>
        </ol>
    </nav>
</div>

<!-- Statistics -->
<div class="row mb-4">
    <div class="col-md-2">
        <div class="card stat-card">
            <div class="stat-info text-center">
                <h3><?php echo number_format($stats['total']); ?></h3>
                <p>Total</p>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card stat-card">
            <div class="stat-info text-center">
                <h3 style="color: #ffc107;"><?php echo number_format($stats['pending']); ?></h3>
                <p>Pending</p>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card stat-card">
            <div class="stat-info text-center">
                <h3 style="color: #17a2b8;"><?php echo number_format($stats['under_review']); ?></h3>
                <p>Under Review</p>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card stat-card">
            <div class="stat-info text-center">
                <h3 style="color: #28a745;"><?php echo number_format($stats['approved']); ?></h3>
                <p>Approved</p>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card stat-card">
            <div class="stat-info text-center">
                <h3 style="color: #dc3545;"><?php echo number_format($stats['rejected']); ?></h3>
                <p>Rejected</p>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card stat-card">
            <div class="stat-info text-center">
                <h3>₦<?php echo number_format($stats['total_value']); ?></h3>
                <p>Total Value</p>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="fas fa-file-alt"></i> All Applications
        </h5>
    </div>
    
    <div class="card-body">
        <!-- Filters -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-3">
                    <input type="text" name="search" class="form-control" placeholder="Search..." 
                           value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="col-md-2">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="under_review" <?php echo $status_filter === 'under_review' ? 'selected' : ''; ?>>Under Review</option>
                        <option value="approved" <?php echo $status_filter === 'approved' ? 'selected' : ''; ?>>Approved</option>
                        <option value="rejected" <?php echo $status_filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="package" class="form-select">
                        <option value="">All Packages</option>
                        <?php foreach ($packages as $pkg): ?>
                        <option value="<?php echo $pkg['id']; ?>" <?php echo $package_filter == $pkg['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($pkg['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <input type="date" name="date_from" class="form-control" value="<?php echo $date_from; ?>">
                </div>
                <div class="col-md-2">
                    <input type="date" name="date_to" class="form-control" value="<?php echo $date_to; ?>">
                </div>
                <div class="col-md-1">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i>
                    </button>
                </div>
            </div>
        </form>
        
        <!-- Table -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Application #</th>
                        <th>Applicant</th>
                        <th>Package</th>
                        <th>Annual Rent</th>
                        <th>Monthly Payment</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th style="width: 200px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($applications)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4">
                            <i class="fas fa-inbox fa-3x text-muted mb-3 d-block"></i>
                            <p class="text-muted">No applications found</p>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($applications as $app): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($app['application_number']); ?></strong></td>
                            <td>
                                <?php echo htmlspecialchars($app['full_name']); ?>
                                <br>
                                <small class="text-muted">
                                    <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($app['email']); ?>
                                </small>
                            </td>
                            <td><?php echo htmlspecialchars($app['package_name'] ?? 'N/A'); ?></td>
                            <td><strong>₦<?php echo number_format($app['annual_rent']); ?></strong></td>
                            <td>₦<?php echo number_format($app['total_monthly_payment']); ?></td>
                            <td>
                                <?php
                                $badge_class = [
                                    'pending' => 'warning',
                                    'under_review' => 'info',
                                    'approved' => 'success',
                                    'rejected' => 'danger',
                                    'documents_requested' => 'secondary'
                                ][$app['status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $badge_class; ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $app['status'])); ?>
                                </span>
                            </td>
                            <td><?php echo date('M d, Y', strtotime($app['created_at'])); ?></td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-primary view-app" 
                                            data-id="<?php echo $app['id']; ?>"
                                            data-bs-toggle="tooltip" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    
                                    <?php if ($app['status'] === 'pending' && ($auth->hasPermission('can_edit') || $auth->hasRole('super_admin'))): ?>
                                    <button type="button" class="btn btn-outline-success approve-app" 
                                            data-id="<?php echo $app['id']; ?>"
                                            data-bs-toggle="tooltip" title="Approve">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <button type="button" class="btn btn-outline-danger reject-app" 
                                            data-id="<?php echo $app['id']; ?>"
                                            data-bs-toggle="tooltip" title="Reject">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    <?php endif; ?>
                                    
                                    <button type="button" class="btn btn-outline-info" 
                                            onclick="window.open('generate-pdf.php?type=application&id=<?php echo $app['id']; ?>', '_blank')"
                                            data-bs-toggle="tooltip" title="Download PDF">
                                        <i class="fas fa-file-pdf"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <nav>
            <ul class="pagination justify-content-center">
                <li class="page-item <?php echo $page_num <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page_num - 1])); ?>">Previous</a>
                </li>
                <?php for ($i = max(1, $page_num - 2); $i <= min($total_pages, $page_num + 2); $i++): ?>
                <li class="page-item <?php echo $i === $page_num ? 'active' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
                <li class="page-item <?php echo $page_num >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page_num + 1])); ?>">Next</a>
                </li>
            </ul>
        </nav>
        <?php endif; ?>
    </div>
</div>

<!-- View Application Modal -->
<div class="modal fade" id="appModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Application Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="appModalBody">
                <div class="text-center"><i class="fas fa-spinner fa-spin fa-3x"></i></div>
            </div>
        </div>
    </div>
</div>

<!-- Reject Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Reject Application</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <textarea id="rejectReason" class="form-control" rows="4" placeholder="Enter rejection reason..."></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmReject">Reject Application</button>
            </div>
        </div>
    </div>
</div>

<script>
    let currentAppId = null;
    
    $(document).ready(function() {
        // View application
        $('.view-app').click(function() {
            const appId = $(this).data('id');
            $('#appModal').modal('show');
            
            $.get('ajax/get-application-details.php', { id: appId }, function(data) {
                $('#appModalBody').html(data);
            });
        });
        
        // Approve
        $('.approve-app').click(function() {
            const appId = $(this).data('id');
            
            Swal.fire({
                title: 'Approve Application?',
                text: 'This will approve the rental application',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                confirmButtonText: 'Yes, approve'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('rental-applications.php', {
                        action: 'approve',
                        app_id: appId,
                        csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
                    }, function(response) {
                        if (response.success) {
                            Swal.fire('Approved!', response.message, 'success')
                                .then(() => location.reload());
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    }, 'json');
                }
            });
        });
        
        // Reject
        $('.reject-app').click(function() {
            currentAppId = $(this).data('id');
            $('#rejectModal').modal('show');
        });
        
        $('#confirmReject').click(function() {
            const reason = $('#rejectReason').val();
            
            if (!reason) {
                Swal.fire('Error', 'Please enter a rejection reason', 'error');
                return;
            }
            
            $.post('rental-applications.php', {
                action: 'reject',
                app_id: currentAppId,
                reason: reason,
                csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
            }, function(response) {
                if (response.success) {
                    $('#rejectModal').modal('hide');
                    Swal.fire('Rejected', response.message, 'success')
                        .then(() => location.reload());
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            }, 'json');
        });
        
        $('[data-bs-toggle="tooltip"]').tooltip();
    });
</script>

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