<?php
include('dbconnect.php');
include('function.php');

// Get filter parameters
$status = isset($_POST['status']) ? $_POST['status'] : '';
$projectIds = isset($_POST['project_ids']) ? $_POST['project_ids'] : [];

// Base condition for user role
$cond = "";
if($_SESSION['role'] == 'STANDARD'){
    $cond = "AND tbl_lead_user_assigned_user_id = " . $_SESSION['user_id'] . " ";
}

// Build the SQL query based on status and project IDs
$sql = "SELECT DISTINCT l.* FROM tbl_lead_user l 
        LEFT JOIN tbl_lead_user_projects p ON l.tbl_lead_user_id = p.tbl_lead_user_id 
        WHERE 1=1 $cond";

// Add status condition if provided
if (!empty($status)) {
    $sql .= " AND l.tbl_lead_user_status = '$status'";
}

// Add project filter if projects are selected
if (!empty($projectIds) && is_array($projectIds)) {
    $projectIdsStr = implode(',', array_map('intval', $projectIds));
    $sql .= " AND p.tbl_lead_user_prj_id IN ($projectIdsStr)";
}

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

$result = $conn->query($sql);
$data = [];

if ($result->num_rows > 0) {
    // Fetch the data and store it in an array
    $sl = 1;
    $source = 'Facebook Ads';
    $status = '';
    $intent = '';
    $svUser = '-';
    $markedBy = 'Varun';
    $leasAccessbility = '-';
    $access = '-';
    $lastNote = '-';
    $actions = '';
    
    while ($row = $result->fetch_assoc()) {
        $sql_profile = "SELECT * FROM tbl_lead_user_profile WHERE tbl_lead_user_profile_flag = 0 AND tbl_lead_user_profile_id = '".$row['tbl_lead_user_profile_id']."'";
        $rprofile = $conn->query($sql_profile);

        // Fetch the profile data
        if ($rprofile && $profile = $rprofile->fetch_assoc()) {
            $project_name = get_project_name($row['tbl_lead_user_id']);
            $source_name = get_source_name($row['tbl_lead_user_source_id']);
            $city_name = get_city_name($row['tbl_lead_user_city_id']);
            $as_u_name = get_assigned_user_name($row['tbl_lead_user_assigned_user_id']);
            $data[] = [
                $sl,
                $profile['tbl_lead_user_profile_name'],
                $profile['tbl_lead_user_profile_mobile'],
                $profile['tbl_lead_user_profile_cdate'],
                $project_name,
                $row['tbl_lead_user_status'],
                $row['tbl_lead_user_intent'],
                $source_name,
                $city_name,
                $as_u_name,
                $row['tbl_lead_user_cdate'],
                $svUser,
                $markedBy,
                $row['tbl_lead_user_cdate'],
                $leasAccessbility,
                $access,
                $lastNote,
                $row['tbl_lead_user_id'],
            ];
            $sl++;
        }
    }
}

// Close the database connection
$conn->close();

// Return the data as JSON
echo json_encode($data);
?> 