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

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

// Get project IDs from session if they exist
$projectFilter = "";
if (isset($_SESSION['selected_projects']) && !empty($_SESSION['selected_projects'])) {
    // Check if the selected_projects is a JSON string and decode it
    $projectIds = is_string($_SESSION['selected_projects']) 
        ? json_decode($_SESSION['selected_projects'], true) 
        : $_SESSION['selected_projects'];
    
    // Make sure we have an array
    if (is_array($projectIds) && !empty($projectIds)) {
        $projectIdsStr = implode(',', array_map('intval', $projectIds));
        $projectFilter = "AND tbl_lead_user_id IN (
            SELECT tbl_lead_user_id 
            FROM tbl_lead_user_projects 
            WHERE tbl_lead_user_prj_id IN ($projectIdsStr)
        )";
    }
}

// Calculate lead counts with project filter
$all_cnt = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM tbl_lead_user WHERE 1 AND tbl_lead_user_flag=0 $projectFilter $cond"));
$all_new = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM tbl_lead_user WHERE 1 AND tbl_lead_user_flag=0 AND tbl_lead_user_status='new' $projectFilter $cond"));
$all_followup = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM tbl_lead_user WHERE 1 AND tbl_lead_user_flag=0 AND tbl_lead_user_status IN('Not Connected','In Progress') $projectFilter $cond"));
$all_sv_sch = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM tbl_lead_user WHERE 1 AND tbl_lead_user_flag=0 AND tbl_lead_user_status IN('SV Scheduled') $projectFilter $cond"));
$all_sv_sc = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM tbl_lead_user WHERE 1 AND tbl_lead_user_flag=0 AND tbl_lead_user_status IN('SV Completed') $projectFilter $cond"));
$all_booking_eoi = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM tbl_lead_user WHERE 1 AND tbl_lead_user_flag=0 AND tbl_lead_user_status IN('EOI Completed','Booking Completed') $projectFilter $cond"));
$all_dead = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM tbl_lead_user WHERE 1 AND tbl_lead_user_flag=0 AND tbl_lead_user_status IN('Dead Lead') $projectFilter $cond"));

// Return the counts as JSON
echo json_encode([
    'all_cnt' => $all_cnt,
    'all_new' => $all_new,
    'all_followup' => $all_followup,
    'all_sv_sch' => $all_sv_sch,
    'all_sv_sc' => $all_sv_sc,
    'all_booking_eoi' => $all_booking_eoi,
    'all_dead' => $all_dead
]);
?> 