<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$interest_type = $_GET['interest_type'] ?? '';

$sql = "SELECT l.*, u.first_name as agent_first_name, u.last_name as agent_last_name,
               p.name as property_name
        FROM leads l
        LEFT JOIN users u ON l.assigned_agent_id = u.id
        LEFT JOIN properties p ON l.property_interested_in = p.id
        WHERE 1=1";

$params = [];
$types = '';

if (!empty($search)) {
    $sql .= " AND (l.first_name LIKE ? OR l.last_name LIKE ? OR l.email LIKE ? OR l.phone LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ssss';
}

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

if (!empty($interest_type)) {
    $sql .= " AND l.interest_type = ?";
    $params[] = $interest_type;
    $types .= 's';
}

$sql .= " ORDER BY l.created_at DESC";

if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Leads / Buyers')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'CRM', 'title' => 'Leads / Buyers')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by name, email, or phone">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="New" <?php echo $status_filter == 'New' ? 'selected' : ''; ?>>New</option>
                                                <option value="Contacted" <?php echo $status_filter == 'Contacted' ? 'selected' : ''; ?>>Contacted</option>
                                                <option value="Viewing Scheduled" <?php echo $status_filter == 'Viewing Scheduled' ? 'selected' : ''; ?>>Viewing Scheduled</option>
                                                <option value="Offer Made" <?php echo $status_filter == 'Offer Made' ? 'selected' : ''; ?>>Offer Made</option>
                                                <option value="Converted" <?php echo $status_filter == 'Converted' ? 'selected' : ''; ?>>Converted</option>
                                                <option value="Lost" <?php echo $status_filter == 'Lost' ? 'selected' : ''; ?>>Lost</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Interest Type</label>
                                            <select class="form-select" name="interest_type">
                                                <option value="">All Types</option>
                                                <option value="Rent" <?php echo $interest_type == 'Rent' ? 'selected' : ''; ?>>Rent</option>
                                                <option value="Buy" <?php echo $interest_type == 'Buy' ? 'selected' : ''; ?>>Buy</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="ri-search-line me-1"></i>Filter
                                                </button>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <a href="add_lead.php" class="btn btn-success w-100">
                                                    <i class="ri-add-line me-1"></i>Add Lead
                                                </a>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">All Leads</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Name</th>
                                                    <th>Contact</th>
                                                    <th>Interest</th>
                                                    <th>Budget</th>
                                                    <th>Property</th>
                                                    <th>Assigned Agent</th>
                                                    <th>Status</th>
                                                    <th>Source</th>
                                                    <th>Created</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($lead = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($lead['first_name'] . ' ' . $lead['last_name']); ?>
                                                                    </h5>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <p class="mb-0"><?php echo htmlspecialchars($lead['email'] ?? 'N/A'); ?></p>
                                                                    <small class="text-muted"><?php echo htmlspecialchars($lead['phone'] ?? 'N/A'); ?></small>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($lead['interest_type'] ?? 'N/A'); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if ($lead['budget_min'] || $lead['budget_max']): ?>
                                                                    KES <?php echo number_format($lead['budget_min'] ?? 0, 0); ?> - 
                                                                    KES <?php echo number_format($lead['budget_max'] ?? 0, 0); ?>
                                                                <?php else: ?>
                                                                    N/A
                                                                <?php endif; ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($lead['property_name'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <?php if ($lead['agent_first_name']): ?>
                                                                    <?php echo htmlspecialchars($lead['agent_first_name'] . ' ' . $lead['agent_last_name']); ?>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Unassigned</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_colors = [
                                                                    'New' => 'info',
                                                                    'Contacted' => 'primary',
                                                                    'Viewing Scheduled' => 'warning',
                                                                    'Offer Made' => 'success',
                                                                    'Converted' => 'success',
                                                                    'Lost' => 'danger'
                                                                ];
                                                                $color = $status_colors[$lead['status']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $color; ?> text-<?php echo $color; ?>">
                                                                    <?php echo htmlspecialchars($lead['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-secondary text-secondary">
                                                                    <?php echo htmlspecialchars($lead['source'] ?? 'N/A'); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo date('M d, Y', strtotime($lead['created_at'])); ?></td>
                                                            <td>
                                                                <a href="lead_details.php?id=<?php echo $lead['id']; ?>" 
                                                                   class="btn btn-soft-secondary btn-sm">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="10" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No leads found</p>
                                                                <a href="add_lead.php" class="btn btn-primary btn-sm mt-2">
                                                                    <i class="ri-add-line me-1"></i>Add First Lead
                                                                </a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
