<?php
include("dbconnect.php"); // Replace with your DB connection
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$projectFilter = "";
if (isset($_SESSION['selected_projects']) && !empty($_SESSION['selected_projects'])) {
    $projectIds = is_string($_SESSION['selected_projects']) 
        ? json_decode($_SESSION['selected_projects'], true) 
        : $_SESSION['selected_projects'];

    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)
        )";
    }
}

$statusProjectFilter = "";
if (isset($_SESSION['selected_status_projects']) && !empty($_SESSION['selected_status_projects'])) {
    $projectIds = is_string($_SESSION['selected_status_projects']) 
        ? json_decode($_SESSION['selected_status_projects'], true) 
        : $_SESSION['selected_status_projects'];

    if (is_array($projectIds) && !empty($projectIds)) {
        $statusProjectIdsStr = implode(',', array_map('intval', $projectIds));
        $statusProjectFilter = "AND tbl_lead_user_status IN (
            SELECT tbl_followup_status_name 
            FROM tbl_followup_status 
            WHERE tbl_followup_status_id IN ($statusProjectIdsStr)
        )";
    }
}

// Get assigned user IDs from session if they exist
$userFilter = "";
if (isset($_SESSION['assigned_user']) && !empty($_SESSION['assigned_user'])) {
    // Check if the selected_projects is a JSON string and decode it
    $userIds = is_string($_SESSION['assigned_user']) 
        ? json_decode($_SESSION['assigned_user'], true) 
        : $_SESSION['assigned_user'];
    
    // Make sure we have an array
    if (is_array($userIds) && !empty($userIds)) {
        $userIdsStr = implode(',', array_map('intval', $userIds));
        $userFilter = "AND tbl_lead_user_assigned_user_id IN ($userIdsStr)";
    }
}

// Get Date from session if they exist
$dateFilter="";
if (
    (isset($_SESSION['date_option']) && !empty($_SESSION['date_option'])) || 
    (isset($_SESSION['date_start']) && !empty($_SESSION['date_start'])) || 
    (isset($_SESSION['date_end']) && !empty($_SESSION['date_end']))
) {
    // your code here
    if (!empty($_SESSION['date_option'])) {
        $today = date('Y-m-d');
        
        switch ($_SESSION['date_option']) {
            case 'today':
                $dateFilter = " AND DATE(tbl_lead_user_regdate) = '$today'";
                break;
    
            case 'yesterday':
                $yesterday = date('Y-m-d', strtotime('-1 day'));
                $dateFilter = " AND DATE(tbl_lead_user_regdate) = '$yesterday'";
                break;
    
            case 'this_week':
                $startOfWeek = date('Y-m-d', strtotime('monday this week'));
                $endOfWeek = date('Y-m-d', strtotime('sunday this week'));
                $dateFilter = " AND DATE(tbl_lead_user_regdate) BETWEEN '$startOfWeek' AND '$endOfWeek'";
                break;
    
            case 'this_month':
                $startOfMonth = date('Y-m-01');
                $endOfMonth = date('Y-m-t');
                $dateFilter = " AND DATE(tbl_lead_user_regdate) BETWEEN '$startOfMonth' AND '$endOfMonth'";
                break;
        }
    }
    
    if (!empty($_SESSION['date_start']) && !empty($_SESSION['date_end'])) {
        $startDate = $_SESSION['date_start'];
        $endDate = $_SESSION['date_end'];
        
        $dateFilter = " AND DATE(tbl_lead_user_regdate) BETWEEN '$startDate' AND '$endDate'";
    }

}

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

function countQuery($conn, $extraCondition = '') {
    global $projectFilter, $userFilter, $dateFilter, $statusProjectFilter, $cond;
    //$query = "SELECT COUNT(*) as cnt FROM tbl_lead_user WHERE tbl_lead_user_flag=0 $extraCondition $projectFilter $userFilter $dateFilter $cond";
    $query = "SELECT COUNT(*) as cnt 
                FROM tbl_lead_user 
                WHERE tbl_lead_user_flag=0 
                $extraCondition $projectFilter $userFilter $dateFilter $statusProjectFilter  $cond
                AND tbl_lead_user_cdate = (
                    SELECT MAX(t2.tbl_lead_user_cdate)
                    FROM tbl_lead_user t2
                    WHERE t2.tbl_lead_user_mobile = tbl_lead_user.tbl_lead_user_mobile
                      AND t2.tbl_lead_user_flag=0 
                      $extraCondition $cond $projectFilter $userFilter $dateFilter $statusProjectFilter
                )";
    $result = mysqli_query($conn, $query);
    return mysqli_fetch_assoc($result)['cnt'];
}

echo json_encode([
    "all" => countQuery($conn),
    "new" => countQuery($conn, "AND tbl_lead_user_status='new'"),
    "followup" => countQuery($conn, "AND tbl_lead_user_status IN ('Not Connected','In Progress')"),
    "svscheduled" => countQuery($conn, "AND tbl_lead_user_status IN ('SV Scheduled')"),
    "svcompleted" => countQuery($conn, "AND tbl_lead_user_status IN ('SV Completed')"),
    "bookingeoi" => countQuery($conn, "AND tbl_lead_user_status IN ('EOI Completed','Booking Completed')"),
    "dead" => countQuery($conn, "AND tbl_lead_user_status IN ('Dead Lead')")
]);
?>
