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

$page_title = 'Sell Applications';

if (!$auth->isAdmin()) {
    $_SESSION['error'] = "You don't have permission to access this page";
    header('Location: dashboard.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!Security::validateCSRFToken($_POST['csrf_token'])) {
        die('Invalid CSRF token');
    }
    
    $action = $_POST['action'];
    $app_id = (int)$_POST['app_id'];
    
    if ($action === 'update_status') {
        $status = $_POST['status'];
        $admin_notes = $_POST['admin_notes'] ?? '';
        
        $sql = "UPDATE sell_applications SET 
                status = ?, 
                updated_at = NOW()
                WHERE id = ?";
        
        if ($db->execute($sql, [$status, $app_id])) {
            // Log activity
            $sql = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, user_agent) 
                    VALUES (?, 'update_sell_application', 'sell_application', ?, ?, ?, ?)";
            $db->execute($sql, [
                $current_user['id'],
                $app_id,
                "Sell application status changed to $status",
                Security::getClientIP(),
                $_SERVER['HTTP_USER_AGENT'] ?? ''
            ]);
            
            echo json_encode(['success' => true, 'message' => 'Status updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update status']);
        }
        exit;
    }
    
    if ($action === 'delete' && $auth->hasRole('super_admin')) {
        $sql = "DELETE FROM sell_applications WHERE id = ?";
        if ($db->execute($sql, [$app_id])) {
            $_SESSION['success'] = "Application deleted successfully";
        } else {
            $_SESSION['error'] = "Failed to delete application";
        }
        header('Location: sell-applications.php');
        exit;
    }
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

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

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

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

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

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

$sql = "SELECT sa.*, u.email as user_email
        FROM sell_applications sa
        LEFT JOIN users u ON sa.user_id = u.id
        $where_sql
        ORDER BY sa.created_at DESC
        LIMIT $limit OFFSET $offset";

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

// Get statistics
$stats = [
    'pending' => $db->fetchOne("SELECT COUNT(*) as count FROM sell_applications WHERE status = 'pending'")['count'],
    'approved' => $db->fetchOne("SELECT COUNT(*) as count FROM sell_applications WHERE status = 'approved'")['count'],
    'listed' => $db->fetchOne("SELECT COUNT(*) as count FROM sell_applications WHERE status = 'listed'")['count'],
    'sold' => $db->fetchOne("SELECT COUNT(*) as count FROM sell_applications WHERE status = 'sold'")['count']
];

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Sell 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">Sell Applications</li>
        </ol>
    </nav>
</div>

<?php if (isset($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show">
    <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Statistics -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-clock fa-2x text-warning"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['pending']; ?></h3>
                        <p class="text-muted mb-0">Pending</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-check fa-2x text-success"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['approved']; ?></h3>
                        <p class="text-muted mb-0">Approved</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-list fa-2x text-info"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['listed']; ?></h3>
                        <p class="text-muted mb-0">Listed</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-handshake fa-2x text-primary"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['sold']; ?></h3>
                        <p class="text-muted mb-0">Sold</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="fas fa-handshake"></i> All Applications
            <span class="badge bg-primary"><?php echo number_format($total); ?></span>
        </h5>
    </div>
    
    <div class="card-body">
        <!-- Filters -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-6">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" name="search" class="form-control" placeholder="Search..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                
                <div class="col-md-4">
                    <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="listed" <?php echo $status_filter === 'listed' ? 'selected' : ''; ?>>Listed</option>
                        <option value="sold" <?php echo $status_filter === 'sold' ? 'selected' : ''; ?>>Sold</option>
                        <option value="rejected" <?php echo $status_filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                </div>
            </div>
        </form>
        
        <!-- Applications Table -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Application #</th>
                        <th>Seller Info</th>
                        <th>Property Type</th>
                        <th>Price</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($applications)): ?>
                    <tr>
                        <td colspan="7" 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>
                                <strong><?php echo htmlspecialchars($app['seller_name']); ?></strong>
                                <br>
                                <small class="text-muted">
                                    <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($app['email']); ?>
                                </small>
                                <br>
                                <small class="text-muted">
                                    <i class="fas fa-phone"></i> <?php echo htmlspecialchars($app['phone']); ?>
                                </small>
                            </td>
                            <td>
                                <span class="badge bg-info">
                                    <?php echo htmlspecialchars($app['property_type']); ?>
                                </span>
                                <br>
                                <small class="text-muted">
                                    Category: <?php echo htmlspecialchars($app['seller_category']); ?>
                                </small>
                            </td>
                            <td>
                                <strong>₦<?php echo number_format($app['price']); ?></strong>
                            </td>
                            <td>
                                <?php
                                $badge_class = [
                                    'pending' => 'warning',
                                    'under_review' => 'info',
                                    'approved' => 'success',
                                    'listed' => 'primary',
                                    'sold' => 'dark',
                                    'rejected' => 'danger'
                                ][$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'])); ?>
                                <br>
                                <small class="text-muted"><?php echo date('H:i', strtotime($app['created_at'])); ?></small>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-primary view-details" 
                                            data-id="<?php echo $app['id']; ?>">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    
                                    <button type="button" class="btn btn-outline-success update-status" 
                                            data-id="<?php echo $app['id']; ?>"
                                            data-status="<?php echo $app['status']; ?>">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    
                                    <?php if ($auth->hasRole('super_admin')): ?>
                                    <button type="button" class="btn btn-outline-danger delete-app" 
                                            data-id="<?php echo $app['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($app['application_number']); ?>">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </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 <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">Previous</a>
                </li>
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <li class="page-item <?php echo $i === $page ? '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 >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">Next</a>
                </li>
            </ul>
        </nav>
        <?php endif; ?>
    </div>
</div>

<!-- View Details Modal -->
<div class="modal fade" id="detailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <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="detailsContent">
                <div class="text-center py-4">
                    <div class="spinner-border" role="status"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Update Status Modal -->
<div class="modal fade" id="statusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Status</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="statusAppId">
                
                <div class="mb-3">
                    <label class="form-label">Status</label>
                    <select id="newStatus" class="form-select">
                        <option value="pending">Pending</option>
                        <option value="under_review">Under Review</option>
                        <option value="approved">Approved</option>
                        <option value="listed">Listed</option>
                        <option value="sold">Sold</option>
                        <option value="rejected">Rejected</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">Admin Notes</label>
                    <textarea id="adminNotes" class="form-control" rows="3"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="saveStatus">Save Changes</button>
            </div>
        </div>
    </div>
</div>

<form method="POST" id="deleteForm" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="app_id" id="deleteId">
    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
</form>

<script>
    // View details
    $('.view-details').click(function() {
        const appId = $(this).data('id');
        $('#detailsContent').html('<div class="text-center py-4"><div class="spinner-border"></div></div>');
        $('#detailsModal').modal('show');
        
        $.get('ajax/get-sell-application-details.php', { id: appId }, function(data) {
            $('#detailsContent').html(data);
        });
    });
    
    // Update status
    $('.update-status').click(function() {
        const appId = $(this).data('id');
        const currentStatus = $(this).data('status');
        
        $('#statusAppId').val(appId);
        $('#newStatus').val(currentStatus);
        $('#statusModal').modal('show');
    });
    
    $('#saveStatus').click(function() {
        const appId = $('#statusAppId').val();
        const status = $('#newStatus').val();
        const notes = $('#adminNotes').val();
        
        $.post('sell-applications.php', {
            action: 'update_status',
            app_id: appId,
            status: status,
            admin_notes: notes,
            csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
        }, function(response) {
            if (response.success) {
                $('#statusModal').modal('hide');
                Swal.fire('Success', response.message, 'success').then(() => location.reload());
            } else {
                Swal.fire('Error', response.message, 'error');
            }
        }, 'json');
    });
    
    // Delete
    $('.delete-app').click(function() {
        const id = $(this).data('id');
        const name = $(this).data('name');
        
        Swal.fire({
            title: 'Delete Application?',
            html: `Delete <strong>${name}</strong>?<br><br>This action cannot be undone!`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $('#deleteId').val(id);
                $('#deleteForm').submit();
            }
        });
    });
</script>

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