<?php
App::uses('Model', 'Model');

/**
 * Application model for Report.
 *
 * Add your report-wide methods in the class below, your models
 * @package       app.Model
 */

class Report extends AppModel {
    public $useTable = false;

    /**
     * activeUsers
     * @params : array
     * return array
     */
    public function activeUsers($params){
        //pr($params);
        $reportArr = array();
        $date = $params['date'];
        switch($params['type']){
            case 'daily':
                $oC = "o.order_date = '$date'";
                $rdC = "rs.sale_date = '$date'";
                $conrdC = "rs.order_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));

                $oC = "o.order_date between '$d1' AND '$d2'";
                $rdC = "rs.sale_date between '$d1' AND '$d2'";
                $conrdC = "rs.order_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;

            case 'between':
                $d1 = $params['query']['from'];
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }

                $oC = "o.order_date between '$d1' AND '$d2'";
                $rdC = "rs.sale_date between '$d1' AND '$d2'";
                $conrdC = "rs.order_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $oC = "o.order_date between '$d1' AND '$d2'";
                $rdC = "rs.sale_date between '$d1' AND '$d2'";
                $conrdC = "rs.order_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
        }
        $dvC = $rgC = $dpC = "";
        if (!empty($params['query']['dv'])){
            $dvC = " AND u.division_id = ".$params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND u.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND u.depot_id = ".$params['query']['dp'];
        }

        $result = array();
        $orderEntry = $this->query("SELECT count(u.id) as oentry, o.user_id, u.first_name, u.last_name FROM orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC GROUP BY u.id");

        $consorderEntry = $this->query("SELECT count(u.id) as oentry, o.user_id, u.first_name, u.last_name FROM consumer_orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC GROUP BY u.id");

        $rSaleEntry = $this->query("SELECT count(u.id) as rsentry, rs.user_id, u.first_name, u.last_name FROM redistributor_sales rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC GROUP BY u.id");

        $consrSaleEntry = $this->query("SELECT count(u.id) as rsentry, rs.user_id, u.first_name, u.last_name FROM consumer_redistribution_orders rs INNER JOIN users u ON u.id = rs.user_id WHERE $conrdC $dvC $rgC $dpC GROUP BY u.id");

        //$visitEntry = $this->query("SELECT count(u.id) as ventry, cv.user_id, u.first_name, u.last_name FROM customer_visits cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC GROUP BY u.id");
        if(!empty($params['cvisityear_tables'])) {
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName) {
                $visitEntries[$year] = $this->query("SELECT count(u.id) as ventry, cv.user_id, u.first_name, u.last_name FROM $cv_tableName cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC GROUP BY u.id");
            }
        }

        if ($orderEntry){
            foreach ($orderEntry as $oe){
                $uid = $oe['o']['user_id'];
                $result[$uid]['orderEntry'] = $oe;
                $result[$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
            }
        }

        if ($consorderEntry){
            foreach ($consorderEntry as $oe){
                $uid = $oe['o']['user_id'];
                $result[$uid]['consorderEntry'] = $oe;
                $result[$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
            }
        }

        if ($rSaleEntry){
            foreach ($rSaleEntry as $rse){
                $uid = $rse['rs']['user_id'];
                $result[$uid]['rsEntry'] = $rse;
                $result[$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
            }
        }

        if ($consrSaleEntry){
            foreach ($consrSaleEntry as $rse){
                $uid = $rse['rs']['user_id'];
                $result[$uid]['consrsEntry'] = $rse;
                $result[$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
            }
        }

        /*if ($visitEntry){
            foreach ($visitEntry as $cve){
                $uid = $cve['cv']['user_id'];
                $result[$uid]['visitEntry'] = $cve;
                $result[$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
            }
        } */

        if (!empty($visitEntries)) {
            foreach ($visitEntries as $year => $visitEntry) {
                foreach ($visitEntry as $cve) {
                    $uid = $cve['cv']['user_id'];
                    $result[$uid]['visitEntry'] = $cve;
                    $result[$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                }
            }
        }

        return $result;

    }


    /**
     * activeUsers
     * @params : array
     * return array
     */
    public function nonactiveUsers($params){
        //pr($params);
        $reportArr = array();
        $date = $params['date'];
        switch($params['type']){
            case 'daily':
                $oC = "AND o.order_date = '$date'";
                $rdC = "AND rs.sale_date = '$date'";
                $cvC = "AND cv.visiting_date LIKE '".$date."%'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));

                $oC = "AND o.order_date between '$d1' AND '$d2'";
                $rdC = "AND rs.sale_date between '$d1' AND '$d2'";
                $cvC = "AND cv.visiting_date between '$d1' AND '$d2 23:59:59'";

                break;

            case 'between':
                $d1 = $params['query']['from'];
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $oC = "AND o.order_date between '$d1' AND '$d2'";
                $rdC = "AND rs.sale_date between '$d1' AND '$d2'";
                $cvC = "AND cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;

            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $oC = "AND o.order_date between '$d1' AND '$d2'";
                $rdC = "AND rs.sale_date between '$d1' AND '$d2'";
                $cvC = "AND cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
        }
        $dvC = $rgC = $dpC = "";
        if (!empty($params['query']['dv'])){
            $dvC = " AND u.division_id = ".$params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND u.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND u.depot_id = ".$params['query']['dp'];
        }
		
		//Get Roles
		$Role=  ClassRegistry::init('Role');
        $reportRoles = $Role->find('list', array('fields' => array('id', 'name'), 'conditions' => array('Role.grade >' => 3), 'order' => array('Role.grade' => 'asc', 'Role.name' => 'asc')));
				

        $result = array();
        /*$result = $this->query("SELECT u.id, u.first_name, u.last_name, r.name, rg.title, d.title
		FROM users u INNER JOIN roles r ON r.id = u.role_id INNER JOIN regions rg ON rg.id = u.region_id 
		INNER JOIN depots d ON d.id = u.depot_id
		LEFT JOIN orders o ON o.user_id = u.id $oC
		LEFT JOIN redistributor_sales rs ON rs.user_id = u.id $rdC
		LEFT JOIN customer_visits cv ON cv.user_id = u.id $cvC		
		WHERE u.status= ".ACTIVE." AND r.grade > 3 AND o.id IS NULL 
		AND cv.id IS NULL 
		AND rs.id IS NULL $dvC $rgC $dpC GROUP BY u.id"); */

        if(!empty($params['cvisityear_tables'])) {
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName) {				
                /* $results[$year] = $this->query("SELECT u.id, u.first_name, u.last_name, r.name, rg.title, d.title
                    FROM users u INNER JOIN roles r ON r.id = u.role_id INNER JOIN regions rg ON rg.id = u.region_id 
                    INNER JOIN depots d ON d.id = u.depot_id
                    LEFT JOIN orders o ON o.user_id = u.id $oC
                    LEFT JOIN redistributor_sales rs ON rs.user_id = u.id $rdC
                    LEFT JOIN $cv_tableName cv ON cv.user_id = u.id $cvC		
                    WHERE u.status= ".ACTIVE." AND r.grade > 3 AND o.id IS NULL 
                    AND cv.id IS NULL 
                    AND rs.id IS NULL $dvC $rgC $dpC GROUP BY u.id"); */
					//Updated on : 2025-04-03
					$results[$year] = $this->query("SELECT u.id, u.first_name, u.last_name, r.name, rg.title, d.title FROM users u INNER JOIN roles r ON r.id = u.role_id INNER JOIN regions rg ON rg.id = u.region_id INNER JOIN depots d ON d.id = u.depot_id WHERE u.status= ".ACTIVE." AND r.grade > 3 AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id $oC) AND NOT EXISTS (SELECT 1 FROM redistributor_sales rs WHERE rs.user_id = u.id $rdC) AND NOT EXISTS (SELECT 1 FROM $cv_tableName cv WHERE cv.user_id = u.id $cvC) $rgC $dpC");
			}
        }

        if (!empty($results)) {
            foreach ($results as $year => $resulti) {
                $result += $resulti;
            }
        }

        return array(
			'result' => $result,
			'reportRoles' => $reportRoles
		);

    }

    /* function callReports($params){
        $output = array();
        $date = $params['date'];
        //pr($params);
        switch($params['type']){
            case 'daily':
                $oC = "sl.sale_date = '$date'";
                $rdC = "rsi.sale_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
                break;
            case 'between':

                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }

                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                $ccC = "c.created between '$d1' AND '$d2 23:59:59'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                $ccC = "c.created between '$d1' AND '$d2 23:59:59'";
                break;
        }
       
        if(!empty($params['query']['t-month'])){
            $d1Arrar['1'] = $params['query']['t-month'];
        }else{
            $d1Arrar = explode("-", $d1); //pr($d1Arrar);
        }


        $userDVC = $cdvC = $cvdvC = $dv_regC = $userDC = $userRC = $rgC = $dpC = $crgC = $cdpC = $cvrgC = $cvdpC ="";
        if (!empty($params['query']['dv'])){
            if (empty($params['query']['rg']) && empty($params['query']['dp'])) {
                $divisionRegion=  ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields'=>array('region_id'),'conditions'=>array('division_id'=>$params['query']['dv'])));
                $rIds = implode(",",$rIds); //pr($rIds);exit;
                $dv_regC = " AND d.region_id IN ( ".$rIds.") ";
            }
            $cvdvC = " AND us.division_id = ".$params['query']['dv'];
            $cdvC = " AND c.division_id = ".$params['query']['dv'];
            $userDVC = " AND u.division_id = ".$params['query']['dv'];

        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND d.region_id = ".$params['query']['rg'];
            $cvrgC = " AND us.region_id = ".$params['query']['rg'];
            $crgC = " AND c.region_id = ".$params['query']['rg'];
            $userRC = " AND u.region_id = ".$params['query']['rg'];

        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND d.id = ".$params['query']['dp'];
            $cvdpC = " AND us.depot_id = ".$params['query']['dp'];
            $cdpC = " AND c.depot_id = ".$params['query']['dp'];
            $userDC = " AND u.depot_id = ".$params['query']['dp'];
        }


        $result = array();

        $orderEntry = $this->query("SELECT count(DISTINCT sl.order_id) as oentry, sl.user_id, sl.depot_id, d.title, d.region_id FROM sales sl INNER JOIN depots d ON d.id = sl.depot_id WHERE $oC $dv_regC $rgC $dpC GROUP BY sl.depot_id, sl.user_id"); //pr($orderEntry);

        $consorderEntry = $this->query("SELECT count(DISTINCT sl.consumer_order_id) as oentry, sl.user_id, sl.depot_id, d.title, d.region_id FROM consumer_sales sl INNER JOIN depots d ON d.id = sl.depot_id WHERE $oC $dv_regC $rgC $dpC GROUP BY sl.depot_id, sl.user_id"); //pr($orderEntry);

        $rSaleEntry = $this->query("SELECT count(DISTINCT rsi.redistributor_sale_id) as rsentry, rsi.user_id, rsi.depot_id, d.title, d.region_id FROM redistributor_saleitems rsi INNER JOIN depots d ON d.id = rsi.depot_id WHERE $rdC $dv_regC $rgC $dpC GROUP BY rsi.depot_id, rsi.user_id");

        $rConsSaleEntry = $this->query("SELECT count(DISTINCT rsi.consumer_redistribution_order_id) as rsentry, rsi.user_id, rsi.depot_id, d.title, d.region_id FROM consumer_redistribution_sales rsi INNER JOIN depots d ON d.id = rsi.depot_id WHERE $rdC $dv_regC $rgC $dpC GROUP BY rsi.depot_id, rsi.user_id");

        //$visitEntry = $this->query("SELECT count(cv.user_id) as ventry, cv.user_id, cv.depot_id, us.depot_id, us.region_id FROM customer_visits cv INNER JOIN users us ON us.id = cv.user_id WHERE $cvC $cvdvC $cvrgC $cvdpC GROUP BY us.depot_id, cv.user_id");
		
		$excludeVisitRoles = [ADMINISTRATOR, HMS, SUPPORTTEAM1, SUPPORTTEAM2, PROMO, DIVISIONMANAGER, RM];
        if(!empty($params['cvisityear_tables'])) {
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName) {
                $visitEntries[$year] = $this->query("SELECT count(cv.user_id) as ventry, cv.user_id, cv.depot_id, us.depot_id, us.region_id FROM $cv_tableName cv INNER JOIN users us ON us.id = cv.user_id WHERE $cvC $cvdvC $cvrgC $cvdpC AND us.role_id NOT IN (".implode(', ', $excludeVisitRoles).") GROUP BY us.depot_id, cv.user_id");
            }
        }
        //pr($visitEntry);

        if ($orderEntry){
            foreach ($orderEntry as $oe){
                //$uid = $oe['sl']['user_id'];
				$uid = !empty($oe['sl']['user_id']) ? $oe['sl']['user_id'] : 0 ;
                //$did = $oe['sl']['depot_id'];
                $did = !empty($oe['sl']['depot_id']) ? $oe['sl']['depot_id'] : 0;
				//$rid = $oe['d']['region_id'];
                $rid = !empty($oe['d']['region_id']) ? $oe['d']['region_id'] : 0;
                $result[$rid][$did][$uid]['orderEntry'] = $oe;
                //$result[$rid][$did][$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
                $result[$rid][$did][$uid]['saleEntry'] = $oe['0']['oentry'];
                //$result[$rid][$did][$uid]['dname'] = $oe['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $oe['u']['role_id'];
            }
        }

        if ($consorderEntry){
            foreach ($consorderEntry as $oe){
                $uid = $oe['sl']['user_id'];
                //$did = $oe['sl']['depot_id'];
                $did = !empty($oe['sl']['depot_id']) ? $oe['sl']['depot_id'] : 0;
                //$rid = $oe['d']['region_id'];
                $rid = !empty($oe['d']['region_id']) ? $oe['d']['region_id'] : 0;
                $result[$rid][$did][$uid]['consorderEntry'] = $oe;
                //$result[$rid][$did][$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
                $result[$rid][$did][$uid]['conssaleEntry'] = $oe['0']['oentry'];
                //$result[$rid][$did][$uid]['dname'] = $oe['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $oe['u']['role_id'];
            }
        }

        if ($rSaleEntry){
            foreach ($rSaleEntry as $rse){
                $uid = $rse['rsi']['user_id'];
                //$did = $rse['rsi']['depot_id'];
                $did = !empty($rse['rsi']['depot_id']) ? $rse['rsi']['depot_id'] : 0;
                //$rid = $rse['d']['region_id'];
                $rid = !empty($rse['d']['region_id']) ? $rse['d']['region_id'] : 0;
                $result[$rid][$did][$uid]['rsEntry'] = $rse;
                //$result[$rid][$did][$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
                $result[$rid][$did][$uid]['rsSaleEntry'] = $rse['0']['rsentry'];
                //$result[$rid][$did][$uid]['dname'] = $rse['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $rse['u']['role_id'];
            }
        }

        if ($rConsSaleEntry){
            foreach ($rConsSaleEntry as $rse){
                $uid = $rse['rsi']['user_id'];
                //$did = $rse['rsi']['depot_id'];
                $did = !empty($rse['rsi']['depot_id']) ? $rse['rsi']['depot_id'] : 0;
                //$rid = $rse['d']['region_id'];
                $rid = !empty($rse['d']['region_id']) ? $rse['d']['region_id'] : 0;
                $result[$rid][$did][$uid]['crsEntry'] = $rse;
                //$result[$rid][$did][$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
                $result[$rid][$did][$uid]['crsSaleEntry'] = $rse['0']['rsentry'];
                //$result[$rid][$did][$uid]['dname'] = $rse['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $rse['u']['role_id'];
            }
        }

        // if ($visitEntry){
            // foreach ($visitEntry as $cve){
                // $uid = $cve['cv']['user_id'];
                //$did = ($cve['us']['depot_id'])?$cve['us']['depot_id']:0;
                // $did = !empty($cve['us']['depot_id'])?$cve['us']['depot_id']:0;
                //$rid = $cve['us']['region_id'];
                // $rid =  !empty($cve['us']['region_id'])? $cve['us']['region_id'] : 0;
                // $result[$rid][$did][$uid]['visitEntry'] = $cve;
                //$result[$rid][$did][$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                // $result[$rid][$did][$uid]['ventry'] = $cve['0']['ventry'];
                //$result[$rid][$did][$uid]['dname'] = $cve['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $cve['u']['role_id'];
            // }
        // }

        if (!empty($visitEntries)) {
            foreach ($visitEntries as $year => $visitEntry) {
                foreach ($visitEntry as $cve){
                    $uid = $cve['cv']['user_id'];
                    //$did = ($cve['us']['depot_id'])?$cve['us']['depot_id']:0;
                    $did = !empty($cve['us']['depot_id'])?$cve['us']['depot_id']:0;
                    //$rid = $cve['us']['region_id'];
                    $rid =  !empty($cve['us']['region_id'])? $cve['us']['region_id'] : 0;
                    $result[$rid][$did][$uid]['visitEntry'] = $cve;
                    //$result[$rid][$did][$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                    $result[$rid][$did][$uid]['ventry'] = $cve['0']['ventry'];
                    //$result[$rid][$did][$uid]['dname'] = $cve['d']['title'];
                    //$result[$rid][$did][$uid]['role_id'] = $cve['u']['role_id'];
                }

            }
        }

        //Count customers created
        //$customerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM customers c WHERE 1 $cdvC $crgC $cdpC GROUP BY c.user_id");
		$customerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM customers c WHERE 1 $cdvC $crgC $cdpC AND c.status = ".ACTIVE." GROUP BY c.user_id");

        if ($customerEntry){
            foreach ($customerEntry as $cve){
                $uid = $cve['c']['user_id'];
                //$did = $cve['c']['depot_id'];
                //$rid = $cve['c']['region_id'];
                $result['cCreated'][$uid] = $cve;
                //$result[$rid][$did][$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                $result['totalCustomer'][$uid] = $cve['0']['cCreated'];
                //$result[$rid][$did][$uid]['dname'] = $cve['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $cve['u']['role_id'];
            }
        }

        //Count consumers created
        $consumerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM consumers c WHERE 1 $cdvC $crgC $cdpC GROUP BY c.user_id");

        if ($consumerEntry){
            foreach ($consumerEntry as $cve){
                $uid = $cve['c']['user_id'];
                //$did = $cve['c']['depot_id'];
                //$rid = $cve['c']['region_id'];
                $result['conCreated'][$uid] = $cve;
                //$result[$rid][$did][$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                $result['totalConsumer'][$uid] = $cve['0']['cCreated'];
                //$result[$rid][$did][$uid]['dname'] = $cve['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $cve['u']['role_id'];
            }
        }

        //$output['totalCalls'] = $totalCalls;
        $output['result'] = $result;
        //Get roles
        // $roles = array();
        // $roleData = $this->query("SELECT id, name FROM roles AS Role");
        // foreach($roleData as $role){
            // $id = $role['Role']['id'];
            // $roles[$id] = $role['Role']['name'];
        // }
        // $output['roles'] = $roles;

        //Get All users 
        $users = array();
        //$usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE r.grade > 2 AND u.status = ".ACTIVE."  $userDVC $userDC $userRC ORDER BY rg.title ASC, u.role_id ASC");
		$excludedRoles = [ADMINISTRATOR, HMS, SUPPORTTEAM1, SUPPORTTEAM2, PROMO];
        $usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE  r.id NOT IN(".implode(', ', $excludedRoles).") AND u.status = ".ACTIVE."  $userDVC $userDC $userRC ORDER BY rg.title ASC, u.role_id ASC");
        foreach($usersData as $user){

            $rid = ($user['u']['region_id'])?$user['u']['region_id']:0;
            $did = ($user['u']['depot_id'])?$user['u']['depot_id']:0;

            $uid = $user['u']['id'];
            $users[$rid][$did][$uid] = array('name'=> $user['u']['first_name'].' '.$user['u']['last_name'], 'rid'=>$user['u']['role_id'], 'role'=>$user['r']['name'], 'depot'=>$user['d']['title']);
        }
        $output['users'] = $users;
        //pr($users);
		
		 
		
        //find monthly Targets
        $targets = array();
        $targetQry = $this->query("SELECT user_id, depot_id, target FROM user_targets AS Target WHERE type='Call'");
        //pr($targetQry);
        if($targetQry){
            foreach($targetQry as $target){
                $user_id = $target['Target']['user_id'];
                $depot_id = $target['Target']['depot_id'];
                $userTargets = @unserialize($target['Target']['target']);
                $targets[$user_id] = !empty($userTargets[$d1Arrar['1']])?$userTargets[$d1Arrar['1']]:0;
				
				
            }
        }
        $output['targets'] = $targets; //pr($output['targets']);
        return $output;
    } */
	
	function callReports($params){
        $output = array();
        //$date = $params['date'];
        //pr($params);
        $dateParams = $params['dateParams'];

        switch($params['type']){
            case 'daily':
                $date = $dateParams['date'];
                $oC = "sl.sale_date = '$date'";
                $rdC = "rsi.sale_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
                break;
            default:
				$d1 = $dateParams['from'];
				$d2 = $dateParams['to'];
				
				$oC = "sl.sale_date between '$d1' AND '$d2'";
				$rdC = "rsi.sale_date between '$d1' AND '$d2'";
				$cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";				
				$ccC = "c.created between '$d1' AND '$d2 23:59:59'";					
        }
        
        /* $d1Arrar = explode("-", $d1); */
        /*if(!empty($params['query']['t-month'])){
            $d1Arrar['1'] = $params['query']['t-month'];
        }else{
            $d1Arrar = explode("-", $d1); //pr($d1Arrar);
        }*/
        
        if(!empty($params['query']['t-month'])){
			$monthValue = $params['query']['t-month'];
		}else{
			$monthValue = isset($dateParams['month']) && strlen($dateParams['month']) === 1 
    		? '0' . $dateParams['month'] : $dateParams['month'];
		}


        $userDVC = $userRC = $userDC = "";
        if (!empty($params['query']['dv'])){
            $userDVC = " AND u.division_id = ".$params['query']['dv'];
		}
        if (!empty($params['query']['rg'])){
            $userRC = " AND u.region_id = ".$params['query']['rg'];

        }
        if (!empty($params['query']['dp'])){
            $userDC = " AND u.depot_id = ".$params['query']['dp'];
        }


        $result = array();
		
		//Get All users 
        $users = $user_ids = array();
		//[ADMINISTRATOR, HMS, SUPPORTTEAM1, SUPPORTTEAM2, PROMO]
		$excludedRoles = getExcludedUserRolesForVisit();
        $usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, u.status, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE  r.id NOT IN(".implode(', ', $excludedRoles).") $userDVC $userDC $userRC ORDER BY rg.title ASC, u.role_id ASC");
        foreach($usersData as $user){

            $rid = ($user['u']['region_id'])?$user['u']['region_id']:0;
            $did = ($user['u']['depot_id'])?$user['u']['depot_id']:0;

            $uid = $user['u']['id'];
            $users[$rid][$did][$uid] = array('name'=> $user['u']['first_name'].' '.$user['u']['last_name'], 'rid'=>$user['u']['role_id'], 'role'=>$user['r']['name'], 'depot'=>$user['d']['title'], 'status'=>$user['u']['status']);
			if (!in_array($uid, $user_ids)){
				array_push($user_ids, $uid);
			}
			
        }
        $output['users'] = $users;

        $orderEntry = $this->query("SELECT COUNT(DISTINCT CONCAT(sl.customer_id, '-', sl.sale_date)) as oentry, sl.user_id, sl.depot_id FROM sales sl WHERE $oC AND sl.user_id IN (".implode(', ', $user_ids).") GROUP BY sl.user_id"); //pr($orderEntry); 

        $consorderEntry = $this->query("SELECT COUNT(DISTINCT CONCAT(sl.consumer_id, '-', sl.sale_date)) as oentry, sl.user_id, sl.depot_id FROM consumer_sales sl WHERE $oC AND sl.user_id IN (".implode(', ', $user_ids).") GROUP BY sl.user_id"); //pr(consorderEntry);

        $rSaleEntry = $this->query("SELECT COUNT(DISTINCT CONCAT(rsi.customer_id, '-', rsi.sale_date)) as rsentry, rsi.user_id, rsi.depot_id FROM redistributor_saleitems rsi WHERE $rdC AND rsi.user_id IN (".implode(', ', $user_ids).") GROUP BY rsi.user_id"); //pr($rSaleEntry); 

        $rConsSaleEntry = $this->query("SELECT COUNT(DISTINCT CONCAT(rsi.consumer_id, '-', rsi.sale_date)) as rsentry, rsi.user_id, rsi.depot_id FROM consumer_redistribution_sales rsi WHERE $rdC AND rsi.user_id IN (".implode(', ', $user_ids).") GROUP BY rsi.user_id");

        //$visitEntry = $this->query("SELECT count(cv.user_id) as ventry, cv.user_id, cv.depot_id, us.depot_id, us.region_id FROM customer_visits cv INNER JOIN users us ON us.id = cv.user_id WHERE $cvC $cvdvC $cvrgC $cvdpC GROUP BY us.depot_id, cv.user_id");
	
        if(!empty($params['cvisityear_tables'])) {
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName) {
                $visitEntries[$year] = $this->query("SELECT COUNT(DISTINCT CONCAT(cv.customer_id, '-', date(cv.visiting_date))) as ventry, cv.user_id, cv.depot_id FROM $cv_tableName cv WHERE $cvC AND cv.user_id IN (".implode(', ', $user_ids).") GROUP BY cv.user_id");
            }
        }
        //pr($visitEntries); 

        if ($orderEntry){
            foreach ($orderEntry as $oe){
                $uid = !empty($oe['sl']['user_id']) ? $oe['sl']['user_id'] : 0 ;
                $did = !empty($oe['sl']['depot_id']) ? $oe['sl']['depot_id'] : 0;
                $result[$uid]['call']['saleEntry'] = $oe['0']['oentry'];
            }
        }

        if ($consorderEntry){
            foreach ($consorderEntry as $oe){
                $uid = !empty($oe['sl']['user_id']) ? $oe['sl']['user_id'] : 0 ;
                $did = !empty($oe['sl']['depot_id']) ? $oe['sl']['depot_id'] : 0;
                $result[$uid]['call']['conssaleEntry'] = $oe['0']['oentry'];
            }
        }

        if ($rSaleEntry){
            foreach ($rSaleEntry as $rse){
                $uid = !empty($rse['rsi']['user_id']) ? $rse['rsi']['user_id'] : 0 ;
                $did = !empty($rse['rsi']['depot_id']) ? $rse['rsi']['depot_id'] : 0;
                $result[$uid]['call']['rsSaleEntry'] = $rse['0']['rsentry'];
            }
        }

        if ($rConsSaleEntry){
            foreach ($rConsSaleEntry as $rse){
                $uid = !empty($rse['rsi']['user_id']) ? $rse['rsi']['user_id'] : 0 ;
                $did = !empty($rse['rsi']['depot_id']) ? $rse['rsi']['depot_id'] : 0;
                $result[$uid]['call']['crsSaleEntry'] = $rse['0']['rsentry'];
            }
        }

        /*if ($visitEntry){
            foreach ($visitEntry as $cve){
                $uid = $cve['cv']['user_id'];
                //$did = ($cve['us']['depot_id'])?$cve['us']['depot_id']:0;
                $did = !empty($cve['us']['depot_id'])?$cve['us']['depot_id']:0;
                //$rid = $cve['us']['region_id'];
                $rid =  !empty($cve['us']['region_id'])? $cve['us']['region_id'] : 0;
                $result[$rid][$did][$uid]['visitEntry'] = $cve;
                //$result[$rid][$did][$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                $result[$rid][$did][$uid]['ventry'] = $cve['0']['ventry'];
                //$result[$rid][$did][$uid]['dname'] = $cve['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $cve['u']['role_id'];
            }
        } */

        if (!empty($visitEntries)) {
            foreach ($visitEntries as $year => $visitEntry) {
                foreach ($visitEntry as $cve){
                    $uid = !empty($cve['cv']['user_id']) ? $cve['cv']['user_id'] : 0 ;
                    $did = !empty($cve['cv']['depot_id'])?$cve['cv']['depot_id']:0;
					if(empty($result[$uid]['call']['ventry'])){
						 $result[$uid]['call']['ventry'] = $cve['0']['ventry'];
					}else{
						$result[$uid]['call']['ventry'] += $cve['0']['ventry'];
					}
                    
                }

            }
        }

        //Count customers created
        //$customerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM customers c WHERE 1 $cdvC $crgC $cdpC GROUP BY c.user_id");
		$customerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM customers c WHERE c.status = ".ACTIVE." AND c.user_id IN (".implode(', ', $user_ids).") GROUP BY c.user_id");

        if ($customerEntry){
            foreach ($customerEntry as $cve){
				$uid = !empty($cve['c']['user_id']) ? $cve['c']['user_id'] : 0 ;
                $result[$uid]['totalCustomer'] = $cve['0']['cCreated'];
            }
        }

        //Count consumers created
        $consumerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM consumers c WHERE 1 AND c.user_id IN (".implode(', ', $user_ids).") GROUP BY c.user_id");

        if ($consumerEntry){
            foreach ($consumerEntry as $cve){
                $uid = !empty($cve['c']['user_id']) ? $cve['c']['user_id'] : 0 ;
                $result[$uid]['totalConsumer'] = $cve['0']['cCreated'];
            }
        }

        //$output['totalCalls'] = $totalCalls;
        $output['result'] = $result;
        //Get roles
        /*$roles = array();
        $roleData = $this->query("SELECT id, name FROM roles AS Role");
        foreach($roleData as $role){
            $id = $role['Role']['id'];
            $roles[$id] = $role['Role']['name'];
        }
        $output['roles'] = $roles;*/

        
		
		//Get month names between two dates ($d1 and $d2)
		/* $months =array();
		$time   = strtotime($d1);
		$last   = date('M-Y', strtotime($d2));
		do {
			$month = date('M-Y', $time);
			$total = date('t', $time);
			
			if(!in_array(date('m', $time), $months)){
				$months[]=date('m', $time);
			}

			$time = strtotime('+1 month', $time);
		} while ($month != $last);  */ 
		
        //find monthly Targets
        $targets = array();
        $targetQry = $this->query("SELECT user_id, depot_id, target FROM user_targets AS Target WHERE type='Call'");
        //pr($targetQry);
        if($targetQry){
            foreach($targetQry as $target){
                $user_id = $target['Target']['user_id'];
                $depot_id = $target['Target']['depot_id'];
                $userTargets = @unserialize($target['Target']['target']);
                //$targets[$user_id] = !empty($userTargets[$d1Arrar['1']])?$userTargets[$d1Arrar['1']]:0;
                $targets[$user_id] = !empty($userTargets[$monthValue])?$userTargets[$monthValue]:0;
				
				
            }
        }
        $output['targets'] = $targets; //pr($output['targets']);
        return $output;
    }

    function effectiveCallReports($params){
        $output = array();
        //$date = $params['date'];
        $dateParams = $params['dateParams'];

        switch($params['type']){
            case 'daily':
                $date = $dateParams['date'];
                $oC = "sl.sale_date = '$date'";
                $rdC = "rsi.sale_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
				//$ccC = "c.created LIKE '$date%'";
				$ccC = "c.created <= '$date 23:59:59'";
                break;
                
                default:
				$d1 = $dateParams['from'];
				$d2 = $dateParams['to'];
				
                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
				//$ccC = "c.created between '$d1' AND '$d2 23:59:59'";
				$ccC = "c.created <= '$d2 23:59:59'";
        }
        /* $d1Arrar = explode("-", $d1); */
        /*if(!empty($params['query']['t-month'])){
            $d1Arrar['1'] = $params['query']['t-month'];
        }else{
            $d1Arrar = explode("-", $d1); //pr($d1Arrar);
        }*/
        
        if(!empty($params['query']['t-month'])){
			$monthValue = $params['query']['t-month'];
		}else{
			$monthValue = isset($dateParams['month']) && strlen($dateParams['month']) === 1 
    		? '0' . $dateParams['month'] : $dateParams['month'];
		}
		
		


        $userDVC = $cdvC = $cvdvC = $dv_regC = $userDC = $userRC = $rgC = $dpC = $crgC = $cdpC = $cvrgC = $cvdpC ="";
        if (!empty($params['query']['dv'])){
            if (empty($params['query']['rg']) && empty($params['query']['dp'])) {
                $divisionRegion=  ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields'=>array('region_id'),'conditions'=>array('division_id'=>$params['query']['dv'])));
                $rIds = implode(",",$rIds); //pr($rIds);exit;
                $dv_regC = " AND d.region_id IN ( ".$rIds.") ";
            }
            $cvdvC = " AND us.division_id = ".$params['query']['dv'];
            $cdvC = " AND c.division_id = ".$params['query']['dv'];
            $userDVC = " AND u.division_id = ".$params['query']['dv'];

        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND d.region_id = ".$params['query']['rg'];
            $cvrgC = " AND us.region_id = ".$params['query']['rg'];
            $crgC = " AND c.region_id = ".$params['query']['rg'];
            $userRC = " AND u.region_id = ".$params['query']['rg'];

        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND d.id = ".$params['query']['dp'];
            $cvdpC = " AND us.depot_id = ".$params['query']['dp'];
            $cdpC = " AND c.depot_id = ".$params['query']['dp'];
            $userDC = " AND u.depot_id = ".$params['query']['dp'];
        }


        $result = array();

        $orderEntry = $this->query("SELECT SUM(sl.cal_qty) AS totQty, count(DISTINCT sl.order_id) as oentry, sl.user_id, sl.depot_id, d.title, d.region_id FROM sales sl INNER JOIN depots d ON d.id = sl.depot_id WHERE $oC $dv_regC $rgC $dpC GROUP BY sl.depot_id, sl.user_id");

        $consorderEntry = $this->query("SELECT SUM(sl.cal_qty) AS totQty, count(DISTINCT sl.consumer_order_id) as oentry, sl.user_id, sl.depot_id, d.title, d.region_id FROM consumer_sales sl INNER JOIN depots d ON d.id = sl.depot_id WHERE $oC $dv_regC $rgC $dpC GROUP BY sl.depot_id, sl.user_id");

        $rSaleEntry = $this->query("SELECT SUM(rsi.cal_qty) AS totQty, count(DISTINCT rsi.redistributor_sale_id) as rsentry, rsi.user_id, rsi.depot_id, d.title, d.region_id FROM redistributor_saleitems rsi INNER JOIN depots d ON d.id = rsi.depot_id WHERE $rdC $dv_regC $rgC $dpC GROUP BY rsi.depot_id, rsi.user_id");

        $consrSaleEntry = $this->query("SELECT SUM(rsi.cal_qty) AS totQty, count(DISTINCT rsi.consumer_redistribution_order_id) as rsentry, rsi.user_id, rsi.depot_id, d.title, d.region_id FROM consumer_redistribution_sales rsi INNER JOIN depots d ON d.id = rsi.depot_id WHERE $rdC $dv_regC $rgC $dpC GROUP BY rsi.depot_id, rsi.user_id");

        //$visitEntry = $this->query("SELECT count(cv.user_id) as ventry, cv.user_id, cv.depot_id, us.depot_id, us.region_id FROM customer_visits cv INNER JOIN users us ON us.id = cv.user_id WHERE $cvC $cvdvC $cvrgC $cvdpC GROUP BY us.depot_id, cv.user_id");
		
		$excludeVisitRoles = getExcludedUserRolesForSale();
		
        if(!empty($params['cvisityear_tables'])){
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                $visitEntries[$year] = $this->query("SELECT count(cv.user_id) as ventry, cv.user_id, cv.depot_id, us.depot_id, us.region_id FROM $cv_tableName cv INNER JOIN users us ON us.id = cv.user_id WHERE $cvC $cvdvC $cvrgC $cvdpC AND us.role_id NOT IN (".implode(', ', $excludeVisitRoles).") GROUP BY us.depot_id, cv.user_id");
            }
            //pr($params['cvisityear_tables']);
        }
        //pr($visitEntry);

        if ($orderEntry){
            foreach ($orderEntry as $oe){
                $uid = $oe['sl']['user_id'];
                $did = $oe['sl']['depot_id'];
                $rid = $oe['d']['region_id'];
                $result[$rid][$did][$uid]['orderEntry'] = $oe;
                $result[$rid][$did][$uid]['saleEntry'] = $oe['0']['oentry'];
                $result[$rid][$did][$uid]['saleTotQty'] = $oe['0']['totQty'];
            }
        }

        if ($consorderEntry){
            foreach ($consorderEntry as $oe){
                $uid = $oe['sl']['user_id'];
                $did = $oe['sl']['depot_id'];
                $rid = $oe['d']['region_id'];
                $result[$rid][$did][$uid]['consorderEntry'] = $oe;
                $result[$rid][$did][$uid]['conssaleEntry'] = $oe['0']['oentry'];
                $result[$rid][$did][$uid]['conssaleTotQty'] = $oe['0']['totQty'];
            }
        }

        if ($consrSaleEntry){
            foreach ($consrSaleEntry as $rse){
                $uid = $rse['rsi']['user_id'];
                $did = $rse['rsi']['depot_id'];
                $rid = $rse['d']['region_id'];
                $result[$rid][$did][$uid]['consrsEntry'] = $rse;
                $result[$rid][$did][$uid]['consrsSaleEntry'] = $rse['0']['rsentry'];
                $result[$rid][$did][$uid]['consrsSaleTotQty'] = $rse['0']['totQty'];
            }
        }

        /*if ($visitEntry){
            foreach ($visitEntry as $cve){
                $uid = $cve['cv']['user_id'];
                $did = ($cve['us']['depot_id'])?$cve['us']['depot_id']:0;
                $rid = $cve['us']['region_id'];
                $result[$rid][$did][$uid]['visitEntry'] = $cve;
                $result[$rid][$did][$uid]['ventry'] = $cve['0']['ventry'];
            }
        } */

        if (!empty($visitEntries)) {
            foreach ($visitEntries as $year => $visitEntry) {
                foreach ($visitEntry as $cve){
                    $uid = $cve['cv']['user_id'];
                    $did = ($cve['us']['depot_id'])?$cve['us']['depot_id']:0;
                    $rid = $cve['us']['region_id'];
                    $result[$rid][$did][$uid]['visitEntry'] = $cve;
                    $result[$rid][$did][$uid]['ventry'] = $cve['0']['ventry'];
                }
            }
        }

        //Count customers created
        //$customerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM customers c WHERE 1 $cdvC $crgC $cdpC GROUP BY c.user_id");
		$customerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM customers c WHERE $ccC $cdvC $crgC $cdpC AND c.status = ".ACTIVE." GROUP BY c.user_id");

        if ($customerEntry){
            foreach ($customerEntry as $cve){
                $uid = $cve['c']['user_id'];
                $result['cCreated'][$uid] = $cve;
                $result['totalCustomer'][$uid] = $cve['0']['cCreated'];
            }
        }

        //Count consumers created
        $consumerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM consumers c WHERE $ccC $cdvC $crgC $cdpC GROUP BY c.user_id");

        if ($consumerEntry){
            foreach ($consumerEntry as $cve){
                $uid = $cve['c']['user_id'];
                $result['consCreated'][$uid] = $cve;
                $result['totalConsumer'][$uid] = $cve['0']['cCreated'];
            }
        }

        //$output['totalCalls'] = $totalCalls;
        $output['result'] = $result;

        //Get All users
        $users = array();
		
        /* $usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE r.grade > 2 AND u.status = ".ACTIVE."   $userDVC $userRC $userDC ORDER BY rg.title ASC, u.role_id ASC"); */
		
		$excludedRoles = getExcludedUserRolesForVisit();
		
		$usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE r.id NOT IN(".implode(', ', $excludedRoles).") AND u.status = ".ACTIVE."   $userDVC $userRC $userDC ORDER BY rg.title ASC, u.role_id ASC");
		
        foreach($usersData as $user){

            $rid = ($user['u']['region_id'])?$user['u']['region_id']:0;
            $did = ($user['u']['depot_id'])?$user['u']['depot_id']:0;

            $uid = $user['u']['id'];
            $users[$rid][$did][$uid] = array('name'=> $user['u']['first_name'].' '.$user['u']['last_name'], 'rid'=>$user['u']['role_id'], 'role'=>$user['r']['name'], 'depot'=>$user['d']['title']);
        }
        $output['users'] = $users;
        //pr($users);
        //find monthly Targets
        $targets = array();
        $targetQry = $this->query("SELECT user_id, depot_id, target FROM user_targets AS Target WHERE type='Call'");
        //pr($targetQry);
        if($targetQry){
            foreach($targetQry as $target){
                $user_id = $target['Target']['user_id'];
                $depot_id = $target['Target']['depot_id'];
                $userTargets = @unserialize($target['Target']['target']);
                $targets[$user_id] = !empty($userTargets[$monthValue])?$userTargets[$monthValue]:0;

                //$targets[$user_id] = !empty($userTargets[$d1Arrar['1']])?$userTargets[$d1Arrar['1']]:0;
            }
        }
        $output['targets'] = $targets;
        return $output;
    }

    function customerReports($params){
        $output = array();
        $date = $params['date'];

        switch($params['type']){
            case 'daily':

                break;
            case 'between':

                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }


                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);
                $enddate = date('Y-m-d', strtotime("+1 day", strtotime($d2)));
                //$cdate = "c.created between '$d1' AND '$enddate'";
                $cdate = "1";

                break;
        }
        $d1Arrar = explode("-", $d1);


        $userDVC = $dvC = $userDC = $userRC = $rgC = $dpC = "";
        if (!empty($params['query']['dv'])){
            $dvC = " AND c.division_id = ".$params['query']['dv'];
            $userDVC = " AND u.division_id = ".$params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND c.region_id = ".$params['query']['rg'];
            $userRC = " AND u.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND c.depot_id = ".$params['query']['dp'];
            $userDC = " AND u.depot_id = ".$params['query']['dp'];
        }


        $result = array();

        //$customerByUser = $this->query("SELECT count(c.id) as totCustomer, c.user_id FROM customers c WHERE $cdate $dvC $rgC $dpC GROUP BY c.user_id");
		$customerByUser = $this->query("SELECT count(c.id) as totCustomer, c.user_id FROM customers c WHERE $cdate $dvC $rgC $dpC AND c.status= ".ACTIVE." GROUP BY c.user_id");

        if ($customerByUser){
            foreach ($customerByUser as $cust){
                $uid = $cust['c']['user_id'];
                //$did = $cust['c']['depot_id'];
                //$rid = $cust['d']['region_id'];
                //$result[$rid][$did][$uid]['customerEntry'] = $cust;
                //$result[$rid][$did][$uid]['name'] = $cust['u']['first_name'].' '.$cust['u']['last_name'];
                $result['custCreated'][$uid] = $cust['0']['totCustomer'];
                //$result[$rid][$did][$uid]['dname'] = $cust['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $cust['u']['role_id'];
            }
        }



        //$output['totalCalls'] = $totalCalls;
        $output['result'] = $result;
        //Get roles
        /*$roles = array();
        $roleData = $this->query("SELECT id, name FROM roles AS Role");
        foreach($roleData as $role){
            $id = $role['Role']['id'];
            $roles[$id] = $role['Role']['name'];
        }
        $output['roles'] = $roles;
        */
        $users = array();
        $usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE r.grade > 2 AND u.status = ".ACTIVE." $userDVC $userDC $userRC ORDER BY rg.title ASC, u.role_id ASC");
        foreach($usersData as $user){

            $rid = $user['u']['region_id'];
            $did = $user['u']['depot_id'];
            $uid = $user['u']['id'];
            $users[$rid][$did][$uid] = array('name'=> $user['u']['first_name'].' '.$user['u']['last_name'], 'rid'=>$user['u']['role_id'], 'role'=>$user['r']['name'], 'depot'=>$user['d']['title']);
        }
        $output['users'] = $users;

        //find monthly Targets
        $targets = array();
        $targetQry = $this->query("SELECT user_id, depot_id, target FROM user_targets AS Target WHERE type='Customer'");
        if($targetQry){
            foreach($targetQry as $target){
                $user_id = $target['Target']['user_id'];
                $depot_id = $target['Target']['depot_id'];
                //$userTargets = @unserialize($target['Target']['target']);
                $targets[$user_id] = $target['Target']['target'];
            }
        }
        $output['targets'] = $targets;
        return $output;
    }

    /* function dayCalls($params){
        $output = array();
        $date = $params['date'];
        switch($params['type']){
            case 'daily':
                $oC = "o.order_date = '$date'";
                $rdC = "rs.sale_date = '$date'";
                $crdC = "rs.order_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
                break;
            case 'between':

                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }

                $oC = "o.order_date between '$d1' AND '$d2'";
                $rdC = "rs.sale_date between '$d1' AND '$d2'";
                $crdC = "rs.order_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $oC = "o.order_date between '$d1' AND '$d2'";
                $rdC = "rs.sale_date between '$d1' AND '$d2'";
                $crdC = "rs.order_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
        }

		//pr($oC); pr($rdC); pr($crdC); pr($cvC); 

        $dvC = $rgC = $dpC = "";
        if (!empty($params['query']['dv'])){
            $dvC = " AND u.division_id = ".$params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND u.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND u.depot_id = ".$params['query']['dp'];
        }

        //$orderCount = $this->query("SELECT count(o.id) as oentry FROM orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC");
		$orderCount = $this->query("SELECT o.id, SUM((SELECT count(DISTINCT(sl.order_id)) FROM sales sl INNER JOIN depots d ON d.id = sl.depot_id WHERE sl.order_id = o.id )) as oentry FROM orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC");

        $consorderCount = $this->query("SELECT count(o.id) as oentry FROM consumer_orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC");

        //$rSaleCount = $this->query("SELECT count(rs.id) as rsentry FROM redistributor_sales rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC");
		$rSaleCount = $this->query("SELECT rs.id, SUM((SELECT count(DISTINCT(rsi.redistributor_sale_id)) FROM redistributor_saleitems rsi WHERE rsi.redistributor_sale_id = rs.id )) as rsentry FROM redistributor_sales rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC");

        $consrSaleCount = $this->query("SELECT count(rs.id) as rsentry FROM consumer_redistribution_orders rs INNER JOIN users u ON u.id = rs.user_id WHERE $crdC $dvC $rgC $dpC");

        //$visitCount = $this->query("SELECT count(cv.id) as ventry FROM customer_visits cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC");
        if(!empty($params['cvisityear_tables'])){
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                $visitCounts[$year] = $this->query("SELECT count(cv.id) as ventry FROM $cv_tableName cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC");
            }
            //pr($visitCounts);
            //pr($params['cvisityear_tables']);
        }

        $output['effectiveSales'] = $orderCount['0']['0']['oentry'];
        $output['effectiveRdSales'] = $rSaleCount['0']['0']['rsentry'];

        $output['effectiveConsSales'] = $consorderCount['0']['0']['oentry'];
        $output['effectiveConsRdSales'] = $consrSaleCount['0']['0']['rsentry'];

        //$output['effectiveVisit'] = $visitCount['0']['0']['ventry'];
        $output['effectiveVisit'] = 0;
        $visitCount['0']['0']['ventry'] = 0;
        if (!empty($visitCounts)) {
            foreach ($visitCounts as $year => $visitCounti) {
                $output['effectiveVisit'] += $visitCounti['0']['0']['ventry'];
                $visitCount['0']['0']['ventry'] += $visitCounti['0']['0']['ventry'];
            }
        }
        $output['effectiveSalesAndRd'] = $output['effectiveSales'] + $output['effectiveRdSales'] +$output['effectiveConsSales'] + $output['effectiveConsRdSales'];

        $totalCalls = $orderCount['0']['0']['oentry'] + $rSaleCount['0']['0']['rsentry'] + $consorderCount['0']['0']['oentry'] + $consrSaleCount['0']['0']['rsentry'] + $visitCount['0']['0']['ventry'];

        $result = array();
        //$orderEntry = $this->query("SELECT count(u.id) as oentry, o.user_id, u.first_name, u.last_name FROM orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC GROUP BY u.id");
		$orderEntry = $this->query("SELECT SUM((SELECT count(DISTINCT(sl.order_id)) FROM sales sl INNER JOIN depots d ON d.id = sl.depot_id WHERE sl.order_id = o.id )) as oentry, o.user_id, u.first_name, u.last_name FROM orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC GROUP BY u.id");

        $consorderEntry = $this->query("SELECT count(u.id) as oentry, o.user_id, u.first_name, u.last_name FROM consumer_orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC GROUP BY u.id");

        //$rSaleEntry = $this->query("SELECT count(u.id) as rsentry, rs.user_id, u.first_name, u.last_name FROM redistributor_sales rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC GROUP BY u.id");
		$rSaleEntry = $this->query("SELECT SUM((SELECT count(DISTINCT(rsi.redistributor_sale_id)) FROM redistributor_saleitems rsi WHERE rsi.redistributor_sale_id = rs.id )) as rsentry, rs.user_id, u.first_name, u.last_name FROM redistributor_sales rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC GROUP BY u.id");

        $consrSaleEntry = $this->query("SELECT count(u.id) as rsentry, rs.user_id, u.first_name, u.last_name FROM consumer_redistribution_orders rs INNER JOIN users u ON u.id = rs.user_id WHERE $crdC $dvC $rgC $dpC GROUP BY u.id");

        //$visitEntry = $this->query("SELECT count(u.id) as ventry, cv.user_id, u.first_name, u.last_name FROM customer_visits cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC GROUP BY u.id");
        if(!empty($params['cvisityear_tables'])){
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                $visitEntries[$year] = $this->query("SELECT count(u.id) as ventry, cv.user_id, u.first_name, u.last_name FROM $cv_tableName cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC GROUP BY u.id");
            }
            //pr($visitEntries);
        }

        if ($orderEntry){
            foreach ($orderEntry as $oe){
                $uid = $oe['o']['user_id'];
                $result[$uid]['orderEntry'] = $oe;
                $result[$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
            }
        }

        if ($consorderEntry){
            foreach ($consorderEntry as $oe){
                $uid = $oe['o']['user_id'];
                $result[$uid]['consorderEntry'] = $oe;
                $result[$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
            }
        }

        if ($rSaleEntry){
            foreach ($rSaleEntry as $rse){
                $uid = $rse['rs']['user_id'];
                $result[$uid]['rsEntry'] = $rse;
                $result[$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
            }
        }

        if ($consrSaleEntry){
            foreach ($consrSaleEntry as $rse){
                $uid = $rse['rs']['user_id'];
                $result[$uid]['consrsEntry'] = $rse;
                $result[$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
            }
        }

        if (!empty($visitEntries)){
            foreach ($visitEntries as $year => $visitEntry){
                foreach ($visitEntry as $cve) {
                    $uid = $cve['cv']['user_id'];
                    $result[$uid]['visitEntry'] = $cve;
                    $result[$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                }
            }
        }

        $output['totalCalls'] = $totalCalls;
        $output['result'] = $result;
        //pr($output);
        return $output;
    } */
	
	function dayCalls($params){
        $output = array();
        $dateParams = $params['dateParams'];
		
        switch($params['type']){
            case 'daily':
				$date = $dateParams['date'];
                $oC = "sl.sale_date = '$date'";
                $rdC = "rsi.sale_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
                break;
			default:
				$d1 = $dateParams['from'];
				$d2 = $dateParams['to'];
				
				$oC = "sl.sale_date between '$d1' AND '$d2'";
				$rdC = "rsi.sale_date between '$d1' AND '$d2'";
				$cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
				
            /* case 'between':

                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }

                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break; */
        }
		
		
		$userDVC = $userRC = $userDC = "";
        if (!empty($params['query']['dv'])){
            $userDVC = " AND u.division_id = ".$params['query']['dv'];
		}
        if (!empty($params['query']['rg'])){
            $userRC = " AND u.region_id = ".$params['query']['rg'];

        }
        if (!empty($params['query']['dp'])){
            $userDC = " AND u.depot_id = ".$params['query']['dp'];
        }
		
		
		$result = array();
		
		
		//Get All users 
        $users = $user_ids = array();
		//[ADMINISTRATOR, HMS, SUPPORTTEAM1, SUPPORTTEAM2, PROMO, DIVISIONMANAGER, RM]
		$excludedRoles = getExcludedUserRolesForSale();
        $usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, u.status, d.title FROM users AS u INNER JOIN depots d ON d.id = u.depot_id WHERE u.role_id NOT IN(".implode(', ', $excludedRoles).") $userDVC $userDC $userRC ORDER BY u.first_name ASC, u.last_name ASC");
        foreach($usersData as $user){

            $rid = ($user['u']['region_id'])?$user['u']['region_id']:0;
            $did = ($user['u']['depot_id'])?$user['u']['depot_id']:0;

            $uid = $user['u']['id'];
            $users[$uid] = array('name'=> $user['u']['first_name'].' '.$user['u']['last_name'], 'rid'=>$user['u']['role_id'], 'depot'=>$user['d']['title'], 'status'=>$user['u']['status']);
			if (!in_array($uid, $user_ids)){
				array_push($user_ids, $uid);
			}
			
        }
        $output['users'] = $users;
		
		/* $orderEntry = $this->query("SELECT count(DISTINCT sl.order_id) as oentry, sl.user_id, sl.depot_id FROM sales sl WHERE $oC AND sl.user_id IN (".implode(', ', $user_ids).") GROUP BY sl.user_id"); //pr($orderEntry); 

        $consorderEntry = $this->query("SELECT count(DISTINCT sl.consumer_order_id) as oentry, sl.user_id, sl.depot_id FROM consumer_sales sl WHERE $oC AND sl.user_id IN (".implode(', ', $user_ids).") GROUP BY sl.user_id"); //pr(consorderEntry);

        $rSaleEntry = $this->query("SELECT count(DISTINCT rsi.redistributor_sale_id) as rsentry, rsi.user_id, rsi.depot_id FROM redistributor_saleitems rsi WHERE $rdC AND rsi.user_id IN (".implode(', ', $user_ids).") GROUP BY rsi.user_id"); //pr($rSaleEntry); 

        $consrSaleEntry = $this->query("SELECT count(DISTINCT rsi.consumer_redistribution_order_id) as rsentry, rsi.user_id, rsi.depot_id FROM consumer_redistribution_sales rsi WHERE $rdC AND rsi.user_id IN (".implode(', ', $user_ids).") GROUP BY rsi.user_id");

        if(!empty($params['cvisityear_tables'])) {
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName) {
                $visitEntries[$year] = $this->query("SELECT count(cv.user_id) as ventry, cv.user_id, cv.depot_id FROM $cv_tableName cv WHERE $cvC AND cv.user_id IN (".implode(', ', $user_ids).") GROUP BY cv.user_id");
            }
        } */
		
		$orderEntry = $this->query("SELECT COUNT(DISTINCT CONCAT(sl.customer_id, '-', sl.sale_date)) as oentry, sl.user_id, sl.depot_id FROM sales sl WHERE $oC AND sl.user_id IN (".implode(', ', $user_ids).") GROUP BY sl.user_id"); //pr($orderEntry); 

        $consorderEntry = $this->query("SELECT COUNT(DISTINCT CONCAT(sl.consumer_id, '-', sl.sale_date)) as oentry, sl.user_id, sl.depot_id FROM consumer_sales sl WHERE $oC AND sl.user_id IN (".implode(', ', $user_ids).") GROUP BY sl.user_id"); //pr(consorderEntry);

        $rSaleEntry = $this->query("SELECT COUNT(DISTINCT CONCAT(rsi.customer_id, '-', rsi.sale_date)) as rsentry, rsi.user_id, rsi.depot_id FROM redistributor_saleitems rsi WHERE $rdC AND rsi.user_id IN (".implode(', ', $user_ids).") GROUP BY rsi.user_id"); //pr($rSaleEntry); 

        $consrSaleEntry = $this->query("SELECT COUNT(DISTINCT CONCAT(rsi.consumer_id, '-', rsi.sale_date)) as rsentry, rsi.user_id, rsi.depot_id FROM consumer_redistribution_sales rsi WHERE $rdC AND rsi.user_id IN (".implode(', ', $user_ids).") GROUP BY rsi.user_id");

        if(!empty($params['cvisityear_tables'])) {
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName) {
                $visitEntries[$year] = $this->query("SELECT COUNT(DISTINCT CONCAT(cv.customer_id, '-', date(cv.visiting_date))) as ventry, cv.user_id, cv.depot_id FROM $cv_tableName cv WHERE $cvC AND cv.user_id IN (".implode(', ', $user_ids).") GROUP BY cv.user_id");
            }
        }
		
		$output['TotalSaleCount'] =  $output['TotalRdSaleCount'] = $output['TotalConsSaleCount'] =  $output['TotalConsRdSaleCount'] = $output['TotalVisitCount'] = $output['TotalCalls'] = 0;
		

        if ($orderEntry){
            foreach ($orderEntry as $oe){
                $uid = $oe['sl']['user_id'];
                $result[$uid]['orderEntry'] = $oe['0']['oentry'];
				$output['TotalSaleCount'] += $oe['0']['oentry'];
            }
        }

        if ($consorderEntry){
            foreach ($consorderEntry as $oe){
                $uid = $oe['sl']['user_id'];
                $result[$uid]['consorderEntry'] = $oe['0']['oentry'];
				$output['TotalConsSaleCount'] += $oe['0']['oentry'];
            }
        }

        if ($rSaleEntry){
            foreach ($rSaleEntry as $rse){
                $uid = $rse['rsi']['user_id'];
                $result[$uid]['rsEntry'] = $rse['0']['rsentry'];
				$output['TotalRdSaleCount'] += $rse['0']['rsentry'];
            }
        }

        if ($consrSaleEntry){
            foreach ($consrSaleEntry as $rse){
                $uid = $rse['rsi']['user_id'];
                $result[$uid]['consrsEntry'] = $rse['0']['rsentry'];
                $output['TotalConsRdSaleCount'] += $rse['0']['rsentry'];
            }
        }


        if (!empty($visitEntries)){
            foreach ($visitEntries as $year => $visitEntry){
                foreach ($visitEntry as $cve) {
                    $uid = $cve['cv']['user_id'];
                    $result[$uid]['visitEntry'] = $cve['0']['ventry'];
                   $output['TotalVisitCount'] += $cve['0']['ventry'];
                }
            }
        }
		
		$output['TotalCalls'] = $output['TotalSaleCount'] +  $output['TotalRdSaleCount'] + $output['TotalConsSaleCount'] +  $output['TotalConsRdSaleCount'] + $output['TotalVisitCount'];


        $output['result'] = $result;
        //pr($output);
        return $output;
    }

    /**
     * numberOfCustomers
     * @params : array
     * return array
     */
    public function numberOfCustomers($params){
        //pr($params);
        $reportArr = array();
        $date = $params['date'];
        $result = array();
        switch($params['type']){
            case 'daily':
                $cC = "c.created LIKE '".$date."%'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));
                $cC = "c.created between '$d1' AND '$d2'";
                break;
            case 'between':
                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $cC = "c.created between '$d1' AND '$d2'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $cC = "c.created between '$d1' AND '$d2 23:59:59'";

                break;
        }
        $dvC = $rgC = $dpC = "";
        if (!empty($params['query']['dv'])){
            $dvC = " AND c.division_id = ".$params['query']['dv'];
        }
        if(!empty($params['query']['rg'])){
            $rgC = " AND c.region_id = ".$params['query']['rg'];
        }
        if(!empty($params['query']['dp'])){
            $dpC = " AND c.depot_id = ".$params['query']['dp'];
        }
        $customerCreated = $this->query("SELECT COUNT(*) as totCustomer FROM customers c WHERE $cC $dvC $rgC $dpC");

        $numberOfCustomer = $this->query("SELECT u.id, u.first_name, u.last_name, COUNT(c.id) as totCust FROM users u INNER JOIN customers c ON c.user_id = u.id WHERE $cC $dvC $rgC $dpC GROUP BY c.user_id");

        $result['totCustomer'] = $customerCreated['0']['0']['totCustomer'];
        $result['userCustomer'] = $numberOfCustomer;

        return $result;
    }
    /**
     * numberOfCustomers
     * @params : array
     * return array
     */
    public function numberofVisits($params){
        //pr($params);
        $reportArr = array();
        $date = $params['date'];
        $result = array();
        switch($params['type']){
            case 'daily':
                $cC = "c.created LIKE '".$date."%'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));
                $cC = "c.created between '$d1' AND '$d2'";
                break;
            case 'between':
                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $cC = "c.created between '$d1' AND '$d2'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $cC = "c.created between '$d1' AND '$d2'";

                break;
        }

        $customerVists = $this->query("SELECT COUNT(*) as totVisits FROM customer_visits c WHERE $cC");

        $numberOfVists = $this->query("SELECT u.id, u.first_name, u.last_name, COUNT(c.id) as totVisit FROM users u INNER JOIN customer_visits c ON c.user_id = u.id WHERE $cC GROUP BY c.user_id");

        $result['totVisits'] = $customerVists['0']['0']['totVisits'];
        $result['userVisits'] = $numberOfVists;

        return $result;
    }
    /**
     * customer_notvisits
     * @params : array
     * return array
     */
    public function customerNotvisitConditions($params, &$paginate, &$conditions){
        //pr($params);
        $reportArr = array();
        $date = !empty($params['date']) ? $params['date'] : date('Y-m-d');
        $result = array();
        switch($params['type']){
            case 'daily':
				$d1 = $params['date'];
				$oC = "AND Order.order_date = '".$d1."'";
				$cvC = "AND CustomerVisit.visiting_date LIKE '".$d1."%'";
				$Rc = " AND RSale.sale_date LIKE '".$d1."%'";
			break;
			
			default:
				$d1 = $params['from'];
				$d2 = $params['to'];
				
				$oC = "AND Order.order_date between '$d1' AND '$d2'";
				$cvC = "AND CustomerVisit.visiting_date between '$d1' AND '$d2 23:59:59'";
				$Rc = " AND RSale.sale_date between '$d1' AND '$d2'";
			break;
        }
		
		$conditions = array('Customer.status' => ACTIVE);
		$conditions['Customer.first_name NOT'] = null;
		$conditions['Customer.last_name NOT'] = null;
		
		if (!empty($params['query']['user_ids']) && !empty($params['query']['user_ids'][0])){
			$conditions['Customer.user_id'] = $params['query']['user_ids'];
		}
		
        if (!empty($params['query']['dv'])){
            $conditions['Customer.division_id'] = $params['query']['dv'];
        }

        if (!empty($params['query']['rg'])){
            $conditions['Customer.region_id'] = $params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $conditions['Customer.depot_id'] = $params['query']['dp'];
        }
		if (!empty($params['query']['rt'])){
            $conditions['Customer.route_id'] = $params['query']['rt'];
        }

        $paginate['paramType'] = 'querystring';
		
		if(empty($params['join_order']) && empty($params['join_customer_visit']) && empty($params['join_rsale'])){
			$params['join_order'] = $params['join_customer_visit'] = $params['join_rsale'] = 1;
		}

        if (!empty($params['join_order'])) {
			$paginate['joins'][] = array('table' => 'orders', 'type'=>'left', 'alias'=>'Order', 'conditions'=>array('Customer.id=Order.customer_id '.$oC));
		}

        //$paginate['joins'][] = array('table' => 'customer_visits', 'type'=>'left', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id '.$cvC));
		
		if (!empty($params['join_customer_visit'])) {
			if(!empty($params['cvisityear_tables'])){
				if(count($params['cvisityear_tables'])>1){
					$cvisityear_tabSqlArray = array();
					foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
						$cvisityear_tabSqlArray[] = " ( SELECT * FROM $cv_tableName as CustomerVisit WHERE 1 $cvC )";
					}
					$cvisityear_tabSql = "( ".implode(" UNION ALL ", $cvisityear_tabSqlArray)." )"; // UNION operation For Multiple customer_visits table as per year wise organized

				}else{
					$cvisityear_tabSql = $params['cvisityear_tables'][key($params['cvisityear_tables'])]; // Single customer_visits table as per year wise organized
				}
				//pr($cvisityear_tabSql);
			}else{
				$cvisityear_tabSql ='customer_visits';
			}
			
			
			$paginate['joins'][] = array('table' => $cvisityear_tabSql, 'type'=>'left', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id '.$cvC));
		}

		if (!empty($params['join_rsale'])) {
			$paginate['joins'][] = array('table' => 'redistributor_sales', 'type' => 'left', 'alias' => 'RSale', 'conditions' => array('Customer.id = RSale.customer_id'.$Rc));
		}
		
		
        if(!empty($params['isVisit']) && $params['isVisit'] == 1){
            //$conditions['OR'] = array('RSale.id IS NOT null','Order.id IS NOT null', 'CustomerVisit.id IS NOT null');
			
			$orConditions = array();

			if (!empty($params['join_rsale'])) {
				$orConditions[] = 'RSale.id IS NOT null';
			}

			if (!empty($params['join_order'])) {
				$orConditions[] = 'Order.id IS NOT null';
			}

			if (!empty($params['join_customer_visit'])) {
				$orConditions[] = 'CustomerVisit.id IS NOT null';
			}

			if (!empty($orConditions)) {
				$conditions['OR'] = $orConditions;
			}
			
        }else{
            $conditions['CustomerVisit.id'] = null;
            $conditions['Order.id'] = null;
            $conditions['RSale.id'] = null;
        }
        $paginate['limit'] = PAGE_LIMIT;

    }

    function averageCalls($params){
        $output = array();
        //$date = $params['date'];
        switch($params['type']){
            case 'daily':
                $date = $params['date'];
                $oC = "o.order_date = '$date'";
                $rdC = "rs.sale_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
                break;
			default:
				$d1 = $params['from'];
				$d2 = $params['to'];
				
				$oC = "o.order_date between '$d1' AND '$d2'";
				$rdC = "rs.sale_date between '$d1' AND '$d2'";
				$cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";	
			break;	
			
        }



        $dvC = $rgC = $dpC = "";
        if (!empty($params['query']['dv'])){
            $dvC = " AND u.division_id = ".$params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND u.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND u.depot_id = ".$params['query']['dp'];
        }
		$custAC = " AND c.status =".ACTIVE;
        $result = array();
        $orderCount = $this->query("SELECT count(o.id) as oentry FROM orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC");
        $rSaleCount = $this->query("SELECT count(rs.id) as rsentry FROM redistributor_sales rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC");
        //$visitCount = $this->query("SELECT count(cv.id) as ventry FROM customer_visits cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC");
		//$visitCount = $this->query("SELECT count(cv.id) as ventry FROM customer_visits cv LEFT JOIN customers c ON cv.customer_id = c.id INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC $custAC");
        if(!empty($params['cvisityear_tables'])){
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                $visitCounts[$year] = $this->query("SELECT count(cv.id) as ventry FROM $cv_tableName cv LEFT JOIN customers c ON cv.customer_id = c.id INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC $custAC");
            }
        }

        $output['effectiveSales'] = $orderCount['0']['0']['oentry'];
        $output['effectiveRdSales'] = $rSaleCount['0']['0']['rsentry'];
        //$output['effectiveVisit'] = $visitCount['0']['0']['ventry'];
        $output['effectiveVisit'] = 0;
        $visitCount['0']['0']['ventry'] = 0;
        if (!empty($visitCounts)) {
            foreach ($visitCounts as $year => $visitCounti) {
                $output['effectiveVisit'] += $visitCounti['0']['0']['ventry'];
                $visitCount['0']['0']['ventry'] += $visitCounti['0']['0']['ventry'];
            }
        }

        $result['totalCalls'] = $orderCount['0']['0']['oentry'] + $rSaleCount['0']['0']['rsentry'] + $visitCount['0']['0']['ventry'];

        /* $users = $this->query("SELECT COUNT(*) AS totUser FROM users u INNER JOIN roles r ON r.id = u.role_id WHERE r.grade > 3 $rgC $rgC");
        //$customers = $this->query("SELECT COUNT(*) AS totCustomer FROM customers u WHERE status!=2 $rgC $rgC");
        //$result['totCustomer'] = $customers['0']['0']['totCustomer'];
        $result['totUser'] = $users['0']['0']['totUser']; */

        $resultas = array();
        $orderEntry = $this->query("SELECT count(u.id) as oentry, o.user_id, u.first_name, u.last_name FROM orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC GROUP BY u.id");
        $rSaleEntry = $this->query("SELECT count(u.id) as rsentry, rs.user_id, u.first_name, u.last_name FROM redistributor_sales rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC GROUP BY u.id");
        //$visitEntry = $this->query("SELECT count(u.id) as ventry, cv.user_id, u.first_name, u.last_name FROM customer_visits cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC GROUP BY u.id");
        //$visitEntry = $this->query("SELECT count(u.id) as ventry, cv.user_id, u.first_name, u.last_name FROM customer_visits cv LEFT JOIN customers c ON cv.customer_id = c.id INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC $custAC GROUP BY u.id");
        if(!empty($params['cvisityear_tables'])){
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                $visitEntries[$year] = $this->query("SELECT count(u.id) as ventry, cv.user_id, u.first_name, u.last_name FROM $cv_tableName cv LEFT JOIN customers c ON cv.customer_id = c.id INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC $custAC GROUP BY u.id");
            }
            //pr($visitEntries);
        }
        if ($orderEntry){
            foreach ($orderEntry as $oe){
                $uid = $oe['o']['user_id'];
                $resultas[$uid]['orderEntry'] = $oe;
                $resultas[$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
            }
        }

        if ($rSaleEntry){
            foreach ($rSaleEntry as $rse){
                $uid = $rse['rs']['user_id'];
                $resultas[$uid]['rsEntry'] = $rse;
                $resultas[$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
            }
        }

        /*if ($visitEntry){
            foreach ($visitEntry as $cve){
                $uid = $cve['cv']['user_id'];
                $resultas[$uid]['visitEntry'] = $cve;
                $resultas[$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
            }
        } */

        if (!empty($visitEntries)){
            foreach ($visitEntries as $year => $visitEntry){
                foreach ($visitEntry as $cve) {
                    $uid = $cve['cv']['user_id'];
                    $resultas[$uid]['visitEntry'] = $cve;
                    $resultas[$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                }
            }
        }

        /* $users = $this->query("SELECT COUNT(*) AS totUser FROM users u INNER JOIN roles r ON r.id = u.role_id WHERE r.grade > 3 $rgC $rgC"); */

        //$customers = $this->query("SELECT COUNT(*) AS totCustomer FROM customers u WHERE status!=2 $rgC $rgC");
        //$result['totCustomer'] = $customers['0']['0']['totCustomer'];
        //$result['totUser'] = $users['0']['0']['totUser'];
        $result['totUser'] = count($resultas);

        $result['avgCall'] = 0;
        if ($result['totUser'] > 0){
            $result['avgCall'] = number_format( ($result['totalCalls'] / $result['totUser']), 2);
        }
        return $result;

    }


    function customerTrend($params, &$paginate, &$conditions){
        $output = array();

        $date = ($params['opt'])?$params['opt']:date('Y-m-d');
        $strtotime = strtotime($date);
		
		if($params['etype']=='period'){
            $d1 = $params['query']['from1'];
            $d2 = $params['query']['to1'];

            $d3 = $params['query']['from2'];
            $d4 = $params['query']['to2'];

        }else{
			$d1 = date('Y-m-d', strtotime('-30 days', $strtotime) );
			$d2 = $date;

			$d4 = date('Y-m-d', strtotime('-31 days', $strtotime) );
			$d3 = date('Y-m-d', strtotime('-60 days', $strtotime) );
		}

        if (!empty($params['query']['dv'])){
            $conditions['Customer.division_id'] = $params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $conditions['Customer.region_id'] = $params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $conditions['Customer.depot_id'] = $params['query']['dp'];
        }
		if (!empty($params['query']['rt'])){
            $conditions['Customer.route_id'] = $params['query']['rt'];
        }
        if (!empty($params['query']['us'])){
            $conditions['Customer.user_id'] = $params['query']['us'];
        }


        //$paginate['limit'] = 20;
        $paginate['type'] = $params['type'];
        $paginate['model'] = 'Cutomer';

        $paginate['query'] = $params['query'];
        $paginate['dates'] = compact('d1', 'd2', 'd3', 'd4');

        return compact('d1', 'd2', 'd3', 'd4');
    }

    public function paginate( $conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
        $order = 'totPurchase DESC';
        if($extra['type'] == 'up'){
            $having = "totPurchase > totPurchase2";
        }elseif($extra['type'] == 'same'){
            $having = "totPurchase = totPurchase2";
        }elseif($extra['type'] == 'down'){
            $having = "totPurchase < totPurchase2";
            $order = 'totPurchase2 DESC';
        }
        $conditions = '';
        //pr($extra);
        if (!empty($extra['query']['dv'])){
            $conditions .= ' AND Customer.division_id = '.$extra['query']['dv'];
        }
        if (!empty($extra['query']['rg'])){
            $conditions .= ' AND Customer.region_id = '.$extra['query']['rg'];
        }
        if (!empty($extra['query']['dp'])){
            $conditions .= ' AND Customer.depot_id = '.$extra['query']['dp'];
        }
		if (!empty($extra['query']['rt'])){
            $conditions .= ' AND Customer.route_id = '.$extra['query']['rt'];
        }
        if (!empty($extra['query']['us'])){
            $conditions .= ' AND Customer.user_id = '.$extra['query']['us'];
        }
        if(empty($extra['query']['export'])){
            $start = ($page-1)*$limit;
            $limitStr = "LIMIT $start,  $limit";
        }else{
            $offset = $extra['query']['offset'];
            if($offset == ''){$offset = 0;}
            $limitStr = "LIMIT $offset,  10000";
        }
        $result = $this->query("SELECT Customer.id, Customer.first_name, Customer.last_name,Customer.depot_id,Customer.route_id , SUM(Sale.`cal_qty`) AS totPurchase, Sale2.tot2 as totPurchase2 FROM `customers` AS Customer LEFT JOIN `sales` AS Sale ON Sale.customer_id = Customer.id LEFT JOIN (SELECT s2.customer_id AS customer_id, SUM(s2.cal_qty) as tot2 FROM sales as s2 WHERE s2.sale_date between '".$extra['dates']['d3']."' AND '".$extra['dates']['d4']."' GROUP BY s2.customer_id ) AS Sale2 ON Sale.customer_id = Sale2.customer_id WHERE Sale.sale_date between '".$extra['dates']['d1']."' AND '".$extra['dates']['d2']."' $conditions GROUP BY Sale.`customer_id` having $having ORDER BY $order $limitStr");
        return $result;
    }

    public function paginateCount($conditions = null, $recursive = 0,$extra = array()) {

        if($extra['type'] == 'up'){
            $having = "totPurchase > totPurchase2";
        }elseif($extra['type'] == 'same'){
            $having = "totPurchase = totPurchase2";
        }elseif($extra['type'] == 'down'){
            $having = "totPurchase < totPurchase2";
            $order = 'totPurchase2 DESC';
        }
        $conditions = '';
        if (!empty($extra['query']['dv'])){
            $conditions .= ' AND Customer.division_id = '.$extra['query']['dv'];
        }
        if (!empty($extra['query']['rg'])){
            $conditions .= ' AND Customer.region_id = '.$extra['query']['rg'];
        }
        if (!empty($extra['query']['dp'])){
            $conditions .= ' AND Customer.depot_id = '.$extra['query']['dp'];
        }
		if (!empty($extra['query']['rt'])){
            $conditions .= ' AND Customer.route_id = '.$extra['query']['rt'];
        }
        if (!empty($extra['query']['us'])){
            $conditions .= ' AND Customer.user_id = '.$extra['query']['us'];
        }
        $countResult = $this->query("SELECT Customer.id, Customer.first_name, Customer.last_name,Customer.route_id,  SUM(Sale.`cal_qty`) AS totPurchase, Sale2.tot2 as totPurchase2 FROM `customers` AS Customer LEFT JOIN `sales` AS Sale ON Sale.customer_id = Customer.id LEFT JOIN (SELECT s2.customer_id AS customer_id, SUM(s2.cal_qty) as tot2 FROM sales as s2 WHERE s2.sale_date between '".$extra['dates']['d3']."' AND '".$extra['dates']['d4']."' GROUP BY s2.customer_id ) AS Sale2 ON Sale.customer_id = Sale2.customer_id WHERE Sale.sale_date between '".$extra['dates']['d1']."' AND '".$extra['dates']['d2']."' $conditions GROUP BY Sale.`customer_id` having $having");
        return count($countResult);
    }
    /********************************************************* PK Task *****************************************************/

    /**
     * numberOfQuantitySale
     * @params : array
     * return array
     */
//     public function numberOfQuantitySale($params){
//         //pr($params);
//         $reportArr = array();
//         $date = $params['date'];
//         $result = array();
//         switch($params['type']){
//             case 'daily':
//                 $cC = "c.sale_date = '".$date."'";
//                 break;
//             case 'weekly':
//                 $d1 = date('Y-m-d', $params['strtotime']);
//                 $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));

//                 $cC = "c.sale_date between '$d1' AND '$d2'";
//                 break;
//             case 'between':
//                 if(empty( $params['query']['from'])){
//                     $d1 = date('Y-m-d');
//                 }else{
//                     $d1 =  $params['query']['from'];
//                 }
//                 if(empty( $params['query']['to'])){
//                     $d2 = date('Y-m-d');
//                 }else{
//                     $d2 =  $params['query']['to'];
//                 }
//                 $cC = "c.sale_date between '$d1' AND '$d2'";
//                 break;
//             case 'monthly':
//                 $d1 = date('Y-m-01', $params['strtotime']);
//                 $d2 = date('Y-m-t', $params['strtotime']);

//                 $cC = "c.sale_date between '$d1' AND '$d2'";

//                 break;
//         }

//         $dv_regC = $rgC = $dpC = "";
//         if (!empty($params['query']['dv'])){
//             if (empty($params['query']['rg'])) {
//                 $divisionRegion = ClassRegistry::init('DivisionsRegion');
//                 $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $params['query']['dv'])));
//                 $rIds = implode(",", $rIds); //pr($rIds);exit;
//                 $dv_regC = " AND d.region_id IN ( " . $rIds . ") ";
//             }

//         }
//         if (!empty($params['query']['rg'])){
//             $rgC = " AND d.region_id = ".$params['query']['rg'];
//         }
//         if (!empty($params['query']['dp'])){
//             $dpC = " AND c.depot_id = ".$params['query']['dp'];
//         }
// 		$viaAppC = "";
// 		if (isset($params['query']['via_app']) && $params['query']['via_app']!='' ){
//             $viaAppC = " AND c.via_app = ".$params['query']['via_app'];
//         }

//         // Check null depot id
//         $ndpC = "AND c.depot_id != 0";

//         $saleCreated = $this->query("SELECT SUM(c.cal_qty) as quantity FROM sales c LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC $ndpC $viaAppC");

//         //$numberOfSale = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.cal_qty) as totSale FROM users u INNER JOIN sales c ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $rgC $dpC GROUP BY c.user_id");

//         $numberOfSale = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.cal_qty) as totSale FROM users u INNER JOIN sales c ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC $ndpC $viaAppC GROUP BY c.user_id");

//         $result['totSale'] = $saleCreated['0']['0']['quantity'];
//         $result['userSale'] = $numberOfSale;

//         return $result;
//     }

    public function numberOfQuantitySale($params){
        //pr($params);
        $result = array();
		$type = $params['type'];
		$user = $params['user'];
		switch ($type) {
			case 'daily':
				$d1 = $params['date'];
				$cC = "c.sale_date = '".$d1."'";
			break;
			default:
				$d1 = $params['from'];
				$d2 = $params['to'];
				$cC = "c.sale_date between '$d1' AND '$d2'";
			break;					
		}

        $dv_regC = $rgC = $dpC = $roleC = "";

        switch($user['Role']['grade']){
            case 2:
                if ($user['Role']['id'] == DIVISIONMANAGER){
                    $divisionRegion = ClassRegistry::init('DivisionsRegion');
                    $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $user['division_id'])));
                    $rIds = implode(",", $rIds);
                    
				    $roleC = " AND c.user_id IN (SELECT id FROM users WHERE region_id IN ( " . $rIds . "))";
                }
				break;
			case 3:
				$roleC = " AND c.user_id IN (SELECT id FROM users WHERE region_id = ".$user['region_id'].")";
				break;
			case 4:
				$roleC = " AND c.user_id IN (SELECT id FROM users WHERE depot_id = ".$user['depot_id'].")";
				break;
			case 5:
				$roleC = " AND (c.user_id = ".$user['id']." OR c.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = ".$user['id']."))";
				break;
			case 6:
			case 7:
				$roleC = " AND c.user_id = ".$user['id'];
				break;
		}

        if (!empty($params['query']['dv'])){
            if (empty($params['query']['rg'])) {
                $divisionRegion = ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $params['query']['dv'])));
                $rIds = implode(",", $rIds); //pr($rIds);exit;
                $dv_regC = " AND d.region_id IN ( " . $rIds . ") ";
            }

        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND d.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND c.depot_id = ".$params['query']['dp'];
        }
		$viaAppC = "";
		if (isset($params['query']['via_app']) && $params['query']['via_app']!='' ){
            $viaAppC = " AND c.via_app = ".$params['query']['via_app'];
        }

        // Check null depot id
        $ndpC = "AND c.depot_id != 0";

        $saleCreated = $this->query("SELECT SUM(c.cal_qty) as quantity FROM sales c LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC $ndpC $roleC $viaAppC ");

    

        //$numberOfSale = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.cal_qty) as totSale FROM users u INNER JOIN sales c ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $rgC $dpC GROUP BY c.user_id");

        $numberOfSale = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.cal_qty) as totSale FROM users u INNER JOIN sales c ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC $ndpC $roleC $viaAppC GROUP BY c.user_id");

        $result['totSale'] = $saleCreated['0']['0']['quantity'];
        $result['userSale'] = $numberOfSale;

        return $result;
    }

    
    /**
     * numberOfQuantityConsumerSale
     * @params : array
     * return array
     */
    public function numberOfQuantityConsumerSale($params){
        //pr($params);
        $reportArr = array();
        $date = $params['date'];
        $result = array();
        switch($params['type']){
            case 'daily':
                $cC = "c.sale_date = '".$date."'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));

                $cC = "c.sale_date between '$d1' AND '$d2'";
                break;
            case 'between':
                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $cC = "c.sale_date between '$d1' AND '$d2'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $cC = "c.sale_date between '$d1' AND '$d2'";

                break;
        }

        $dv_regC = $rgC = $dpC = "";
        if (!empty($params['query']['dv'])){
            if (empty($params['query']['rg'])) {
                $divisionRegion = ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $params['query']['dv'])));
                $rIds = implode(",", $rIds); //pr($rIds);exit;
                $dv_regC = " AND d.region_id IN ( " . $rIds . ") ";
            }

        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND d.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND c.depot_id = ".$params['query']['dp'];
        }

        $saleCreated = $this->query("SELECT SUM(c.cal_qty) as quantity FROM consumer_sales c LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC");

        $numberOfSale = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.cal_qty) as totSale FROM users u INNER JOIN consumer_sales c ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC GROUP BY c.user_id");

        $result['totSale'] = $saleCreated['0']['0']['quantity'];
        $result['userSale'] = $numberOfSale;

        return $result;
    }



    /**
     * ridistribtutionSale
     * @params : array
     * return array
     */
//     public function ridistribtutionSale($params){
//         //pr($params);
//         $reportArr = array();
//         $date = $params['date'];
//         $result = array();
//         switch($params['type']){
//             case 'daily':
//                 $cC = "c.sale_date = '".$date."'";
//                 break;
//             case 'weekly':
//                 $d1 = date('Y-m-d', $params['strtotime']);
//                 $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));

//                 $cC = "c.sale_date between '$d1' AND '$d2'";
//                 break;

//             case 'between':
//                 if(empty( $params['query']['from'])){
//                     $d1 = date('Y-m-d');
//                 }else{
//                     $d1 =  $params['query']['from'];
//                 }
//                 if(empty( $params['query']['to'])){
//                     $d2 = date('Y-m-d');
//                 }else{
//                     $d2 =  $params['query']['to'];
//                 }
//                 $cC = "c.sale_date between '$d1' AND '$d2'";
//                 break;
//             case 'monthly':
//                 $d1 = date('Y-m-01', $params['strtotime']);
//                 $d2 = date('Y-m-t', $params['strtotime']);

//                 $cC = "c.sale_date between '$d1' AND '$d2'";

//                 break;
//         }

//         $dv_regC = $rgC = $dpC = "";
//         if (!empty($params['query']['dv'])){
//             if (empty($params['query']['rg'])) {
//                 $divisionRegion = ClassRegistry::init('DivisionsRegion');
//                 $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $params['query']['dv'])));
//                 $rIds = implode(",", $rIds); //pr($rIds);exit;
//                 $dv_regC = " AND d.region_id IN ( " . $rIds . ") ";
//             }

//         }
//         if (!empty($params['query']['rg'])){
//             $rgC = " AND d.region_id = ".$params['query']['rg'];
//         }
//         if (!empty($params['query']['dp'])){
//             $dpC = " AND c.depot_id = ".$params['query']['dp'];
//         }
		
// 		$viaAppC = "";
// 		if (isset($params['query']['via_app']) && $params['query']['via_app']!='' ){
//             $viaAppC = " AND c.via_app = ".$params['query']['via_app'];
//         }

//         // Check null depot id
//         $ndpC = "AND c.depot_id != 0";

//         $redistributorCreated = $this->query("SELECT SUM(c.cal_qty) as quantity FROM redistributor_saleitems c LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC $ndpC $viaAppC");

//         $numberOfSale = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.cal_qty) as totSale FROM users u INNER JOIN redistributor_saleitems c ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC $ndpC $viaAppC GROUP BY c.user_id");

//         $result['totSale'] = $redistributorCreated['0']['0']['quantity'];
//         $result['userSale'] = $numberOfSale;

//         return $result;
//     }

    public function redistributionSale($params){
        //pr($params);
        $result = array();
		$type = $params['type'];
		$user = $params['user'];
		switch ($type) {
			case 'daily':
				$d1 = $params['date'];
				$cC = "c.sale_date = '".$d1."'";
			break;
			default:
				$d1 = $params['from'];
				$d2 = $params['to'];
				$cC = "c.sale_date between '$d1' AND '$d2'";
			break;					
		}

        $dv_regC = $rgC = $dpC = $roleC = "";

        switch($user['Role']['grade']){
            case 2:
                if ($user['Role']['id'] == DIVISIONMANAGER){
                    $divisionRegion = ClassRegistry::init('DivisionsRegion');
                    $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $user['division_id'])));
                    $rIds = implode(",", $rIds);
                    
				    $roleC = " AND c.user_id IN (SELECT id FROM users WHERE region_id IN ".$rIds.")";
                }
				break;
			case 3:
				$roleC = " AND c.user_id IN (SELECT id FROM users WHERE region_id = ".$user['region_id'].")";
				break;
			case 4:
				$roleC = " AND c.user_id IN (SELECT id FROM users WHERE depot_id = ".$user['depot_id'].")";
				break;
			case 5:
				$roleC = " AND (c.user_id = ".$user['id']." OR c.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = ".$user['id']."))";
				break;
			case 6:
			case 7:
				$roleC = " AND c.user_id = ".$user['id'];
				break;
		}

        if (!empty($params['query']['dv'])){
            if (empty($params['query']['rg'])) {
                $divisionRegion = ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $params['query']['dv'])));
                $rIds = implode(",", $rIds); //pr($rIds);exit;
                $dv_regC = " AND d.region_id IN ( " . $rIds . ") ";
            }

        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND d.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND c.depot_id = ".$params['query']['dp'];
        }
		
		$viaAppC = "";
		if (isset($params['query']['via_app']) && $params['query']['via_app']!='' ){
            $viaAppC = " AND c.via_app = ".$params['query']['via_app'];
        }

        // Check null depot id
        $ndpC = "AND c.depot_id != 0";

        $redistributorCreated = $this->query("SELECT SUM(c.cal_qty) as quantity FROM redistributor_saleitems c LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC $ndpC $roleC $viaAppC");

        $numberOfSale = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.cal_qty) as totSale FROM users u INNER JOIN redistributor_saleitems c ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC $ndpC $roleC $viaAppC GROUP BY c.user_id");

        $result['totSale'] = $redistributorCreated['0']['0']['quantity'];
        $result['userSale'] = $numberOfSale;

        return $result;
    }
    
    /**
     * totalAmountonPayment
     * @params : array
     * return array
     */
    public function totalAmountonPayment($params){
        //pr($params);
        $reportArr = array();
        $date = $params['date'];
        $result = array();
        switch($params['type']){
            case 'daily':
                $cC = "c.payment_date = '".$date."'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));

                $cC = "c.payment_date between '$d1' AND '$d2'";
                break;
            case 'between':
                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $cC = "c.payment_date between '$d1' AND '$d2'";
                break;

            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $cC = "c.payment_date between '$d1' AND '$d2'";

                break;
        }

        $dv_regC = $rgC = $dpC = "";
        if (!empty($params['query']['dv'])){
            if (empty($params['query']['rg'])) {
                $divisionRegion = ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $params['query']['dv'])));
                $rIds = implode(",", $rIds); //pr($rIds);exit;
                $dv_regC = " AND d.region_id IN ( " . $rIds . ") ";
            }

        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND d.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND c.depot_id = ".$params['query']['dp'];
        }

        //$totalAmountCreated = $this->query("SELECT SUM(c.amount) as amount FROM payments c LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC");
		
		$totalAmountCreated = $this->query("SELECT SUM(c.amount) as amount FROM payments c inner join users u on c.user_id=u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC");

        //$amountOfSale = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.amount) as totSale FROM payments c Left JOIN users u ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC GROUP BY c.user_id");
		
		 $amountOfSale = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.amount) as totSale FROM users u INNER JOIN payments c ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC GROUP BY c.user_id");

        $result['totSale'] = $totalAmountCreated['0']['0']['amount'];
        $result['userSale'] = $amountOfSale;

        return $result;
    }

    /**
     * totalExpenceAmountonSale
     * @params : array
     * return array
     */
    // public function totalExpenceAmounton($params){
    //     //pr($params);
    //     $reportArr = array();
    //     $date = $params['date'];
    //     $result = array();
    //     switch($params['type']){
    //         case 'daily':
    //             $cC = "c.exp_date = '".$date."'";
    //             break;
    //         case 'weekly':
    //             $d1 = date('Y-m-d', $params['strtotime']);
    //             $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));

    //             $cC = "c.exp_date between '$d1' AND '$d2'";
    //             break;
    //         case 'between':
    //             if(empty( $params['query']['from'])){
    //                 $d1 = date('Y-m-d');
    //             }else{
    //                 $d1 =  $params['query']['from'];
    //             }
    //             if(empty( $params['query']['to'])){
    //                 $d2 = date('Y-m-d');
    //             }else{
    //                 $d2 =  $params['query']['to'];
    //             }
    //             $cC = "c.exp_date between '$d1' AND '$d2'";
    //             break;
    //         case 'monthly':
    //             $d1 = date('Y-m-01', $params['strtotime']);
    //             $d2 = date('Y-m-t', $params['strtotime']);

    //             $cC = "c.exp_date between '$d1' AND '$d2'";

    //             break;
    //     }

    //     $dv_regC = $rgC = $dpC = "";
    //     if (!empty($params['query']['dv'])){
    //         if (empty($params['query']['rg'])) {
    //             $divisionRegion = ClassRegistry::init('DivisionsRegion');
    //             $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $params['query']['dv'])));
    //             $rIds = implode(",", $rIds); //pr($rIds);exit;
    //             $dv_regC = " AND d.region_id IN ( " . $rIds . ") ";
    //         }

    //     }
    //     if (!empty($params['query']['rg'])){
    //         $rgC = " AND d.region_id = ".$params['query']['rg'];
    //     }
    //     if (!empty($params['query']['dp'])){
    //         $dpC = " AND c.depot_id = ".$params['query']['dp'];
    //     }

    //     //$totalExpAmountCreated = $this->query("SELECT SUM(c.exp_amount) as amount FROM expenses c LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $rgC $dpC");
    //     $totalExpAmountCreated = $this->query("SELECT SUM(c.exp_amount) as amount FROM expenses c inner join users u on c.user_id=u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC");

    //     $amountOfExp = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.exp_amount) as totSale FROM users u INNER JOIN expenses c ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC GROUP BY c.user_id");

    //     $result['totSale'] = $totalExpAmountCreated['0']['0']['amount'];
    //     $result['userSale'] = $amountOfExp;

    //     return $result;
    // }
    
    public function totalExpenseAmount($params){
        //pr($params);
        $result = array();
		$type = $params['type'];
		$user = $params['user'];
        
		switch ($type) {
			case 'daily':
				$d1 = $params['date'];
				$cC = "c.exp_date = '".$d1."'";
			break;
			default:
				$d1 = $params['from'];
				$d2 = $params['to'];
				$cC = "c.exp_date between '$d1' AND '$d2'";
			break;					
		}

        $dv_regC = $rgC = $dpC = $roleC = "";

        switch($user['Role']['grade']){
            case 2:
                if ($user['Role']['id'] == DIVISIONMANAGER){
                    $divisionRegion = ClassRegistry::init('DivisionsRegion');
                    $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $user['division_id'])));
                    $rIds = implode(",", $rIds);
                    
				    $roleC = " AND c.user_id IN (SELECT id FROM users WHERE region_id IN ".$rIds.")";
                }
				break;
			case 3:
				$roleC = " AND c.user_id IN (SELECT id FROM users WHERE region_id = ".$user['region_id'].")";
				break;
			case 4:
				$roleC = " AND c.user_id IN (SELECT id FROM users WHERE depot_id = ".$user['depot_id'].")";
				break;
			case 5:
				$roleC = " AND (c.user_id = ".$user['id']." OR c.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = ".$user['id']."))";
				break;
			case 6:
			case 7:
				$roleC = " AND c.user_id = ".$user['id'];
				break;
		}

        if (!empty($params['query']['dv'])){
            if (empty($params['query']['rg'])) {
                $divisionRegion = ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields' => array('region_id'), 'conditions' => array('division_id' => $params['query']['dv'])));
                $rIds = implode(",", $rIds); //pr($rIds);exit;
                $dv_regC = " AND d.region_id IN ( " . $rIds . ") ";
            }

        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND d.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND c.depot_id = ".$params['query']['dp'];
        }

        //$totalExpAmountCreated = $this->query("SELECT SUM(c.exp_amount) as amount FROM expenses c LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $rgC $dpC");
        $totalExpAmountCreated = $this->query("SELECT SUM(c.exp_amount) as amount FROM expenses c inner join users u on c.user_id=u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC $roleC");

        $amountOfExp = $this->query("SELECT u.id, u.first_name, u.last_name, u.depot_id, SUM(c.exp_amount) as totSale FROM users u INNER JOIN expenses c ON c.user_id = u.id LEFT JOIN depots d ON c.depot_id = d.id WHERE $cC $dv_regC $rgC $dpC $roleC GROUP BY c.user_id");

        $result['totSale'] = $totalExpAmountCreated['0']['0']['amount'];
        $result['userSale'] = $amountOfExp;

        return $result;
    }
    
    /**
     * totalExpenceAmountonSale
     * @params : array
     * return array
     */
    // public function averevenueonSale($params){
    //     //pr($params);
    //     $reportArr = array();
    //     $date = $params['date'];
    //     $result = array();

    //     switch($params['type']){
    //         case 'daily':
    //             $cC = "Sale.sale_date = '".$date."'";
    //             break;
    //         case 'weekly':
    //             $d1 = date('Y-m-d', $params['strtotime']);
    //             $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));

    //             $cC = "Sale.sale_date between '$d1' AND '$d2'";
    //             break;
    //         case 'between':
    //             if(empty( $params['query']['from'])){
    //                 $d1 = date('Y-m-d');
    //             }else{
    //                 $d1 =  $params['query']['from'];
    //             }
    //             if(empty( $params['query']['to'])){
    //                 $d2 = date('Y-m-d');
    //             }else{
    //                 $d2 =  $params['query']['to'];
    //             }
    //             $cC = "Sale.sale_date between '$d1' AND '$d2'";
    //             break;
    //         case 'monthly':
    //             $d1 = date('Y-m-01', $params['strtotime']);
    //             $d2 = date('Y-m-t', $params['strtotime']);

    //             $cC = "Sale.sale_date between '$d1' AND '$d2'";

    //             break;
    //     }

    //     // Check null depot id
    //     $ndpC = "AND Sale.depot_id != 0";

    //     $totalSaleCreated = $this->query("SELECT SUM(cal_qty) as qty,SUM(amount) as amount FROM sales Sale WHERE $cC $ndpC");
    //     /* $totalRedistCreated = $this->query("SELECT SUM(cal_qty) as qty,SUM(amount) as amount FROM redistributor_saleitems c WHERE 1");

    //     $result['totSaleAmount'] = $totalSaleCreated['0']['0']['amount'] + $totalRedistCreated['0']['0']['amount'];
    //     $result['totSaleQty'] = $totalSaleCreated['0']['0']['qty'] + $totalRedistCreated['0']['0']['qty']; */

    //     $result['totSaleAmount'] = $totalSaleCreated['0']['0']['amount'];
    //     $result['totSaleQty'] = $totalSaleCreated['0']['0']['qty'];

    //     return $result;
    // }
    
    public function averevenueonSale($params){
        //pr($params);//die();
		$result = array();
		$type = $params['type'];
		$user = $params['user'];
		switch ($type) {
			case 'daily':
				$d1 = $params['date'];
				$cC = "c.sale_date = '".$d1."'";
			break;
			default:
				$d1 = $params['from'];
				$d2 = $params['to'];
				$cC = "c.sale_date between '$d1' AND '$d2'";
			break;					
		}
		
		$rgC = $dpC = $brdC = $usrC = $roleC = "";

		switch($user['Role']['grade']){
			case 3:
				$roleC = " AND c.user_id IN (SELECT id FROM users WHERE region_id = ".$user['region_id'].")";
				break;
			case 4:
				$roleC = " AND c.user_id IN (SELECT id FROM users WHERE depot_id = ".$user['depot_id'].")";
				break;
			case 5:
				$roleC = " AND (c.user_id = ".$user['id']." OR c.user_id IN (SELECT uid2 FROM user_relations WHERE user_id = ".$user['id']."))";
				break;
			case 6:
			case 7:
				$roleC = " AND c.user_id = ".$user['id'];
				break;
		}

		if (!empty($params['query']['rg'])){
			$rgC = " AND d.region_id = ".$params['query']['rg'];
		}
		if (!empty($params['query']['dp'])){
			$dpC = " AND c.depot_id = ".$params['query']['dp'];
		}
		if (!empty($params['query']['brd'])){
			$brdC = " AND c.brand_id = ".$params['query']['brd'];
		}
		if (!empty($params['query']['usr'])){
			$usrC = " AND c.user_id = ".$params['query']['usr'];
		}

        $totalSaleCreated = $this->query("SELECT SUM(cal_qty) as qty,SUM(amount) as amount FROM sales c WHERE $cC $rgC $dpC $brdC $usrC $roleC");
        /* $totalRedistCreated = $this->query("SELECT SUM(cal_qty) as qty,SUM(amount) as amount FROM redistributor_saleitems c WHERE 1");

        $result['totSaleAmount'] = $totalSaleCreated['0']['0']['amount'] + $totalRedistCreated['0']['0']['amount'];
        $result['totSaleQty'] = $totalSaleCreated['0']['0']['qty'] + $totalRedistCreated['0']['0']['qty']; */

        $result['totSaleAmount'] = $totalSaleCreated['0']['0']['amount'];
        $result['totSaleQty'] = $totalSaleCreated['0']['0']['qty'];

        return $result;
    }


    /**
     * totalNumberOfActiveCustomer
     * @params : array
     * return array
     */
    public function totalNumberOfActiveCustomer($params, &$paginate, &$conditions, &$customer, &$activeCust){
        //pr($params);
        $reportArr = array();
        $date = $params['date'];
        $result = array();
        switch($params['type']){
            case 'daily':
                $cC = "Order.order_date = '".$date."'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));
                $cC = "Order.order_date between '$d1' AND '$d2'";
                break;
            case 'between':
                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $cC = "Order.order_date between '$d1' AND '$d2'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);
                $cC = "Order.order_date between '$d1' AND '$d2'";
                break;
        }

        $customer->virtualFields['totPurchase'] = "SUM(Order.total)";
        $paginate['order'] = array("totPurchase" => "desc");


        $paginate['fields'] = array("Customer.id", "Customer.first_name", "Customer.last_name", "SUM(Order.total) as totPurchase");

        if (!empty($params['query']['dv'])){
            $conditions['Customer.division_id'] = $params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $conditions['Customer.region_id'] = $params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $conditions['Customer.depot_id'] = $params['query']['dp'];
        }

        $join=$paginate['joins'][] = array('table' => 'orders', 'type'=>'inner', 'alias'=>'Order', 'conditions'=>array("Customer.id=Order.customer_id AND $cC "));
        $paginate['limit'] = 50;
        $group=$paginate['group'] = array('Customer.id');

        if (!empty($this->request->query['export'])){
            $activeCust = $this->Customer->find('all',array('conditions'=>$conditions,'joins'=>$join,'group'=>$group));

        }

    }
    /**
     * totalExpenceAmountonSale
     * @params : array
     * return array
     */
    public function purchaseCustomer($params){
        //pr($params);
        $reportArr = array();
        $date = $params['date'];
        $result = array();
        switch($params['type']){
            case 'daily':
                $cC = "c.sale_date = '".$date."'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));

                $cC = "c.sale_date between '$d1' AND '$d2'";
                break;
            case 'between':
                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $cC = "c.sale_date between '$d1' AND '$d2'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $cC = "c.sale_date between '$d1' AND '$d2'";

                break;
        }


        $totalCountData = $this->query("SELECT SUM(c.cal_qty) as tot FROM sales c");
        $totalCountData2 = $this->query("SELECT COUNT(DISTINCT(c.customer_id)) as cust FROM sales c");

        if(isset($totalCountData['0']['0']['tot']))
            $result['totAmount'] = $totalCountData['0']['0']['tot'];

        if(isset($totalCountData2['0']['0']['cust']))
            $result['totCustomer'] = $totalCountData2['0']['0']['cust'];
        return $result;
    }


    /**
     * totalExpenceAmountonSale
     * @params : array
     * return array
     */
    public function avecostCase($params){

        $reportArr = array();
        //$date = $params['date'];
        $type = $params['type'];

        $result = array();
        
        switch ($type) {
			case 'daily':
				$date = $params['date'];
				$cC = "Sale.sale_date = '".$date."'";
                $eC = "Expense.exp_date = '".$date."'";
                $fiC = "FreeItem.sale_date = '".$date."'";
                $inC = "Incentive.incentive_date = '".$date."'";
			break;
			default:
				$d1 = $params['from'];
				$d2 = $params['to'];
				$cC = "Sale.sale_date between '$d1' AND '$d2'";
                $eC = "Expense.exp_date between '$d1' AND '$d2'";
                $fiC = "FreeItem.sale_date between '$d1' AND '$d2'";
                $inC = "Incentive.incentive_date between '$d1' AND '$d2'";
			break;					
		}
		

        // Check null depot id
        $ndpC = "AND Sale.depot_id != 0";
        //$ndpeC = "AND Expense.depot_id != 0";
        $ndpfiC = "AND FreeItem.depot_id != 0";
        $ndpinC = "AND Incentive.depot_id != 0";
        $totFi = $totInc = 0;
        
		$ndpeC = "";

        $totalSaleCreated = $this->query("SELECT SUM(cal_qty) as qty,SUM(amount) as amount FROM sales Sale WHERE $cC $ndpC");
        //$totalRedistCreated = $this->query("SELECT SUM(cal_qty) as qty,SUM(amount) as amount FROM redistributor_saleitems c WHERE 1");

        $totalExpense = $this->query("SELECT SUM(exp_amount) totExp FROM expenses Expense WHERE $eC $ndpeC ");

        if (!empty($params['join_incentive'])) {
            $totalIncAmt = $this->query("SELECT SUM(amount) totInc FROM incentives Incentive WHERE $inC $ndpinC");
            $result['totalIncentive'] = $totInc = $totalIncAmt['0']['0']['totInc'];
        }
        if(!empty($params['join_freeitem'])){
            $totalFiAmt = $this->query("SELECT SUM(amount) totFi FROM free_items FreeItem WHERE $fiC $ndpfiC");
            $result['totalFreeItem'] = $totFi = $totalFiAmt['0']['0']['totFi'];
        }
        $result['totalExpense'] = $totExp = $totalExpense['0']['0']['totExp'];
        
        //$fItemAmt = $incentiveAmt = 0;
        /** $freeItems = $this->query("SELECT brand_id, SUM(cal_qty) as totQty FROM free_items FreeItem GROUP BY brand_id");
        $incentives = $this->query("SELECT brand_id, SUM(cal_qty) as totQty FROM incentives Incentive GROUP BY brand_id"); **/


        /*if(!empty($freeItems)){
            foreach ($freeItems as $fi){
                if (!empty($fr['FreeItem']['brand_id'])){
                    if ($fr['FreeItem']['brand_id'] == 1){
                        $fItemAmt += 21000 * $fr['0']['totQty'];
                    }elseif($fr['FreeItem']['brand_id'] == 3){
                        $fItemAmt += 20000 * $fr['0']['totQty'];
                    }elseif($fr['FreeItem']['brand_id'] == 4){
                        $fItemAmt += 17500 * $fr['0']['totQty'];
                    } 

                    $fItemAmt += $brands[$fr['FreeItem']['brand_id']] * $fr['0']['totQty'];
                }
            }
        }

        if(!empty($incentives)){
            foreach ($incentives as $inc){
                if (!empty($inc['Incentive']['brand_id'])){
                    if ($inc['Incentive']['brand_id'] == 1){
                        $incentiveAmt += 21000 * $inc['0']['totQty'];
                    }elseif($inc['Incentive']['brand_id'] == 3){
                        $incentiveAmt += 20000 * $inc['0']['totQty'];
                    }elseif($inc['Incentive']['brand_id'] == 4){
                        $incentiveAmt += 17500 * $inc['0']['totQty'];
                    } 

                    $incentiveAmt += $brands[$inc['Incentive']['brand_id']] * $inc['0']['totQty'];
                }
            }
        }*/
        //$result['totSaleAmount'] = $totalSaleCreated['0']['0']['amount'] ;
        //$totalAmount = $totalExpense['0']['0']['totExp'] + $fItemAmt + $incentiveAmt;


        $result['totalAmount'] = $totExp + $totFi + $totInc;
        $result['totSaleQty'] = $totalSaleCreated['0']['0']['qty'];

        $result['aveCaseCost'] = 0;
        if ($result['totSaleQty'] > 0){
            $result['aveCaseCost'] = $result['totalAmount']  / $result['totSaleQty'];
        }

        return $result;
    }

    public function customer_status($cids=array(), $isAll=false){
        $sales_cond = 1;
        $visits_cond = 1;
        $rdsales_cond = 1;
        if(count($cids) > 0 && $isAll == false){
            $sales_cond = "o.customer_id IN (".implode(",", $cids).")";
            $visits_cond = "cv.customer_id IN (".implode(",", $cids).")";
            $rdsales_cond = "rs.customer_id IN (".implode(",", $cids).")";
        }
        $result = array();

        $customerSales = $this->query("SELECT o.customer_id, o.user_id, u.role_id FROM `orders` AS o INNER JOIN users as u ON o.user_id = u.id WHERE $sales_cond GROUP BY o.customer_id, o.user_id");
        if($customerSales){
            foreach ($customerSales as $customerSale){
                $cid = $customerSale['o']['customer_id'];
                $uid = $customerSale['o']['user_id'];
                $result[$cid]['sales'][$uid] = $customerSale['u']['role_id'];
            }
        }

        $customerVisits = $this->query("SELECT cv.customer_id, cv.user_id, u.role_id FROM `customer_visits` AS cv INNER JOIN users as u ON cv.user_id = u.id WHERE $visits_cond GROUP BY cv.customer_id, cv.user_id");
        if($customerVisits){
            foreach ($customerVisits as $customerVisit){
                $cid = $customerVisit['cv']['customer_id'];
                $uid = $customerVisit['cv']['user_id'];
                $result[$cid]['visits'][$uid] = $customerVisit['u']['role_id'];
            }
        }

        $customerRdSales = $this->query("SELECT rs.customer_id, rs.user_id, u.role_id FROM `redistributor_sales` AS rs INNER JOIN users as u ON rs.user_id = u.id WHERE $rdsales_cond GROUP BY rs.customer_id, rs.user_id");
        if($customerRdSales){
            foreach ($customerRdSales as $customerRdSale){
                $cid = $customerRdSale['rs']['customer_id'];
                $uid = $customerRdSale['rs']['user_id'];
                $result[$cid]['rdsales'][$uid] = $customerRdSale['u']['role_id'];
            }
        }

        return $result;
    }


    /**
     * routeCustNotvisitCond
     * @params : array
     * return array
     */
    public function routeCustNotvisitCond($params, &$paginate, &$conditions){
        //pr($params);
        $reportArr = array();
        $date = $params['date'];
        $result = array();
        switch($params['type']){
            case 'daily':
                $oC = "AND Order.order_date = '".$date."'";
                $cvC = "AND CustomerVisit.visiting_date LIKE '".$date."%'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));
                $oC = "AND Order.order_date between '$d1' AND '$d2'";
                $cvC = "AND CustomerVisit.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
            case 'between':
                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $oC = "AND Order.order_date between '$d1' AND '$d2'";
                $cvC = "AND CustomerVisit.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $oC = "AND Order.order_date between '$d1' AND '$d2'";
                $cvC = "AND CustomerVisit.visiting_date between '$d1' AND '$d2 23:59:59'";

                break;
        }

        if (!empty($params['query']['dv'])){
            $conditions['Customer.division_id'] = $params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $conditions['Customer.region_id'] = $params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $conditions['Customer.depot_id'] = $params['query']['dp'];
        }

        $paginate['paramType'] = 'querystring';

        //$paginate['joins'][] = array('table' => 'routes', 'type'=>'left', 'alias'=>'Route', 'conditions'=>array('Customer.route_id=Route.id'));
        $paginate['joins'][] = array('table' => 'orders', 'type'=>'left', 'alias'=>'Order', 'conditions'=>array('Customer.id=Order.customer_id '.$oC));

        //$paginate['joins'][] = array('table' => 'customer_visits', 'type'=>'left', 'alias'=>'CustomerVisit', 'conditions'=>array('Customer.id=CustomerVisit.customer_id '.$cvC));
        if(!empty($params['cvisityear_tables'])){
            if(count($params['cvisityear_tables'])>1){
                $cvisityear_tabSqlArray = array();
                foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                    $cvisityear_tabSqlArray[] = " ( SELECT * FROM $cv_tableName as CustomerVisit WHERE 1 $cvC )";
                }
                $cvisityear_tabSql = "( ".implode(" UNION ALL ", $cvisityear_tabSqlArray)." )"; // UNION operation For Multiple customer_visits table as per year wise organized

            }else{
                $cvisityear_tabSql = $params['cvisityear_tables'][key($params['cvisityear_tables'])]; // Single customer_visits table as per year wise organized
            }
            //pr($cvisityear_tabSql);
        }else{
            $cvisityear_tabSql ='customer_visits';
        }
        $paginate['joins'][] = array('table'=>$cvisityear_tabSql, 'alias'=>'CustomerVisit', 'type'=>'left', 'conditions'=>array('Customer.id=CustomerVisit.customer_id '.$cvC));
        if(!empty($params['isVisit']) && $params['isVisit'] == 1){
            $conditions['OR'] = array('Order.id IS NOT null', 'CustomerVisit.id IS NOT null');
        }else{
            $conditions['CustomerVisit.id'] = null;
            $conditions['Order.id'] = null;
        }
        $paginate['limit'] = 50;

    }

    // Time sheet
   /*  function dayUserCalls($params){
        $output = array();
        $date = $params['date'];
        $date1 = $date.' 06:00:00';
        $date2 = $date.' 23:59:59';
        switch($params['type']){
            case 'daily':
                //$oC = "o.order_date = '$date'";
                $toC = $oC =  "o.created LIKE '".$date."%'";
                $cotoC = $cooC =  "co.created LIKE '".$date."%'";
                //$rdC = "rs.sale_date = '$date'";
                $roC = $rdC =  "rs.created LIKE '".$date."%'";
                $croC = $crdC =  "crs.created LIKE '".$date."%'";
                $cvC = "cv.created LIKE '".$date."%'";
				$trk = "ut.tracking_time LIKE '".$date."%'";
                break;
            case 'between':

                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }

               
				$toC = $oC =  "o.created between '$d1' AND '$d2 23:59:59'";
                $cotoC = $cooC =  "co.created between '$d1' AND '$d2 23:59:59'";
                $roC = $rdC =  "rs.created between '$d1' AND '$d2 23:59:59'";
				
				$croC = $crdC = "crs.created between '$d1' AND '$d2 23:59:59'";
                $cvC = "cv.created between '$d1' AND '$d2 23:59:59'";
                $trk = "ut.tracking_time between '$d1' AND '$d2 23:59:59'";
				
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

				$toC = $oC =  "o.created between '$d1' AND '$d2 23:59:59'";
                $cotoC = $cooC =  "co.created between '$d1' AND '$d2 23:59:59'";
                $roC = $rdC =  "rs.created between '$d1' AND '$d2 23:59:59'";
				
				$croC = $crdC = "crs.created between '$d1' AND '$d2 23:59:59'";
                $cvC = "cv.created between '$d1' AND '$d2 23:59:59'";
                $trk = "ut.tracking_time between '$d1' AND '$d2 23:59:59'";
                break;
        }



        $where = $dvC = $rgC = $dpC = "";
        if (!empty($params['query']['dv'])){
            $where = "where ";
            $dvC = " AND u.division_id = ".$params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $where = "where ";
            $rgC = " AND u.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $where = "where ";
            $dpC = " AND u.depot_id = ".$params['query']['dp'];
        }

        $orderCount = $this->query("SELECT count(o.id) as oentry FROM orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC");

        $consorderCount = $this->query("SELECT count(o.id) as oentry FROM consumer_orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC");

        $rSaleCount = $this->query("SELECT count(rs.id) as rsentry FROM redistributor_sales rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC");

        $consrSaleCount = $this->query("SELECT count(rs.id) as rsentry FROM consumer_redistribution_orders rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC");

        //$visitCount = $this->query("SELECT count(cv.id) as ventry FROM customer_visits cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC");

        if(!empty($params['cvisityear_tables'])){
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                $visitCounts[$year] = $this->query("SELECT count(cv.id) as ventry FROM $cv_tableName cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC");
            }
        }

        $visitCount['0']['0']['ventry'] = 0;
        if (!empty($visitCounts)) {
            foreach ($visitCounts as $year => $visitCounti) {
                $visitCount['0']['0']['ventry'] += $visitCounti['0']['0']['ventry'];
            }
        }

        $totalCalls = $orderCount['0']['0']['oentry'] + $rSaleCount['0']['0']['rsentry'] + $consorderCount['0']['0']['oentry'] + $consrSaleCount['0']['0']['rsentry'] + $visitCount['0']['0']['ventry'];

        $result = array();

        $orderEntry1 = $this->query("SELECT sum(s.cal_qty) as oentry, count(DISTINCT s.order_id) as ocnt, o.user_id, u.first_name, u.last_name FROM orders o INNER JOIN users u ON u.id = o.user_id inner join sales s on s.order_id = o.id  WHERE $oC $dvC $rgC $dpC GROUP BY u.id");

        $consorderEntry1 = $this->query("SELECT sum(s.cal_qty) as oentry, count(DISTINCT s.consumer_order_id) as ocnt, o.user_id, u.first_name, u.last_name FROM consumer_orders o INNER JOIN users u ON u.id = o.user_id inner join consumer_sales s on s.consumer_order_id = o.id  WHERE $oC $dvC $rgC $dpC GROUP BY u.id");

        $rSaleEntry1 = $this->query("SELECT sum(rsi.cal_qty) as rsentry , count(DISTINCT rsi.redistributor_sale_id) as rscnt, rs.user_id, u.first_name, u.last_name FROM redistributor_sales rs INNER JOIN users u ON u.id = rs.user_id inner join redistributor_saleitems rsi on rsi.redistributor_sale_id = rs.id WHERE  $rdC $dvC $rgC $dpC GROUP BY u.id");

        $consrSaleEntry1 = $this->query("SELECT sum(rsi.cal_qty) as rsentry , count(DISTINCT rsi.consumer_redistribution_order_id) as rscnt, rs.user_id, u.first_name, u.last_name FROM consumer_redistribution_orders rs INNER JOIN users u ON u.id = rs.user_id inner join consumer_redistribution_sales rsi on rsi.consumer_redistribution_order_id = rs.id WHERE $rdC $dvC $rgC $dpC GROUP BY u.id");

       // $visitEntry1 = $this->query("SELECT count(u.id) as ventry, cv.user_id, u.first_name, u.last_name FROM customer_visits cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC GROUP BY u.id");
        if(!empty($params['cvisityear_tables'])){
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                $visitEntries1[$year] = $this->query("SELECT count(u.id) as ventry, cv.user_id, u.first_name, u.last_name FROM $cv_tableName cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC GROUP BY u.id");
            }
        }
//			pr($orderCount);pr($rSaleCount);pr($visitCount);
//		pr($orderEntry1);pr($rSaleEntry1);pr($visitEntry1);
        if ($orderEntry1){
            foreach ($orderEntry1 as $oe){
                $uid = $oe['o']['user_id'];
                $result[$uid]['orderEntry1'] = $oe;
                $result[$uid]['date'] = $date;
            }
        }

        if ($consorderEntry1){
            foreach ($consorderEntry1 as $oe){
                $uid = $oe['o']['user_id'];
                $result[$uid]['consorderEntry1'] = $oe;
                $result[$uid]['date'] = $date;
            }
        }

        if ($rSaleEntry1){
            foreach ($rSaleEntry1 as $rse){
                $uid = $rse['rs']['user_id'];
                $result[$uid]['rsEntry1'] = $rse;
                $result[$uid]['date'] = $date;
            }
        }

        if ($consrSaleEntry1){
            foreach ($consrSaleEntry1 as $rse){
                $uid = $rse['rs']['user_id'];
                $result[$uid]['consrSaleEntry1'] = $rse;
                $result[$uid]['date'] = $date;
            }
        }

      

        if (!empty($visitEntries1)) {
            foreach ($visitEntries1 as $year => $visitEntry1) {
                foreach ($visitEntry1 as $cve){
                    $uid = $cve['cv']['user_id'];
                    $result[$uid]['visitEntry1'] = $cve;
                    $result[$uid]['date'] = $date;
                }
            }
        }

        $orderEntry = $this->query("SELECT MIN(o.created)as in_time, MAX(o.created) as out_time , o.user_id, u.first_name, u.last_name FROM orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC GROUP BY u.id");//pr($orderEntry);

        $consorderEntry = $this->query("SELECT MIN(o.created)as in_time, MAX(o.created) as out_time , o.user_id, u.first_name, u.last_name FROM consumer_orders o INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC GROUP BY u.id");//pr($orderEntry);

        $rSaleEntry = $this->query("SELECT MIN(rs.created)as in_time, MAX(rs.created) as out_time , rs.user_id, u.first_name, u.last_name FROM redistributor_sales rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC GROUP BY u.id");

        $consrSaleEntry = $this->query("SELECT MIN(rs.created)as in_time, MAX(rs.created) as out_time , rs.user_id, u.first_name, u.last_name FROM consumer_redistribution_orders rs INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC GROUP BY u.id");

        //$visitEntry = $this->query("SELECT MIN(cv.created)as in_time, MAX(cv.created) as out_time ,  cv.user_id, u.first_name, u.last_name FROM customer_visits cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC GROUP BY u.id");

        //$gap_in_calls = $this->query("SELECT data.user_id ,data.dates as first_call, max(data1.dates) as second_call,timediff(data.dates,max(data1.dates)) as call_diff from (SELECT o.user_id, o.created as dates FROM `orders` o  WHERE $toC  UNION all SELECT co.user_id, co.created as dates FROM `consumer_orders` co  WHERE $cotoC  UNION all SELECT cv.user_id, cv.created  FROM customer_visits cv WHERE $cvC  UNION ALL select rs.user_id, rs.created from redistributor_sales rs WHERE $roC UNION ALL select crs.user_id, crs.created from consumer_redistribution_orders crs WHERE $croC) data , (SELECT o.user_id, o.created as dates FROM `orders` o  WHERE $toC UNION all SELECT co.user_id, co.created as dates FROM `consumer_orders` co  WHERE $cotoC UNION all SELECT cv.user_id, cv.created  FROM customer_visits cv WHERE $cvC UNION ALL select rs.user_id, rs.created from redistributor_sales rs WHERE $roC UNION ALL select crs.user_id, crs.created from consumer_redistribution_orders crs WHERE $croC ) data1 WHERE data.dates > data1.dates AND data.user_id = data1.user_id GROUP BY data.dates HAVING timediff(data.dates,max(data1.dates)) > '00:30:00' ORDER by data.dates DESC");
        if(!empty($params['cvisityear_tables'])){
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                $visitEntries[$year] = $this->query("SELECT MIN(cv.created)as in_time, MAX(cv.created) as out_time ,  cv.user_id, u.first_name, u.last_name FROM $cv_tableName cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC GROUP BY u.id");
                $gap_in_callsSel[$year] = $this->query("SELECT data.user_id ,data.dates as first_call, max(data1.dates) as second_call,timediff(data.dates,max(data1.dates)) as call_diff from (SELECT o.user_id, o.created as dates FROM `orders` o  WHERE $toC  UNION all SELECT co.user_id, co.created as dates FROM `consumer_orders` co  WHERE $cotoC  UNION all SELECT cv.user_id, cv.created  FROM $cv_tableName cv WHERE $cvC  UNION ALL select rs.user_id, rs.created from redistributor_sales rs WHERE $roC UNION ALL select crs.user_id, crs.created from consumer_redistribution_orders crs WHERE $croC) data , (SELECT o.user_id, o.created as dates FROM `orders` o  WHERE $toC UNION all SELECT co.user_id, co.created as dates FROM `consumer_orders` co  WHERE $cotoC UNION all SELECT cv.user_id, cv.created  FROM $cv_tableName cv WHERE $cvC UNION ALL select rs.user_id, rs.created from redistributor_sales rs WHERE $roC UNION ALL select crs.user_id, crs.created from consumer_redistribution_orders crs WHERE $croC ) data1 WHERE data.dates > data1.dates AND data.user_id = data1.user_id GROUP BY data.dates HAVING timediff(data.dates,max(data1.dates)) > '00:30:00' ORDER by data.dates DESC");
            }
        }


        if (!empty($gap_in_callsSel)) {
            foreach ($gap_in_callsSel as $year => $gap_in_calls) {
                foreach($gap_in_calls as $calls){
                    $firstcall = $calls['data']['first_call'];
                    $secondcall = $calls['0']['second_call'];
                    $uid = $calls['data']['user_id'];
                    $result[$uid]['GapInCalls'][] = array('firstcall' =>$firstcall,'secondcall' => $secondcall , 'time_diff' => $calls['0']['call_diff']);

                }
            }
        }

        // Difference between created and sync time data
        //$syncedTimediff = $this->query("SELECT data.cdate ,data.mdates , data.user_id , data.mdates - data.cdate as diff from ( SELECT o.user_id as user_id, o.created as cdate, o.modified as mdates FROM `orders` o WHERE $toC UNION all SELECT cv.user_id as user_id, cv.created as cdate, cv.modified as mdates FROM customer_visits cv WHERE $cvC UNION ALL select rs.user_id as user_id, rs.created as cdate, rs.modified as mdates from redistributor_sales rs WHERE $roC )data HAVING (data.mdates - data.cdate ) < '201'");

        // $syncedTimediff = $this->query("SELECT data.user_id ,data.dates as first_call, max(data1.dates) as second_call,timediff(data.dates,max(data1.dates)) as call_diff from (SELECT o.user_id, o.modified as dates FROM `orders` o  WHERE $toC  UNION all SELECT cv.user_id, cv.modified  FROM customer_visits cv WHERE $cvC  UNION ALL select rs.user_id, rs.modified from redistributor_sales rs WHERE $roC) data , (SELECT o.user_id, o.modified as dates FROM `orders` o  WHERE $toC   UNION all SELECT cv.user_id, cv.modified  FROM customer_visits cv WHERE $cvC   UNION ALL select rs.user_id, rs.modified from redistributor_sales rs WHERE $roC ) data1 WHERE data.dates > data1.dates AND data.user_id = data1.user_id GROUP BY data.dates HAVING timediff(data.dates,max(data1.dates)) < '00:02:00' ORDER by data.dates DESC");

        // if($syncedTimediff){
            // foreach($syncedTimediff as $calls){
                // $firstcall = $calls['data']['first_call'];
                // $secondcall = $calls['0']['second_call'];
                // $uid = $calls['data']['user_id'];
                // $result[$uid]['synchTime'][] = array('firstcall' =>$firstcall,'secondcall' => $secondcall , 'time_diff' => $calls['0']['call_diff']);
            // }
        // }
    
        $historyResult = $this->query("SELECT * from user_trackings ut where $trk order by tracking_time desc");
        if($historyResult ){
            foreach($historyResult as $history){//pr($history);
                $user_id = $history['ut']['user_id'];
                $trkData[$user_id][] = array('lat'=>  $history['ut']['lat'] , 'long' => $history['ut']['long'],'tracking_time' => $history['ut']['tracking_time'],'created' => $history['ut']['created'], 'modified' => $history['ut']['modified']   );
            }
            if(isset($trkData)){
                foreach($trkData as $uid => $trk){
                    $IntimeKey = max(array_keys($trk));
                    $outtimeKey = min(array_keys($trk));
                    $result[$uid]['IntimeData'] = $trk[$IntimeKey];
                    $result[$uid]['OuttimeData'] = $trk[$outtimeKey];

                }
            }

        }
        //pr($order);pr($rSale);pr($visit);
        //die();
        if ($orderEntry){
            foreach ($orderEntry as $oe){
                $uid = $oe['o']['user_id'];
                $result[$uid]['orderEntry']['o_in_time']  = date('H:i:s',strtotime($oe['0']['in_time']));
                $result[$uid]['orderEntry']['o_out_time']  = date('H:i:s',strtotime($oe['0']['out_time']));
                $result[$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
            }
        }

        if ($consorderEntry){
            foreach ($consorderEntry as $oe){
                $uid = $oe['o']['user_id'];
                $result[$uid]['orderEntry']['co_in_time']  = date('H:i:s',strtotime($oe['0']['in_time']));
                $result[$uid]['orderEntry']['co_out_time']  = date('H:i:s',strtotime($oe['0']['out_time']));
                $result[$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
            }
        }

        if ($rSaleEntry){
            foreach ($rSaleEntry as $rse){
                $uid = $rse['rs']['user_id'];
                $result[$uid]['orderEntry']['rs_in_time']  = date('H:i:s',strtotime($rse['0']['in_time']));
                $result[$uid]['orderEntry']['rs_out_time']  = date('H:i:s',strtotime($rse['0']['out_time']));
                $result[$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
            }
        }

        if ($consrSaleEntry){
            foreach ($consrSaleEntry as $rse){
                $uid = $rse['rs']['user_id'];
                $result[$uid]['orderEntry']['crs_in_time']  = date('H:i:s',strtotime($rse['0']['in_time']));
                $result[$uid]['orderEntry']['crs_out_time']  = date('H:i:s',strtotime($rse['0']['out_time']));
                $result[$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
            }
        }

        // if ($visitEntry){
            // foreach ($visitEntry as $cve){
                // $uid = $cve['cv']['user_id'];
                // $result[$uid]['orderEntry']['cv_in_time']  = date('H:i:s',strtotime($cve['0']['in_time']));
                // $result[$uid]['orderEntry']['cv_out_time']  = date('H:i:s',strtotime($cve['0']['out_time']));
                // $result[$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
            // }
        // }

        if (!empty($visitEntries)) {
            foreach ($visitEntries as $year => $visitEntry) {
                foreach ($visitEntry as $cve){
                    $uid = $cve['cv']['user_id'];
                    $result[$uid]['orderEntry']['cv_in_time']  = date('H:i:s',strtotime($cve['0']['in_time']));
                    $result[$uid]['orderEntry']['cv_out_time']  = date('H:i:s',strtotime($cve['0']['out_time']));
                    $result[$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                }
            }
        }

        $output['totalCalls'] = $totalCalls;
        $output['result'] = $result;
        //pr($output);
        return $output;
    } */
	
	function dayUserCalls($params){
        $output = array();
        $date = $params['date'];
        $date1 = $date.' 06:00:00';
        $date2 = $date.' 23:59:59';
        switch($params['type']){
            case 'daily':
                //$oC = "o.order_date = '$date'";
                $toC = $oC =  "o.created LIKE '".$date."%'";
                $cotoC = $cooC =  "co.created LIKE '".$date."%'";
                //$rdC = "rs.sale_date = '$date'";
                $roC = $rdC =  "rs.created LIKE '".$date."%'";
                $croC = $crdC =  "crs.created LIKE '".$date."%'";
                $cvC = "cv.created LIKE '".$date."%'";
				$trk = "ut.tracking_time LIKE '".$date."%'";
                break;
            case 'between':

                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }

               /** $oC = "o.order_date between '$d1' AND '$d2'";
                $rdC = "rs.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2'"; **/
				
				/* $toC = $oC =  'o.created BETWEEN "'.$d1.'" AND "'.$d2.'"';
                $cotoC = $cooC =  'co.created BETWEEN "'.$d1.'" AND "'.$d2.'"';
                $roC = $rdC =  'rs.created BETWEEN "'.$d1.'" AND "'.$d2.'"';
                $croC = $crdC =  'crs.created BETWEEN "'.$d1.'" AND "'.$d2.'"';
				$cvC = 'cv.created BETWEEN "'.$d1.'" AND "'.$d2.'"';
				$trk = 'ut.tracking_time BETWEEN "'.$d1.'" AND "'.$d2.'"'; */
				
				$toC = $oC =  "o.created between '$d1' AND '$d2 23:59:59'";
                $cotoC = $cooC =  "co.created between '$d1' AND '$d2 23:59:59'";
                $roC = $rdC =  "rs.created between '$d1' AND '$d2 23:59:59'";
				
				$croC = $crdC = "crs.created between '$d1' AND '$d2 23:59:59'";
                $cvC = "cv.created between '$d1' AND '$d2 23:59:59'";
                $trk = "ut.tracking_time between '$d1' AND '$d2 23:59:59'";
				
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                /* $oC = "o.order_date between '$d1' AND '$d2'";
                $rdC = "rs.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.created between '$d1' AND '$d2 23:59:59'"; */
				
				$toC = $oC =  "o.created between '$d1' AND '$d2 23:59:59'";
                $cotoC = $cooC =  "co.created between '$d1' AND '$d2 23:59:59'";
                $roC = $rdC =  "rs.created between '$d1' AND '$d2 23:59:59'";
				
				$croC = $crdC = "crs.created between '$d1' AND '$d2 23:59:59'";
                $cvC = "cv.created between '$d1' AND '$d2 23:59:59'";
                $trk = "ut.tracking_time between '$d1' AND '$d2 23:59:59'";
                break;
        }



        $where = $dvC = $rgC = $dpC = $rlC = "";
        if (!empty($params['query']['dv'])){
            $where = "where ";
            $dvC = " AND u.division_id = ".$params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $where = "where ";
            $rgC = " AND u.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $where = "where ";
            $dpC = " AND u.depot_id = ".$params['query']['dp'];
        }
		
		if (!empty($params['query']['r'])){
            $where = "where ";
            $rlC = " AND u.role_id = ".$params['query']['r'];
        }

        $result = array();
		
		$totalCalls['orderCount'] = $totalCalls['rsCount'] = $totalCalls['consOrderCount'] = $totalCalls['consRSaleCount'] = $totalCalls['visitCount'] = 0;
		
		$orderEntry = $this->query("SELECT sum(s.cal_qty) as oentry, count(DISTINCT s.order_id) as ocnt, MIN(o.created)as in_time, MAX(o.created) as out_time , o.user_id, u.first_name, u.last_name FROM orders o INNER JOIN sales s on s.order_id = o.id INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC $rlC GROUP BY u.id"); //pr('$orderEntry'); pr($orderEntry);
		
		if ($orderEntry){
            foreach ($orderEntry as $oe){
                $uid = $oe['o']['user_id'];
				$result[$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];                
                $result[$uid]['date'] = $date;
				$result[$uid]['callTime']['o_in_time']  = date('H:i:s',strtotime($oe['0']['in_time']));
                $result[$uid]['callTime']['o_out_time']  = date('H:i:s',strtotime($oe['0']['out_time']));
				$result[$uid]['orderEntry'] = $oe;
				
				$totalCalls['orderCount'] += $oe['0']['ocnt'];
            }
        }
		
		$consorderEntry = $this->query("SELECT sum(s.cal_qty) as oentry, count(DISTINCT s.consumer_order_id) as ocnt, MIN(o.created)as in_time, MAX(o.created) as out_time , o.user_id, u.first_name, u.last_name FROM consumer_orders o INNER JOIN consumer_sales s on s.consumer_order_id = o.id INNER JOIN users u ON u.id = o.user_id WHERE $oC $dvC $rgC $dpC $rlC GROUP BY u.id");

        if ($consorderEntry){
            foreach ($consorderEntry as $oe){
                $uid = $oe['o']['user_id'];
				$result[$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
				$result[$uid]['date'] = $date;
                $result[$uid]['callTime']['co_in_time']  = date('H:i:s',strtotime($oe['0']['in_time']));
                $result[$uid]['callTime']['co_out_time']  = date('H:i:s',strtotime($oe['0']['out_time']));
                $result[$uid]['consOrderEntry'] = $oe;
				
				$totalCalls['consOrderCount'] += $oe['0']['ocnt'];
            }
        }
		
		$rSaleEntry = $this->query("SELECT sum(rsi.cal_qty) as rsentry , count(DISTINCT rsi.redistributor_sale_id) as rscnt, MIN(rs.created)as in_time, MAX(rs.created) as out_time, rs.user_id, u.first_name, u.last_name FROM redistributor_sales rs INNER JOIN redistributor_saleitems rsi on rsi.redistributor_sale_id = rs.id INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC $rlC GROUP BY u.id");
		
		if ($rSaleEntry){
            foreach ($rSaleEntry as $rse){
                $uid = $rse['rs']['user_id'];
				$result[$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
                $result[$uid]['callTime']['rs_in_time']  = date('H:i:s',strtotime($rse['0']['in_time']));
                $result[$uid]['callTime']['rs_out_time']  = date('H:i:s',strtotime($rse['0']['out_time']));
                $result[$uid]['date'] = $date;
				$result[$uid]['rsEntry'] = $rse;
				
				$totalCalls['rsCount'] += $rse['0']['rscnt'];
            }
        }
		
		$consrSaleEntry = $this->query("SELECT sum(rsi.cal_qty) as rsentry , count(DISTINCT rsi.consumer_redistribution_order_id) as rscnt, MIN(rs.created)as in_time, MAX(rs.created) as out_time, rs.user_id, u.first_name, u.last_name FROM consumer_redistribution_orders rs INNER JOIN consumer_redistribution_sales rsi on rsi.consumer_redistribution_order_id = rs.id INNER JOIN users u ON u.id = rs.user_id WHERE $rdC $dvC $rgC $dpC $rlC GROUP BY u.id");
		
		if ($consorderEntry){
            foreach ($consorderEntry as $oe){
                $uid = $oe['o']['user_id'];
				$result[$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
                $result[$uid]['callTime']['co_in_time']  = date('H:i:s',strtotime($oe['0']['in_time']));
                $result[$uid]['callTime']['co_out_time']  = date('H:i:s',strtotime($oe['0']['out_time']));
                $result[$uid]['date'] = $date;
				$result[$uid]['consRSaleEntry'] = $rse;
				
				$totalCalls['consRSaleCount'] += $rse['0']['rscnt'];
            }
        }
		
		if(!empty($params['cvisityear_tables'])){
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
				$visitEntries[$year] = $this->query("SELECT count(u.id) as ventry, MIN(cv.created)as in_time, MAX(cv.created) as out_time ,cv.user_id, u.first_name, u.last_name FROM $cv_tableName cv INNER JOIN users u ON u.id = cv.user_id WHERE $cvC $dvC $rgC $dpC $rlC GROUP BY u.id");
                
				$gap_in_callsSel[$year] = $this->query("SELECT data.user_id ,data.dates as first_call, max(data1.dates) as second_call,timediff(data.dates,max(data1.dates)) as call_diff from (SELECT o.user_id, o.created as dates FROM `orders` o  WHERE $toC  UNION all SELECT co.user_id, co.created as dates FROM `consumer_orders` co  WHERE $cotoC  UNION all SELECT cv.user_id, cv.created  FROM $cv_tableName cv WHERE $cvC  UNION ALL select rs.user_id, rs.created from redistributor_sales rs WHERE $roC UNION ALL select crs.user_id, crs.created from consumer_redistribution_orders crs WHERE $croC) data , (SELECT o.user_id, o.created as dates FROM `orders` o  WHERE $toC UNION all SELECT co.user_id, co.created as dates FROM `consumer_orders` co  WHERE $cotoC UNION all SELECT cv.user_id, cv.created  FROM $cv_tableName cv WHERE $cvC UNION ALL select rs.user_id, rs.created from redistributor_sales rs WHERE $roC UNION ALL select crs.user_id, crs.created from consumer_redistribution_orders crs WHERE $croC ) data1 WHERE data.dates > data1.dates AND data.user_id = data1.user_id GROUP BY data.dates HAVING timediff(data.dates,max(data1.dates)) > '00:30:00' ORDER by data.dates DESC");
            }
        }
		
		if (!empty($visitEntries)) {
            foreach ($visitEntries as $year => $visitEntry) {
                foreach ($visitEntry as $cve){
                    $uid = $cve['cv']['user_id'];
					$result[$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                    $result[$uid]['callTime']['cv_in_time']  = date('H:i:s',strtotime($cve['0']['in_time']));
                    $result[$uid]['callTime']['cv_out_time']  = date('H:i:s',strtotime($cve['0']['out_time']));
					$result[$uid]['date'] = $date;
                    $result[$uid]['visitEntry'] = $cve;
					
					$totalCalls['visitCount'] += $cve['0']['ventry'];                  
                }
            }
        }
		
		$totalCalls['count'] = $totalCalls['orderCount'] + $totalCalls['rsCount'] + $totalCalls['consOrderCount'] + $totalCalls['consRSaleCount'] + $totalCalls['visitCount'];
		
		if (!empty($gap_in_callsSel)) {
            foreach ($gap_in_callsSel as $year => $gap_in_calls) {
                foreach($gap_in_calls as $calls){
                    $firstcall = $calls['data']['first_call'];
                    $secondcall = $calls['0']['second_call'];
                    $uid = $calls['data']['user_id'];
                    $result[$uid]['GapInCalls'][] = array('firstcall' =>$firstcall,'secondcall' => $secondcall , 'time_diff' => $calls['0']['call_diff']);

                }
            }
        }

        // Difference between created and sync time data
        //$syncedTimediff = $this->query("SELECT data.cdate ,data.mdates , data.user_id , data.mdates - data.cdate as diff from ( SELECT o.user_id as user_id, o.created as cdate, o.modified as mdates FROM `orders` o WHERE $toC UNION all SELECT cv.user_id as user_id, cv.created as cdate, cv.modified as mdates FROM customer_visits cv WHERE $cvC UNION ALL select rs.user_id as user_id, rs.created as cdate, rs.modified as mdates from redistributor_sales rs WHERE $roC )data HAVING (data.mdates - data.cdate ) < '201'");

        /*$syncedTimediff = $this->query("SELECT data.user_id ,data.dates as first_call, max(data1.dates) as second_call,timediff(data.dates,max(data1.dates)) as call_diff from (SELECT o.user_id, o.modified as dates FROM `orders` o  WHERE $toC  UNION all SELECT cv.user_id, cv.modified  FROM customer_visits cv WHERE $cvC  UNION ALL select rs.user_id, rs.modified from redistributor_sales rs WHERE $roC) data , (SELECT o.user_id, o.modified as dates FROM `orders` o  WHERE $toC   UNION all SELECT cv.user_id, cv.modified  FROM customer_visits cv WHERE $cvC   UNION ALL select rs.user_id, rs.modified from redistributor_sales rs WHERE $roC ) data1 WHERE data.dates > data1.dates AND data.user_id = data1.user_id GROUP BY data.dates HAVING timediff(data.dates,max(data1.dates)) < '00:02:00' ORDER by data.dates DESC");

        if($syncedTimediff){
            foreach($syncedTimediff as $calls){
                $firstcall = $calls['data']['first_call'];
                $secondcall = $calls['0']['second_call'];
                $uid = $calls['data']['user_id'];
                $result[$uid]['synchTime'][] = array('firstcall' =>$firstcall,'secondcall' => $secondcall , 'time_diff' => $calls['0']['call_diff']);

            }
        }
    */
        $historyResult = $this->query("SELECT * from user_trackings ut where $trk order by tracking_time desc");
        if($historyResult ){
            foreach($historyResult as $history){//pr($history);
                $user_id = $history['ut']['user_id'];
                $trkData[$user_id][] = array('lat'=>  $history['ut']['lat'] , 'long' => $history['ut']['long'],'tracking_time' => $history['ut']['tracking_time'],'created' => $history['ut']['created'], 'modified' => $history['ut']['modified']   );
            }
            if(isset($trkData)){
                foreach($trkData as $uid => $trk){
                    $IntimeKey = max(array_keys($trk));
                    $outtimeKey = min(array_keys($trk));
                    $result[$uid]['IntimeData'] = $trk[$IntimeKey];
                    $result[$uid]['OuttimeData'] = $trk[$outtimeKey];

                }
            }

        }
        //pr($order);pr($rSale);pr($visit);
        //die();
       

        $output['totalCalls'] = $totalCalls['count'];
        $output['result'] = $result;
        //pr($output); //die();
        return $output;
    }

    public function syncCalls($params){
        $output = array();
        $date = $params['date'];
        $date1 = $date.' 06:00:00';
        $date2 = $date.' 23:59:59';
        switch($params['type']){
            case 'daily':
                //$oC = "o.order_date = '$date'";
                $oC =  "o.modified LIKE '".$date."%'";
                $coC =  "co.modified LIKE '".$date."%'";
                $rdC =  "rs.modified LIKE '".$date."%'";
                $cvC = "cv.modified LIKE '".$date."%'";
                break;
				
			case 'between':

                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $oC =  'o.modified BETWEEN "'.$d1.'" AND "'.$d2.'"';
                $coC =  'co.modified BETWEEN "'.$d1.'" AND "'.$d2.'"';
                $rdC =  'rs.modified BETWEEN "'.$d1.'" AND "'.$d2.'"';
                $cvC = 'cv.modified BETWEEN "'.$d1.'" AND "'.$d2.'"';

                break;
        }

        $where = $rgC = $dpC = "";
        if (!empty($params['query']['dv'])){
            $where = "where ";
            $dvC = " AND u.division_id = ".$params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $where = "where ";
            $rgC = " AND u.region_id = ".$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $where = "where ";
            $dpC = " AND u.depot_id = ".$params['query']['dp'];
        }
        $result = array();
        $osycn = $this->query("SELECT min(o.modified) as date,  UNIX_TIMESTAMP(o.modified) DIV 120 as timestamp, o.user_id as user_id, count(o.id) as cnt , sum(s.quantity) as qty FROM orders o INNER JOIN sales s on s.order_id = o.id WHERE $oC GROUP BY  UNIX_TIMESTAMP(o.modified) DIV 120, o.user_id having cnt >= 2");

        if($osycn){
            foreach($osycn as $call){
                $first_call = $call['0']['date'];
                $uid = $call['o']['user_id'];
                $second_call = date("Y-m-d H:i:s",strtotime($first_call." +2 minutes"));
                $result[$uid]['oSync'][] = array('first_call' => $first_call , 'second_call' => $second_call,'ocount' => $call['0']['cnt'], 'qty' => $call['0']['qty']);
            }
        }

        $cosycn = $this->query("SELECT min(co.modified) as date,  UNIX_TIMESTAMP(co.modified) DIV 120 as timestamp, co.user_id as user_id, count(co.id) as cnt , sum(cs.quantity) as qty FROM consumer_orders co INNER JOIN consumer_sales cs on cs.consumer_order_id = co.id WHERE $coC GROUP BY  UNIX_TIMESTAMP(co.modified) DIV 120, co.user_id having cnt >= 2");

        if($cosycn){
            foreach($cosycn as $call){
                $first_call = $call['0']['date'];
                $uid = $call['co']['user_id'];
                $second_call = date("Y-m-d H:i:s",strtotime($first_call." +2 minutes"));
                $result[$uid]['coSync'][] = array('first_call' => $first_call , 'second_call' => $second_call,'cocount' => $call['0']['cnt'], 'qty' => $call['0']['qty']);
            }
        }


        //$cvsycn = $this->query("SELECT min(cv.modified) as date,  UNIX_TIMESTAMP(cv.modified) DIV 120 as timestamp, cv.user_id , count(cv.id) as cnt FROM customer_visits cv WHERE $cvC GROUP BY  UNIX_TIMESTAMP(cv.modified) DIV 120, cv.user_id having cnt >= 2");
        if(!empty($params['cvisityear_tables'])){
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                $cvsycns[$year] = $this->query("SELECT min(cv.modified) as date,  UNIX_TIMESTAMP(cv.modified) DIV 120 as timestamp, cv.user_id , count(cv.id) as cnt FROM $cv_tableName cv WHERE $cvC GROUP BY  UNIX_TIMESTAMP(cv.modified) DIV 120, cv.user_id HAVING cnt >=2");
            }
        }

        /*if($cvsycn){
            foreach($cvsycn as $call){
                $first_call = $call['0']['date'];
                $uid = $call['cv']['user_id'];
                $second_call = date("Y-m-d H:i:s",strtotime($first_call." +2 minutes"));
                $result[$uid]['cvSync'][] = array('first_call' => $first_call , 'second_call' => $second_call,'ocount' => $call['0']['cnt']);
            }
        }*/

        if (!empty($cvsycns)) {
            foreach ($cvsycns as $year => $cvsycn) {
                foreach ($cvsycn as $call) {
                    $first_call = $call['0']['date'];
                    $uid = $call['cv']['user_id'];
                    $second_call = date("Y-m-d H:i:s", strtotime($first_call . " +2 minutes"));
                    $result[$uid]['cvSync'][] = array('first_call' => $first_call, 'second_call' => $second_call, 'ocount' => $call['0']['cnt']);
                }
            }
        }

        $rssycn = $this->query("SELECT min(rs.modified) as date,  UNIX_TIMESTAMP(rs.modified) DIV 120 as timestamp, rs.user_id as user_id, count(rs.id) as cnt , sum(rsi.quantity) as qty FROM redistributor_sales rs  INNER JOIN redistributor_saleitems rsi on rsi.redistributor_sale_id = rs.id  WHERE $rdC GROUP BY  UNIX_TIMESTAMP(rs.modified) DIV 120, rs.user_id having cnt >= 2");

        if($rssycn){
            foreach($rssycn as $call){
                $first_call = $call['0']['date'];
                $uid = $call['rs']['user_id'];
                $second_call = date("Y-m-d H:i:s",strtotime($first_call." +2 minutes"));
                $result[$uid]['rsSync'][] = array('first_call' => $first_call , 'second_call' => $second_call,'ocount' => $call['0']['cnt'] ,'qty' => $call['0']['qty']);
            }
        }

        $crssycn = $this->query("SELECT min(rs.modified) as date,  UNIX_TIMESTAMP(rs.modified) DIV 120 as timestamp, rs.user_id as user_id, count(rs.id) as cnt , sum(rsi.quantity) as qty FROM consumer_redistribution_orders rs  INNER JOIN consumer_redistribution_sales rsi on rsi.consumer_redistribution_order_id = rs.id  WHERE $rdC GROUP BY  UNIX_TIMESTAMP(rs.modified) DIV 120, rs.user_id having cnt >= 2");

        if($crssycn){
            foreach($crssycn as $call){
                $first_call = $call['0']['date'];
                $uid = $call['rs']['user_id'];
                $second_call = date("Y-m-d H:i:s",strtotime($first_call." +2 minutes"));
                $result[$uid]['crsSync'][] = array('first_call' => $first_call , 'second_call' => $second_call,'ocount' => $call['0']['cnt'] ,'qty' => $call['0']['qty']);
            }
        }

        $output['totalCalls'] = count($osycn) + count($cosycn)+ count($cvsycn) + count($rssycn)+ count($crssycn);
        $output['result'] = $result;
        return $output;
    }

    public function mwddepotsales($params, &$depots){
        $d1=$params['d1'] ;
        $d2=$params['d2'] ;

        $dv_reg_dpC = "1";
        if (!empty($params['dv'])){
            if (empty($params['rg']) && empty($params['dp'])) {
                $divisionRegion=  ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields'=>array('region_id'),'conditions'=>array('division_id'=>$params['dv'])));
                $rIds = implode(",",$rIds); //pr($rIds);exit;
                $dv_reg_dpC .= " AND Depot.region_id IN ( ".$rIds.") ";

            }
        }
        if (!empty($params['rg'])){
            $dv_reg_dpC .= " AND Depot.region_id = ".$params['rg'];
        }
        if (!empty($params['dp'])){
            $dv_reg_dpC .= " AND Depot.id = ".$params['dp'];
        }
        //sale
        //$saleQry = "SELECT `Depot`.`id`, `Depot`.`title`, IFNULL(SUM(`Sale`.`cal_qty`),0) AS total_sale, `Sale`.`sale_date` FROM depots AS Depot left JOIN `sales` AS `Sale` ON (`Depot`.`id` = `Sale`.`depot_id` AND Sale.sale_date between '$d1' AND '$d2') GROUP BY `Depot`.`id`,`Sale`.`sale_date` ORDER BY `Depot`.`title` asc";
        $saleQry = "SELECT `Depot`.`id`, `Depot`.`title`, IFNULL(SUM(`Sale`.`cal_qty`),0) AS total_sale, `Sale`.`sale_date` FROM depots AS Depot left JOIN `sales` AS `Sale` ON (`Depot`.`id` = `Sale`.`depot_id` AND Sale.sale_date between '$d1' AND '$d2') WHERE $dv_reg_dpC GROUP BY `Depot`.`id`,`Sale`.`sale_date` ORDER BY `Depot`.`title` asc";
        $sales = $this->query($saleQry);
        $results = array();
        if($sales){
            foreach($sales as $sale){
                $sdid = $sale['Depot']['id'];
                $sdn = $sale['Depot']['title'];
                $sbid = $sale['Sale']['sale_date'];
                $results[$sdid]['sales']['depot_id'] = $sdid;
                $results[$sdid]['sales']['depot_name'] = $sdn;
                if(!empty($sbid)){
                    $sbid = date('Y-m-d', strtotime($sbid));
                    $results[$sdid]['sales']['sale_date'][$sbid] = array('total_qty'=> $sale['0']['total_sale']);
                }
            }
        }

        //consumer sale
        //$consaleQry = "SELECT `Depot`.`id`, `Depot`.`title`, IFNULL(SUM(`Sale`.`cal_qty`),0) AS total_sale, `Sale`.`sale_date` FROM depots AS Depot left JOIN `consumer_sales` AS `Sale` ON (`Depot`.`id` = `Sale`.`depot_id` AND Sale.sale_date between '$d1' AND '$d2') GROUP BY `Depot`.`id`,`Sale`.`sale_date` ORDER BY `Depot`.`title` asc";
        $consaleQry = "SELECT `Depot`.`id`, `Depot`.`title`, IFNULL(SUM(`Sale`.`cal_qty`),0) AS total_sale, `Sale`.`sale_date` FROM depots AS Depot left JOIN `consumer_sales` AS `Sale` ON (`Depot`.`id` = `Sale`.`depot_id` AND Sale.sale_date between '$d1' AND '$d2') WHERE $dv_reg_dpC GROUP BY `Depot`.`id`,`Sale`.`sale_date` ORDER BY `Depot`.`title` asc";
        $consales = $this->query($consaleQry);

        if($consales){
            foreach($consales as $sale){
                $sdid = $sale['Depot']['id'];
                $sdn = $sale['Depot']['title'];
                $sbid = $sale['Sale']['sale_date'];
                $results[$sdid]['consales']['depot_id'] = $sdid;
                $results[$sdid]['consales']['depot_name'] = $sdn;
                if(!empty($sbid)){
                    $sbid = date('Y-m-d', strtotime($sbid));
                    $results[$sdid]['consales']['sale_date'][$sbid] = array('total_qty'=> $sale['0']['total_sale']);
                }
            }
        }

        //Rsale
        /* $rdsaleQry = "SELECT `Depot`.`id`, `Depot`.`title`, IFNULL(SUM(`redistributor_saleitems`.`cal_qty`),0) AS total_sale, `redistributor_saleitems`.`sale_date` FROM `depots` AS `Depot` left JOIN `redistributor_saleitems` AS `redistributor_saleitems` ON (`Depot`.`id` = `redistributor_saleitems`.`depot_id` AND redistributor_saleitems.sale_date between '$d1' AND '$d2') GROUP BY `Depot`.`id`,`redistributor_saleitems`.`sale_date` ORDER BY `Depot`.`title` asc";
        $rdsales = $this->query($rdsaleQry);

        if($rdsales){
            foreach($rdsales as $rdsale){
                $rsdid = $rdsale['Depot']['id'];
                $rsdn = $rdsale['Depot']['title'];
                $rsbid = $rdsale['redistributor_saleitems']['sale_date'];
                $results[$rsdid]['rdsales']['depot_id'] = $rsdid;
                $results[$rsdid]['rdsales']['depot_name'] = $rsdn;
                if(!empty($rsbid)){
                    $rsbid = date('Y-m-d', strtotime($rsbid));
                    $results[$rsdid]['rdsales']['sale_date'][$rsbid] = array('total_qty'=> $rdsale['0']['total_sale']);
                }
            }
        }


        //Consumer Rsale
        $conrdsaleQry = "SELECT `Depot`.`id`, `Depot`.`title`, IFNULL(SUM(`redistributor_saleitems`.`cal_qty`),0) AS total_sale, `redistributor_saleitems`.`sale_date` FROM `depots` AS `Depot` left JOIN `consumer_redistribution_sales` AS `redistributor_saleitems` ON (`Depot`.`id` = `redistributor_saleitems`.`depot_id` AND redistributor_saleitems.sale_date between '$d1' AND '$d2') GROUP BY `Depot`.`id`,`redistributor_saleitems`.`sale_date` ORDER BY `Depot`.`title` asc";
        $conrdsales = $this->query($conrdsaleQry);

        if($conrdsales){
            foreach($conrdsales as $rdsale){
                $rsdid = $rdsale['Depot']['id'];
                $rsdn = $rdsale['Depot']['title'];
                $rsbid = $rdsale['redistributor_saleitems']['sale_date'];
                $results[$rsdid]['conrdsales']['depot_id'] = $rsdid;
                $results[$rsdid]['conrdsales']['depot_name'] = $rsdn;
                if(!empty($rsbid)){
                    $rsbid = date('Y-m-d', strtotime($rsbid));
                    $results[$rsdid]['conrdsales']['sale_date'][$rsbid] = array('total_qty'=> $rdsale['0']['total_sale']);
                }
            }
        } */

        $d2 = date("Y-m-d", strtotime("+1 day", strtotime($d2)) );
        foreach($results as $key=>$result){
            $depotid = $result['sales']['depot_id'];
            $begin = new DateTime($d1);
            $end = new DateTime($d2);
            $interval = DateInterval::createFromDateString('1 day');
            $period = new DatePeriod($begin, $interval, $end);
            foreach ( $period as $dt ){
                $i = $dt->format( "Y-m-d" );

                //HERE total_sale = Sale + Consumer Sale
                $results[$key]['total_sale']['sale_date'][$i]['total_qty'] = 0;

                if(!empty($result['sales']['sale_date'][$i])){

                    $results[$key]['total_sale']['sale_date'][$i]['total_qty'] += $result['sales']['sale_date'][$i]['total_qty'] ;
                }

                /* if(!empty($result['rdsales']['sale_date'][$i])){

                    $results[$key]['total_sale']['sale_date'][$i]['total_qty'] += $result['rdsales']['sale_date'][$i]['total_qty'] ;
                } */

                if(!empty($result['consales']['sale_date'][$i])){

                    $results[$key]['total_sale']['sale_date'][$i]['total_qty'] += $result['consales']['sale_date'][$i]['total_qty'] ;
                }

                /* if(!empty($result['conrdsales']['sale_date'][$i])){

                    $results[$key]['total_sale']['sale_date'][$i]['total_qty'] += $result['conrdsales']['sale_date'][$i]['total_qty'] ;
                } */

                /* if(isset($result['sales']['sale_date'][$i]) && isset($result['rdsales']['sale_date'][$i])){
                    $results[$key]['sale_redis_add']['sale_date'][$i]['total_qty'] = $result['sales']['sale_date'][$i]['total_qty']+ $result['rdsales']['sale_date'][$i]['total_qty'];
                }
                else{
                    if(isset($result['sales']['sale_date'][$i])){
                        $results[$key]['sale_redis_add']['sale_date'][$i]['total_qty'] = $result['sales']['sale_date'][$i]['total_qty'] ;
                    }
                    if(isset($result['rdsales']['sale_date'][$i])){
                        $results[$key]['sale_redis_add']['sale_date'][$i]['total_qty'] = $result['rdsales']['sale_date'][$i]['total_qty'] ;
                    }
                }*/
            }
        }
        return $results;
    }

    public function summary_reports($params, &$depots){
        //pr($params);
        $result = array();
        $sale_cond = "1";
        $rdsale_cond = "1";
        $payment_cond = "1";
        $expense_cond = "1";
		
		$userNotEmptyCond = " AND user_id != 0";

        if(!empty($params['d1']) && !empty($params['d2'])){
            $sale_cond .= " AND sale_date between \"".$params['d1']."\" AND \"".$params['d2']." 23:59:59\"";
            $rdsale_cond .= " AND sale_date between \"".$params['d1']."\" AND \"".$params['d2']." 23:59:59\"";
            $payment_cond .= " AND payment_date between \"".$params['d1']."\" AND \"".$params['d2']." 23:59:59\"";
            $expense_cond .= " AND exp_date between \"".$params['d1']."\" AND \"".$params['d2']." 23:59:59\"";
        }

        if(!empty($params['br'])){
            $sale_cond .= " AND brand_group_id = ".$params['br'];
            $rdsale_cond .= " AND brand_group_id = ".$params['br'];
            $payment_cond .= " AND brand_group_id = ".$params['br'];
            $expense_cond .= " AND brand_group_id = ".$params['br'];
        }


        if(!empty($params['sts'])){
            $sale_cond .= " AND status = ".$params['sts'];
            $rdsale_cond .= " AND status = ".$params['sts'];
            $payment_cond .= " AND status = ".$params['sts'];
            $expense_cond .= " AND status = ".$params['sts'];
        }

        $saleQry = "SELECT depot_id, brand_id, brand_group_id, SUM(cal_qty) AS total_qty, SUM(amount) AS total_amt FROM sales AS Sale WHERE $sale_cond GROUP BY depot_id, brand_group_id";
        $sales = $this->query($saleQry);

        if($sales){
            foreach($sales as $sale){
                $sdid = $sale['Sale']['depot_id'];
                $sbid = $sale['Sale']['brand_group_id'];
                $result[$sdid]['sales']['brand'][$sbid] = array('total_qty'=> $sale['0']['total_qty'],'total_amt'=> $sale['0']['total_amt']);
                if (isset($result[$sdid]['sales']['sales_value'])){
                    $result[$sdid]['sales']['sales_value'] = $result[$sdid]['sales']['sales_value']+$sale['0']['total_amt'];
                }else{
                    $result[$sdid]['sales']['sales_value'] = !empty($sale['0']['total_amt'])?$sale['0']['total_amt']:0;
                }
            }
        }

        $conssaleQry = "SELECT depot_id, brand_id, brand_group_id, SUM(cal_qty) AS total_qty, SUM(amount) AS total_amt FROM consumer_sales AS Sale WHERE $sale_cond GROUP BY depot_id, brand_group_id";
        $conssales = $this->query($conssaleQry);

        if($conssales){
            foreach($conssales as $sale){
                $sdid = $sale['Sale']['depot_id'];
                $sbid = $sale['Sale']['brand_group_id'];
                /* $result[$sdid]['conssales']['brand'][$sbid] = array('total_qty'=> $sale['0']['total_qty'],'total_amt'=> $sale['0']['total_amt']);

                if (isset($result[$sdid]['conssales']['sales_value'])){
                    $result[$sdid]['conssales']['sales_value'] = $result[$sdid]['conssales']['sales_value']+$sale['0']['total_amt'];
                }else{
                    $result[$sdid]['conssales']['sales_value'] = !empty($sale['0']['total_amt'])?$sale['0']['total_amt']:0;
                }
                */

                if(!empty($result[$sdid]['sales']['brand'][$sbid]['total_qty'])){
                    $result[$sdid]['sales']['brand'][$sbid]['total_qty'] += $sale['0']['total_qty'];
                }else{
                    $result[$sdid]['sales']['brand'][$sbid]['total_qty'] = $sale['0']['total_qty'];
                }

                if(!empty($result[$sdid]['sales']['brand'][$sbid]['total_amt'])){
                    $result[$sdid]['sales']['brand'][$sbid]['total_amt'] += $sale['0']['total_amt'];
                }else{
                    $result[$sdid]['sales']['brand'][$sbid]['total_amt'] = $sale['0']['total_amt'];
                }

                if(!empty($result[$sdid]['sales']['sales_value'])){
                    $result[$sdid]['sales']['sales_value'] += $sale['0']['total_amt'];
                }else{
                    $result[$sdid]['sales']['sales_value'] = !empty($sale['0']['total_amt'])?$sale['0']['total_amt']:0;
                }
            }
        }

        $rdsaleQry = "SELECT depot_id, brand_id, brand_group_id, SUM(cal_qty) AS total_qty, SUM(amount) AS total_amt FROM redistributor_saleitems AS RdSale WHERE $sale_cond GROUP BY depot_id, brand_group_id";
        $rdsales = $this->query($rdsaleQry);

        if($rdsales){
            foreach($rdsales as $rdsale){
                $rsdid = $rdsale['RdSale']['depot_id'];
                $rsbid = $rdsale['RdSale']['brand_group_id'];
                $result[$rsdid]['rdsales']['brand'][$rsbid] = array('total_qty'=> $rdsale['0']['total_qty'],'total_amt'=> $rdsale['0']['total_amt']);
                if (isset($result[$rsdid]['rdsales']['sales_value'])){
                    $result[$rsdid]['rdsales']['sales_value'] = $result[$rsdid]['rdsales']['sales_value']+$rdsale['0']['total_amt'];
                }else{
                    $result[$rsdid]['rdsales']['sales_value'] = $rdsale['0']['total_amt'];
                }
            }
        }

        $consrdsaleQry = "SELECT depot_id, brand_id, brand_group_id, SUM(cal_qty) AS total_qty, SUM(amount) AS total_amt FROM consumer_redistribution_sales AS RdSale WHERE $sale_cond GROUP BY depot_id, brand_group_id";
        $consrdsales = $this->query($consrdsaleQry);

        if($consrdsales){
            foreach($consrdsales as $rdsale){
                $rsdid = $rdsale['RdSale']['depot_id'];
                $rsbid = $rdsale['RdSale']['brand_group_id'];
                /* $result[$rsdid]['consrdsales']['brand'][$rsbid] = array('total_qty'=> $rdsale['0']['total_qty'],'total_amt'=> $rdsale['0']['total_amt']);
                if (isset($result[$rsdid]['consrdsales']['sales_value'])){
                    $result[$rsdid]['consrdsales']['sales_value'] = $result[$rsdid]['consrdsales']['sales_value']+$rdsale['0']['total_amt'];
                }else{
                    $result[$rsdid]['consrdsales']['sales_value'] = $rdsale['0']['total_amt'];
                } */

                if(!empty($result[$sdid]['rdsales']['brand'][$sbid]['total_qty'])){
                    $result[$sdid]['rdsales']['brand'][$sbid]['total_qty'] += $sale['0']['total_qty'];
                }else{
                    $result[$sdid]['rdsales']['brand'][$sbid]['total_qty'] = $sale['0']['total_qty'];
                }

                if(!empty($result[$sdid]['rdsales']['brand'][$sbid]['total_amt'])){
                    $result[$sdid]['rdsales']['brand'][$sbid]['total_amt'] += $sale['0']['total_amt'];
                }else{
                    $result[$sdid]['rdsales']['brand'][$sbid]['total_amt'] = $sale['0']['total_amt'];
                }

                if(!empty($result[$sdid]['rdsales']['sales_value'])){
                    $result[$sdid]['rdsales']['sales_value'] += $sale['0']['total_amt'];
                }else{
                    $result[$sdid]['sales']['sales_value'] = !empty($sale['0']['total_amt'])?$sale['0']['total_amt']:0;
                }
            }
        }

        $paymentQry = "SELECT depot_id, brand_id, brand_group_id,  SUM(amount) AS total_amt FROM payments AS Payment WHERE $payment_cond $userNotEmptyCond GROUP BY depot_id";
        $payments = $this->query($paymentQry);
        if($payments){
            foreach($payments as $payment){
                $pdid = $payment['Payment']['depot_id'];
                $result[$pdid]['payment']['total_amt'] = $payment['0']['total_amt'];
            }
        }
        $expenseQry = "SELECT depot_id, brand_id, brand_group_id, SUM(exp_amount) AS total_amt FROM expenses AS Expense WHERE $expense_cond $userNotEmptyCond GROUP BY depot_id";
        $expenses = $this->query($expenseQry);
        if($expenses){
            foreach($expenses as $expense){
                $edid = $expense['Expense']['depot_id'];
                $result[$edid]['expense']['total_amt'] = $expense['0']['total_amt'];
            }
        }
        //pr($result);
        return $result;
    }
/**
    function targetReports($params){
        $output = array();
        $date = $params['date'];
        //pr($params);
        switch($params['type']){
            case 'daily':
                $oC = "sl.sale_date = '$date'";
                $rdC = "rsi.sale_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
                break;
            case 'between':

                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }

                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                $ccC = "c.created between '$d1' AND '$d2 23:59:59'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                $ccC = "c.created between '$d1' AND '$d2 23:59:59'";
                break;
        }


        if(!empty($params['query']['t-month'])){
            $d1Arrar['1'] = $params['query']['t-month'];
        }else{
            $d1Arrar = explode("-", $d1); //pr($d1Arrar);
        }


        $userDVC = $cdvC = $cvdvC = $dv_regC = $userDC = $userRC = $rgC = $dpC = $crgC = $cdpC = $cvrgC = $cvdpC ="";
        if (!empty($params['query']['dv'])){
            if (empty($params['query']['rg']) && empty($params['query']['dp'])) {
                $divisionRegion=  ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields'=>array('region_id'),'conditions'=>array('division_id'=>$params['query']['dv'])));
                $rIds = implode(",",$rIds); //pr($rIds);exit;
                $dv_regC = " AND d.region_id IN ( ".$rIds.") ";
            }
            $cvdvC = " AND us.division_id = ".$params['query']['dv'];
            $cdvC = " AND c.division_id = ".$params['query']['dv'];
            $userDVC = " AND u.division_id = ".$params['query']['dv'];

        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND d.region_id = ".$params['query']['rg'];
            $cvrgC = " AND us.region_id = ".$params['query']['rg'];
            $crgC = " AND c.region_id = ".$params['query']['rg'];
            $userRC = " AND u.region_id = ".$params['query']['rg'];

        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND d.id = ".$params['query']['dp'];
            $cvdpC = " AND us.depot_id = ".$params['query']['dp'];
            $cdpC = " AND c.depot_id = ".$params['query']['dp'];
            $userDC = " AND u.depot_id = ".$params['query']['dp'];
        }


        $result = array();

        switch($params['calltype']){

            case 'sale':
                $orderEntry = $this->query("SELECT count(sl.id) as oentry, SUM(sl.cal_qty) as totSale, sl.user_id, sl.depot_id, sl.brand_group_id, d.title, d.region_id, bg.name FROM sales sl INNER JOIN depots d ON d.id = sl.depot_id INNER JOIN brand_groups bg ON bg.id = sl.brand_group_id WHERE $oC $dv_regC  $rgC $dpC GROUP BY sl.depot_id, sl.user_id, sl.brand_group_id"); //pr($orderEntry);

                if ($orderEntry){
                    foreach ($orderEntry as $oe){
                        $uid = $oe['sl']['user_id'];
                        $bgid = $oe['sl']['brand_group_id'];
                        $did = $oe['sl']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$bgid]['orderEntry'] = $oe;
                        //$result[$rid][$did][$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
                        /* $result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['oentry']; */
    /**                    $result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['totSale'];
                        //$result[$rid][$did][$uid]['dname'] = $oe['d']['title'];
                        //$result[$rid][$did][$uid]['role_id'] = $oe['u']['role_id'];
                    } //pr($result);
                }

                //Consumer Sale
                $consOrderEntry = $this->query("SELECT count(sl.id) as oentry, SUM(sl.cal_qty) as totSale, sl.user_id, sl.depot_id, sl.brand_group_id, d.title, d.region_id, bg.name FROM consumer_sales sl INNER JOIN depots d ON d.id = sl.depot_id INNER JOIN brand_groups bg ON bg.id = sl.brand_group_id WHERE $oC $dv_regC $rgC $dpC GROUP BY sl.depot_id, sl.user_id, sl.brand_group_id"); //pr($orderEntry);

                if ($consOrderEntry){
                    foreach ($consOrderEntry as $oe){
                        $uid = $oe['sl']['user_id'];
                        $bgid = $oe['sl']['brand_group_id'];
                        $did = $oe['sl']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$bgid]['consOrderEntry'] = $oe;
                        //$result[$rid][$did][$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
                        /* $result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['oentry']; */
    /**                    $result[$rid][$did][$uid][$bgid]['consSaleEntry'] = $oe['0']['totSale'];
                        //$result[$rid][$did][$uid]['dname'] = $oe['d']['title'];
                        //$result[$rid][$did][$uid]['role_id'] = $oe['u']['role_id'];
                    } //pr($result);
                }

                $targetType = '"Sale"'; //pr($targetType);

                break;


            case 'redistribution':
                $rSaleEntry = $this->query("SELECT count(rsi.id) as rsentry, SUM(rsi.cal_qty) as totRSale, rsi.user_id, rsi.brand_group_id, rsi.depot_id, d.title, d.region_id, bg.name FROM redistributor_saleitems rsi INNER JOIN depots d ON d.id = rsi.depot_id INNER JOIN brand_groups bg ON bg.id = rsi.brand_group_id WHERE $rdC $dv_regC $rgC $dpC GROUP BY rsi.depot_id, rsi.user_id , rsi.brand_group_id");//pr($rSaleEntry);

                if ($rSaleEntry){
                    foreach ($rSaleEntry as $oe){
                        $uid = $oe['rsi']['user_id'];
                        $bgid = $oe['rsi']['brand_group_id'];
                        $did = $oe['rsi']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$bgid]['orderEntry'] = $oe;
                        //$result[$rid][$did][$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
                        /* $result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['rsentry']; */
       /**                 $result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['totRSale'];
                        //$result[$rid][$did][$uid]['dname'] = $rse['d']['title'];
                        //$result[$rid][$did][$uid]['role_id'] = $rse['u']['role_id'];
                    } //pr($result);
                }

                //Consumer Rsale
                $consRSaleEntry = $this->query("SELECT count(rsi.id) as rsentry, SUM(rsi.cal_qty) as totRSale, rsi.user_id, rsi.brand_group_id, rsi.depot_id, d.title, d.region_id, bg.name FROM consumer_redistribution_sales rsi INNER JOIN depots d ON d.id = rsi.depot_id INNER JOIN brand_groups bg ON bg.id = rsi.brand_group_id WHERE $rdC $dv_regC $rgC $dpC GROUP BY rsi.depot_id, rsi.user_id , rsi.brand_group_id");//pr($rSaleEntry);

                if ($consRSaleEntry){
                    foreach ($consRSaleEntry as $oe){
                        $uid = $oe['rsi']['user_id'];
                        $bgid = $oe['rsi']['brand_group_id'];
                        $did = $oe['rsi']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$bgid]['consOrderEntry'] = $oe;
                        //$result[$rid][$did][$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
                        /* $result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['rsentry']; */
        /**                $result[$rid][$did][$uid][$bgid]['consSaleEntry'] = $oe['0']['totRSale'];
                        //$result[$rid][$did][$uid]['dname'] = $rse['d']['title'];
                        //$result[$rid][$did][$uid]['role_id'] = $rse['u']['role_id'];
                    } //pr($result);
                }

                $targetType = '"Redistribution"';

                break;


            case 'summary':

                $orderEntry = $this->query("SELECT count(sl.id) as oentry, SUM(sl.cal_qty) as totSale, sl.user_id, sl.depot_id, sl.brand_group_id, d.title, d.region_id, bg.name FROM sales sl INNER JOIN depots d ON d.id = sl.depot_id INNER JOIN brand_groups bg ON bg.id = sl.brand_group_id WHERE $oC $dv_regC $rgC $dpC GROUP BY sl.depot_id, sl.user_id, sl.brand_group_id"); //pr($orderEntry);

                if ($orderEntry){
                    foreach ($orderEntry as $oe){
                        $uid = $oe['sl']['user_id'];
                        $bgid = $oe['sl']['brand_group_id'];
                        $did = $oe['sl']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$bgid]['orderEntry'] = $oe;
                        //$result[$rid][$did][$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
                        /* $result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['oentry']; */
        /**                $result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['totSale'];
                        //$result[$rid][$did][$uid]['dname'] = $oe['d']['title'];
                        //$result[$rid][$did][$uid]['role_id'] = $oe['u']['role_id'];
                    } //pr($result);
                }

                //Consumer Sale
                $conOrderEntry = $this->query("SELECT count(sl.id) as oentry, SUM(sl.cal_qty) as totSale, sl.user_id, sl.depot_id, sl.brand_group_id, d.title, d.region_id, bg.name FROM consumer_sales sl INNER JOIN depots d ON d.id = sl.depot_id INNER JOIN brand_groups bg ON bg.id = sl.brand_group_id WHERE $oC $dv_regC $rgC $dpC GROUP BY sl.depot_id, sl.user_id, sl.brand_group_id"); //pr($orderEntry);

                if ($conOrderEntry){
                    foreach ($conOrderEntry as $oe){
                        $uid = $oe['sl']['user_id'];
                        $bgid = $oe['sl']['brand_group_id'];
                        $did = $oe['sl']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$bgid]['consOrderEntry'] = $oe;
                        //$result[$rid][$did][$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
                        /* $result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['oentry']; */
        /**                $result[$rid][$did][$uid][$bgid]['consSaleEntry'] = $oe['0']['totSale'];
                        //$result[$rid][$did][$uid]['dname'] = $oe['d']['title'];
                        //$result[$rid][$did][$uid]['role_id'] = $oe['u']['role_id'];
                    } //pr($result);
                }

                //Rsale
                $rSaleEntry = $this->query("SELECT count(rsi.id) as rsentry, SUM(rsi.cal_qty) as totRSale, rsi.user_id, rsi.brand_group_id, rsi.depot_id, d.title, d.region_id, bg.name FROM redistributor_saleitems rsi INNER JOIN depots d ON d.id = rsi.depot_id INNER JOIN brand_groups bg ON bg.id = rsi.brand_group_id WHERE $rdC $dv_regC $rgC $dpC GROUP BY rsi.depot_id, rsi.user_id , rsi.brand_group_id"); //pr($rSaleEntry);

                if ($rSaleEntry){
                    foreach ($rSaleEntry as $rse){
                        $uid = $rse['rsi']['user_id'];
                        $bgid = $rse['rsi']['brand_group_id'];
                        $did = $rse['rsi']['depot_id'];
                        $rid = $rse['d']['region_id'];
                        $result[$rid][$did][$uid][$bgid]['rSaleEntry'] = $rse;
                        //$result[$rid][$did][$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
                        /* $result[$rid][$did][$uid][$bgid]['rdSaleEntry'] = $rse['0']['rsentry']; */
        /**                $result[$rid][$did][$uid][$bgid]['rdSaleEntry'] = $rse['0']['totRSale'];
                        //$result[$rid][$did][$uid]['dname'] = $rse['d']['title'];
                        //$result[$rid][$did][$uid]['role_id'] = $rse['u']['role_id'];
                    }
                } //pr($result);

                //Consumer Rsale
                $consRSaleEntry = $this->query("SELECT count(rsi.id) as rsentry, SUM(rsi.cal_qty) as totRSale, rsi.user_id, rsi.brand_group_id, rsi.depot_id, d.title, d.region_id, bg.name FROM consumer_redistribution_sales rsi INNER JOIN depots d ON d.id = rsi.depot_id INNER JOIN brand_groups bg ON bg.id = rsi.brand_group_id WHERE $rdC $dv_regC $rgC $dpC GROUP BY rsi.depot_id, rsi.user_id , rsi.brand_group_id"); //pr($rSaleEntry);

                if ($consRSaleEntry){
                    foreach ($consRSaleEntry as $rse){
                        $uid = $rse['rsi']['user_id'];
                        $bgid = $rse['rsi']['brand_group_id'];
                        $did = $rse['rsi']['depot_id'];
                        $rid = $rse['d']['region_id'];
                        $result[$rid][$did][$uid][$bgid]['consRSaleEntry'] = $rse;
                        //$result[$rid][$did][$uid]['name'] = $rse['u']['first_name'].' '.$rse['u']['last_name'];
                        /* $result[$rid][$did][$uid][$bgid]['rdSaleEntry'] = $rse['0']['rsentry']; */
        /**                $result[$rid][$did][$uid][$bgid]['consRdSaleEntry'] = $rse['0']['totRSale'];
                        //$result[$rid][$did][$uid]['dname'] = $rse['d']['title'];
                        //$result[$rid][$did][$uid]['role_id'] = $rse['u']['role_id'];
                    }
                } //pr($result);

                //$targetType = '"Sale OR Redistribution"';

                break;
        }


        //Count customers created
        $customerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM customers c WHERE 1 $cdvC $crgC $cdpC GROUP BY c.user_id");

        if ($customerEntry){
            foreach ($customerEntry as $cve){
                $uid = $cve['c']['user_id'];
                //$did = $cve['c']['depot_id'];
                //$rid = $cve['c']['region_id'];
                $result['cCreated'][$uid] = $cve;
                //$result[$rid][$did][$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                $result['totalCustomer'][$uid] = $cve['0']['cCreated'];
                //$result[$rid][$did][$uid]['dname'] = $cve['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $cve['u']['role_id'];
            }
        }

        //Count consumers created
        $consumerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM consumers c WHERE 1 $crgC $cdpC GROUP BY c.user_id");

        if ($consumerEntry){
            foreach ($consumerEntry as $cve){
                $uid = $cve['c']['user_id'];
                //$did = $cve['c']['depot_id'];
                //$rid = $cve['c']['region_id'];
                $result['conCreated'][$uid] = $cve;
                //$result[$rid][$did][$uid]['name'] = $cve['u']['first_name'].' '.$cve['u']['last_name'];
                $result['totalConsumer'][$uid] = $cve['0']['cCreated'];
                //$result[$rid][$did][$uid]['dname'] = $cve['d']['title'];
                //$result[$rid][$did][$uid]['role_id'] = $cve['u']['role_id'];
            }
        }

        //$output['totalCalls'] = $totalCalls;



        //find monthly Targets
        $targets = array();

        if($params['calltype'] == 'summary'){

            $targetQry['sale'] = $this->query("SELECT t.user_id, t.depot_id, t.target, t.brand_group_id, g.name , dp.region_id FROM user_targets AS t JOIN depots dp ON dp.id = t.depot_id INNER JOIN brand_groups AS g ON t.brand_group_id = g.id WHERE type='Sale'"); //pr($targetQry['sale']);

            if ($targetQry['sale']){
                foreach ($targetQry['sale'] as $sTarget){
                    $uid = $sTarget['t']['user_id'];
                    $bgid = $sTarget['t']['brand_group_id'];
                    $rid = $sTarget['dp']['region_id'];
                    $did = $sTarget['t']['depot_id'];
                    $userSaleTargets = @unserialize($sTarget['t']['target']);
                    $result[$rid][$did][$uid][$bgid]['sale_target'] = $sTarget;
                    $result[$rid][$did][$uid][$bgid]['sale_targetQry'] = !empty($userSaleTargets[$d1Arrar['1']])?$userSaleTargets[$d1Arrar['1']]:0;
                    //$result[$rid][$did][$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
                    ///$result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['oentry'];
                    //$result[$rid][$did][$uid]['dname'] = $oe['d']['title'];
                    //$result[$rid][$did][$uid]['role_id'] = $oe['u']['role_id'];
                } //pr($result);
            }

            $targetQry['rSale'] = $this->query("SELECT t.user_id, t.depot_id, t.target, t.brand_group_id, g.name , dp.region_id FROM user_targets AS t JOIN depots dp ON dp.id = t.depot_id INNER JOIN brand_groups AS g ON t.brand_group_id = g.id WHERE type='Redistribution'"); //pr($targetQry['rSale']);

            if ($targetQry['rSale']){
                foreach ($targetQry['rSale'] as $rsTarget){
                    $uid = $rsTarget['t']['user_id'];
                    $bgid = $rsTarget['t']['brand_group_id'];
                    $rid = $rsTarget['dp']['region_id'];
                    $did = $rsTarget['t']['depot_id'];
                    $userRSaleTargets = @unserialize($rsTarget['t']['target']);
                    $result[$rid][$did][$uid][$bgid]['rsale_target'] = $rsTarget;
                    $result[$rid][$did][$uid][$bgid]['rsale_targetQry'] = !empty($userRSaleTargets[$d1Arrar['1']])?$userRSaleTargets[$d1Arrar['1']]:0;
                    //$result[$rid][$did][$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
                    ///$result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['oentry'];
                    //$result[$rid][$did][$uid]['dname'] = $oe['d']['title'];
                    //$result[$rid][$did][$uid]['role_id'] = $oe['u']['role_id'];
                } //pr($result);
            }

        }else{

            //$targetQry = $this->query("SELECT t.user_id, t.depot_id, t.target, t.brand_group_id, g.name , dp.region_id FROM user_targets AS t JOIN depots dp ON dp.id = t.depot_id INNER JOIN brand_groups AS g ON t.brand_group_id = g.id WHERE type=$targetType GROUP BY t.depot_id, t.brand_group_id"); //pr($targetQry);

            $targetQry = $this->query("SELECT t.user_id, t.depot_id, t.target, t.brand_group_id, g.name , dp.region_id FROM user_targets AS t JOIN depots dp ON dp.id = t.depot_id INNER JOIN brand_groups AS g ON t.brand_group_id = g.id WHERE type=$targetType"); //pr($targetQry);

            if ($targetQry){
                foreach ($targetQry as $target){
                    $uid = $target['t']['user_id'];
                    $bgid = $target['t']['brand_group_id'];
                    $rid = $target['dp']['region_id'];
                    $did = $target['t']['depot_id'];
                    $userTargets = @unserialize($target['t']['target']);
                    $result[$rid][$did][$uid][$bgid]['target'] = $target;
                    $result[$rid][$did][$uid][$bgid]['targetQry'] = !empty($userTargets[$d1Arrar['1']])?$userTargets[$d1Arrar['1']]:0;
                    //$result[$rid][$did][$uid]['name'] = $oe['u']['first_name'].' '.$oe['u']['last_name'];
                    ///$result[$rid][$did][$uid][$bgid]['saleEntry'] = $oe['0']['oentry'];
                    //$result[$rid][$did][$uid]['dname'] = $oe['d']['title'];
                    //$result[$rid][$did][$uid]['role_id'] = $oe['u']['role_id'];
                } //pr($result);
            }
        }





        $output['result'] = $result;
        //Get roles
        /*$roles = array();
        $roleData = $this->query("SELECT id, name FROM roles AS Role");
        foreach($roleData as $role){
            $id = $role['Role']['id'];
            $roles[$id] = $role['Role']['name'];
        }
        $output['roles'] = $roles;*/

        //Get All users
    /**    $users = array();
        //$usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE r.grade > 2 AND u.status = ".ACTIVE." $userDC $userRC ORDER BY rg.title ASC, u.role_id ASC");
        /* $usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE u.status =".ACTIVE." AND r.grade > 2 $userDC $userRC ORDER BY rg.title ASC, u.role_id ASC"); */
    /**    $usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, u.status, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE r.grade > 2 $userDVC $userDC $userRC ORDER BY rg.title ASC, u.role_id ASC");
        foreach($usersData as $user){

            $rid = ($user['u']['region_id'])?$user['u']['region_id']:0;
            $did = ($user['u']['depot_id'])?$user['u']['depot_id']:0;

            $uid = $user['u']['id'];
            $users[$rid][$did][$uid] = array('uid'=>$user['u']['id'],'name'=> $user['u']['first_name'].' '.$user['u']['last_name'], 'status'=>$user['u']['status'], 'rid'=>$user['u']['role_id'], 'role'=>$user['r']['name'], 'depot'=>$user['d']['title']);
        }
        $output['users'] = $users;
        //pr($users);


        /* $orderEntry = $this->query("SELECT count(sl.id) as oentry, sl.user_id, sl.depot_id, sl.brand_group_id, d.title, d.region_id, bg.name FROM sales sl INNER JOIN depots d ON d.id = sl.depot_id INNER JOIN brand_groups bg ON bg.id = sl.brand_group_id WHERE $oC $rgC $dpC GROUP BY sl.depot_id, sl.user_id, sl.brand_group_id"); //pr($orderEntry); */

        //pr($targetQry);
        /* if($targetQry){
            foreach($targetQry as $target){
                $user_id = $target['Target']['user_id'];
                $depot_id = $target['Target']['depot_id'];
                $userTargets = @unserialize($target['Target']['target']);
                $targets[$user_id] = !empty($userTargets[$d1Arrar['1']])?$userTargets[$d1Arrar['1']]:0;
            }
        } */

        //pr($output);
        //$output['targets'] = $targets;
    /**    return $output;
    } **/
	
	function targetReports($params){
        $output = array();
        $date = $params['date'];
        //pr($params);
        switch($params['type']){
            case 'daily':
                $oC = "sl.sale_date = '$date'";
                $rdC = "rsi.sale_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
                break;
            case 'between':

                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }

                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                $ccC = "c.created between '$d1' AND '$d2 23:59:59'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);

                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                $ccC = "c.created between '$d1' AND '$d2 23:59:59'";
                break;
        }


        if(!empty($params['query']['t-month'])){
            $d1Arrar['1'] = $params['query']['t-month'];
        }else{
            $d1Arrar = explode("-", $d1); //pr($d1Arrar);
        }


        $userDVC = $cdvC = $cvdvC = $dv_regC = $userDC = $userRC = $rgC = $dpC = $crgC = $cdpC = $cvrgC = $cvdpC ="";
        if (!empty($params['query']['dv'])){
            if (empty($params['query']['rg']) && empty($params['query']['dp'])) {
                $divisionRegion=  ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields'=>array('region_id'),'conditions'=>array('division_id'=>$params['query']['dv'])));
                $rIds = implode(",",$rIds); //pr($rIds);exit;
                $dv_regC = " AND d.region_id IN ( ".$rIds.") ";
            }
            $cvdvC = " AND us.division_id = ".$params['query']['dv'];
            $cdvC = " AND c.division_id = ".$params['query']['dv'];
            $userDVC = " AND u.division_id = ".$params['query']['dv'];

        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND d.region_id = ".$params['query']['rg'];
            $cvrgC = " AND us.region_id = ".$params['query']['rg'];
            $crgC = " AND c.region_id = ".$params['query']['rg'];
            $userRC = " AND u.region_id = ".$params['query']['rg'];

        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND d.id = ".$params['query']['dp'];
            $cvdpC = " AND us.depot_id = ".$params['query']['dp'];
            $cdpC = " AND c.depot_id = ".$params['query']['dp'];
            $userDC = " AND u.depot_id = ".$params['query']['dp'];
        }


        $result = array();

        switch($params['calltype']){

            case 'sale':
                $orderEntry = $this->query("SELECT count(sl.id) as oentry, SUM(sl.cal_qty) as totSale, sl.user_id, sl.depot_id, sl.brand_group_id, d.title, d.region_id, bg.name,u.depot_id FROM sales sl INNER JOIN users u ON u.id = sl.user_id INNER JOIN depots d ON d.id = sl.depot_id INNER JOIN brand_groups bg ON bg.id = sl.brand_group_id WHERE $oC $dv_regC  $rgC $userDC GROUP BY u.depot_id, sl.user_id, sl.brand_group_id"); //pr($orderEntry);

                if ($orderEntry){
                    foreach ($orderEntry as $oe){
                        $uid = $oe['sl']['user_id'];
                        $bgid = $oe['sl']['brand_group_id'];
                        $did = $oe['u']['depot_id'];
                        $sdid = $oe['sl']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$sdid][$bgid]['orderEntry'] = $oe;

                        $result[$rid][$did][$uid][$sdid][$bgid]['saleEntry'] = $oe['0']['totSale'];

                    } //pr($result);
                }
                //pr($result);exit;
                //pr($users);exit;
                //Consumer Sale
                $consOrderEntry = $this->query("SELECT count(sl.id) as oentry, SUM(sl.cal_qty) as totSale, sl.user_id, sl.depot_id, sl.brand_group_id, d.title, d.region_id, bg.name,u.depot_id FROM consumer_sales sl INNER JOIN users u ON u.id = sl.user_id INNER JOIN depots d ON d.id = sl.depot_id INNER JOIN brand_groups bg ON bg.id = sl.brand_group_id WHERE $oC $dv_regC $rgC $userDC GROUP BY u.depot_id, sl.user_id, sl.brand_group_id"); //pr($orderEntry);

                if ($consOrderEntry){
                    foreach ($consOrderEntry as $oe){
                        $uid = $oe['sl']['user_id'];
                        $bgid = $oe['sl']['brand_group_id'];
                        $did = $oe['u']['depot_id'];
                        $sdid = $oe['sl']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$sdid][$bgid]['consOrderEntry'] = $oe;
                        $result[$rid][$did][$uid][$sdid][$bgid]['consSaleEntry'] = $oe['0']['totSale'];
                    } //pr($result);
                }

                $targetType = '"Sale"'; //pr($targetType);

                break;


            case 'redistribution':
                $rSaleEntry = $this->query("SELECT count(rsi.id) as rsentry, SUM(rsi.cal_qty) as totRSale, rsi.user_id, rsi.brand_group_id, rsi.depot_id, d.title, d.region_id, bg.name,u.depot_id FROM redistributor_saleitems rsi INNER JOIN users u ON u.id = rsi.user_id INNER JOIN depots d ON d.id = rsi.depot_id INNER JOIN brand_groups bg ON bg.id = rsi.brand_group_id WHERE $rdC $dv_regC $rgC $userDC GROUP BY u.depot_id, rsi.user_id , rsi.brand_group_id");//pr($rSaleEntry);
                if ($rSaleEntry){
                    foreach ($rSaleEntry as $oe){
                        $uid = $oe['rsi']['user_id'];
                        $bgid = $oe['rsi']['brand_group_id'];
                        $did = $oe['u']['depot_id'];
                        $sdid = $oe['rsi']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$sdid][$bgid]['orderEntry'] = $oe;
                        $result[$rid][$did][$uid][$sdid][$bgid]['saleEntry'] = $oe['0']['totRSale'];
                    } //pr($result);
                }

                //Consumer Rsale
                $consRSaleEntry = $this->query("SELECT count(rsi.id) as rsentry, SUM(rsi.cal_qty) as totRSale, rsi.user_id, rsi.brand_group_id, rsi.depot_id, d.title, d.region_id, bg.name, u.depot_id FROM consumer_redistribution_sales rsi INNER JOIN users u ON u.id = rsi.user_id INNER JOIN depots d ON d.id = rsi.depot_id INNER JOIN brand_groups bg ON bg.id = rsi.brand_group_id WHERE $rdC $dv_regC $rgC $userDC GROUP BY u.depot_id, rsi.user_id , rsi.brand_group_id");//pr($rSaleEntry);

                if ($consRSaleEntry){
                    foreach ($consRSaleEntry as $oe){
                        $uid = $oe['rsi']['user_id'];
                        $bgid = $oe['rsi']['brand_group_id'];
                        $did = $oe['u']['depot_id'];
                        $sdid = $oe['rsi']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$sdid][$bgid]['consOrderEntry'] = $oe;
                        $result[$rid][$did][$uid][$sdid][$bgid]['consSaleEntry'] = $oe['0']['totRSale'];
                    } //pr($result);
                }

                $targetType = '"Redistribution"';

                break;


            case 'summary':

                $orderEntry = $this->query("SELECT count(sl.id) as oentry, SUM(sl.cal_qty) as totSale, sl.user_id, sl.depot_id, sl.brand_group_id, d.title, d.region_id, bg.name, u.depot_id FROM sales sl INNER JOIN users u ON u.id = sl.user_id INNER JOIN depots d ON d.id = sl.depot_id INNER JOIN brand_groups bg ON bg.id = sl.brand_group_id WHERE $oC $dv_regC $rgC $userDC GROUP BY u.depot_id, sl.user_id, sl.brand_group_id"); //pr($orderEntry);

                if ($orderEntry){
                    foreach ($orderEntry as $oe){
                        $uid = $oe['sl']['user_id'];
                        $bgid = $oe['sl']['brand_group_id'];
                        $did = $oe['u']['depot_id'];
                        $sdid = $oe['sl']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$sdid][$bgid]['orderEntry'] = $oe;
                        $result[$rid][$did][$uid][$sdid][$bgid]['saleEntry'] = $oe['0']['totSale'];
                    } //pr($result);
                }

                //Consumer Sale
                $conOrderEntry = $this->query("SELECT count(sl.id) as oentry, SUM(sl.cal_qty) as totSale, sl.user_id, sl.depot_id, sl.brand_group_id, d.title, d.region_id, bg.name, u.depot_id FROM consumer_sales sl INNER JOIN users u ON u.id = sl.user_id  INNER JOIN depots d ON d.id = sl.depot_id INNER JOIN brand_groups bg ON bg.id = sl.brand_group_id WHERE $oC $dv_regC $rgC $userDC GROUP BY u.depot_id, sl.user_id, sl.brand_group_id"); //pr($orderEntry);

                if ($conOrderEntry){
                    foreach ($conOrderEntry as $oe){
                        $uid = $oe['sl']['user_id'];
                        $bgid = $oe['sl']['brand_group_id'];
                        $did = $oe['u']['depot_id'];
                        $sdid = $oe['sl']['depot_id'];
                        $rid = $oe['d']['region_id'];
                        $result[$rid][$did][$uid][$sdid][$bgid]['consOrderEntry'] = $oe;
                        $result[$rid][$did][$uid][$sdid][$bgid]['consSaleEntry'] = $oe['0']['totSale'];
                    } //pr($result);
                }

                //Rsale
                $rSaleEntry = $this->query("SELECT count(rsi.id) as rsentry, SUM(rsi.cal_qty) as totRSale, rsi.user_id, rsi.brand_group_id, rsi.depot_id, d.title, d.region_id, bg.name,u.depot_id FROM redistributor_saleitems rsi INNER JOIN users u ON u.id = rsi.user_id INNER JOIN depots d ON d.id = rsi.depot_id INNER JOIN brand_groups bg ON bg.id = rsi.brand_group_id WHERE $rdC $dv_regC $rgC $userDC GROUP BY u.depot_id, rsi.user_id , rsi.brand_group_id"); //pr($rSaleEntry);

                if ($rSaleEntry){
                    foreach ($rSaleEntry as $rse){
                        $uid = $rse['rsi']['user_id'];
                        $bgid = $rse['rsi']['brand_group_id'];
                        $did = $rse['u']['depot_id'];
                        $sdid = $rse['rsi']['depot_id'];
                        $rid = $rse['d']['region_id'];
                        $result[$rid][$did][$uid][$sdid][$bgid]['rSaleEntry'] = $rse;
                        $result[$rid][$did][$uid][$sdid][$bgid]['rdSaleEntry'] = $rse['0']['totRSale'];
                    }
                } //pr($result);

                //Consumer Rsale
                $consRSaleEntry = $this->query("SELECT count(rsi.id) as rsentry, SUM(rsi.cal_qty) as totRSale, rsi.user_id, rsi.brand_group_id, rsi.depot_id, d.title, d.region_id, bg.name, u.depot_id FROM consumer_redistribution_sales rsi INNER JOIN users u ON u.id = rsi.user_id INNER JOIN depots d ON d.id = rsi.depot_id INNER JOIN brand_groups bg ON bg.id = rsi.brand_group_id WHERE $rdC $dv_regC $rgC $userDC GROUP BY u.depot_id, rsi.user_id , rsi.brand_group_id"); //pr($rSaleEntry);

                if ($consRSaleEntry){
                    foreach ($consRSaleEntry as $rse){
                        $uid = $rse['rsi']['user_id'];
                        $bgid = $rse['rsi']['brand_group_id'];
                        $did = $rse['u']['depot_id'];
                        $sdid = $rse['rsi']['depot_id'];
                        $rid = $rse['d']['region_id'];
                        $result[$rid][$did][$uid][$sdid][$bgid]['consRSaleEntry'] = $rse;
                        $result[$rid][$did][$uid][$sdid][$bgid]['consRdSaleEntry'] = $rse['0']['totRSale'];
                    }
                } //pr($result);


                break;
        }


        //Count customers created
        $customerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM customers c WHERE 1 $cdvC $crgC $cdpC GROUP BY c.user_id");

        if ($customerEntry){
            foreach ($customerEntry as $cve){
                $uid = $cve['c']['user_id'];
                $result['cCreated'][$uid] = $cve;
                $result['totalCustomer'][$uid] = $cve['0']['cCreated'];
            }
        }

        //Count consumers created
        $consumerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM consumers c WHERE 1 $crgC $cdpC GROUP BY c.user_id");

        if ($consumerEntry){
            foreach ($consumerEntry as $cve){
                $uid = $cve['c']['user_id'];
                $result['conCreated'][$uid] = $cve;
                $result['totalConsumer'][$uid] = $cve['0']['cCreated'];
            }
        }

        //$output['totalCalls'] = $totalCalls;



        //find monthly Targets
        $targets = array();

        if($params['calltype'] == 'summary'){

            $targetQry['sale'] = $this->query("SELECT t.user_id, t.depot_id, t.target, t.brand_group_id, g.name , dp.region_id,u.depot_id FROM user_targets AS t INNER JOIN users u ON u.id = t.user_id JOIN depots dp ON dp.id = t.depot_id INNER JOIN brand_groups AS g ON t.brand_group_id = g.id WHERE type='Sale'"); //pr($targetQry['sale']);

            if ($targetQry['sale']){
                foreach ($targetQry['sale'] as $sTarget){
                    $uid = $sTarget['t']['user_id'];
                    $bgid = $sTarget['t']['brand_group_id'];
                    $rid = $sTarget['dp']['region_id'];
                    $did = $sTarget['u']['depot_id'];
                    $sdid = $sTarget['t']['depot_id'];
                    $userSaleTargets = @unserialize($sTarget['t']['target']);
                    $result[$rid][$did][$uid][$sdid][$bgid]['sale_target'] = $sTarget;
                    $result[$rid][$did][$uid][$sdid][$bgid]['sale_targetQry'] = !empty($userSaleTargets[$d1Arrar['1']])?$userSaleTargets[$d1Arrar['1']]:0;
                } //pr($result);
            }

            $targetQry['rSale'] = $this->query("SELECT t.user_id, t.depot_id, t.target, t.brand_group_id, g.name , dp.region_id,u.depot_id FROM user_targets AS t INNER JOIN users u ON u.id = t.user_id JOIN depots dp ON dp.id = t.depot_id INNER JOIN brand_groups AS g ON t.brand_group_id = g.id WHERE type='Redistribution'"); //pr($targetQry['rSale']);

            if ($targetQry['rSale']){
                foreach ($targetQry['rSale'] as $rsTarget){
                    $uid = $rsTarget['t']['user_id'];
                    $bgid = $rsTarget['t']['brand_group_id'];
                    $rid = $rsTarget['dp']['region_id'];
                    $did = $rsTarget['u']['depot_id'];
                    $sdid = $rsTarget['t']['depot_id'];
                    $userRSaleTargets = @unserialize($rsTarget['t']['target']);
                    $result[$rid][$did][$uid][$sdid][$bgid]['rsale_target'] = $rsTarget;
                    $result[$rid][$did][$uid][$sdid][$bgid]['rsale_targetQry'] = !empty($userRSaleTargets[$d1Arrar['1']])?$userRSaleTargets[$d1Arrar['1']]:0;
                } //pr($result);
            }

        }else{

            $targetQry = $this->query("SELECT t.user_id, t.depot_id, t.target, t.brand_group_id, g.name , dp.region_id, u.depot_id FROM user_targets AS t INNER JOIN users u ON u.id = t.user_id JOIN depots dp ON dp.id = t.depot_id INNER JOIN brand_groups AS g ON t.brand_group_id = g.id WHERE type=$targetType"); //pr($targetQry);

            if ($targetQry){
                foreach ($targetQry as $target){
                    $uid = $target['t']['user_id'];
                    $bgid = $target['t']['brand_group_id'];
                    $rid = $target['dp']['region_id'];
                    $did = $target['u']['depot_id'];
                    $sdid = $target['t']['depot_id'];
                    $userTargets = @unserialize($target['t']['target']);

                    $result[$rid][$did][$uid][$sdid][$bgid]['target'] = $target;
                    $result[$rid][$did][$uid][$sdid][$bgid]['targetQry'] = !empty($userTargets[$d1Arrar['1']])?$userTargets[$d1Arrar['1']]:0;
                } //pr($result);
            }
        }





        $output['result'] = $result;
        //Get roles
        /*$roles = array();
        $roleData = $this->query("SELECT id, name FROM roles AS Role");
        foreach($roleData as $role){
            $id = $role['Role']['id'];
            $roles[$id] = $role['Role']['name'];
        }
        $output['roles'] = $roles;*/

        //Get All users
        $users = array();
        //$usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE r.grade > 2 AND u.status = ".ACTIVE." $userDC $userRC ORDER BY rg.title ASC, u.role_id ASC");
        /* $usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE u.status =".ACTIVE." AND r.grade > 2 $userDC $userRC ORDER BY rg.title ASC, u.role_id ASC"); */
        $usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.region_id, u.depot_id, u.role_id, u.status, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE r.grade > 2 $userDVC $userDC $userRC ORDER BY rg.title ASC, u.role_id ASC"); //pr($usersData);exit;
        foreach($usersData as $user){

            $rid = ($user['u']['region_id'])?$user['u']['region_id']:0;
            $did = ($user['u']['depot_id'])?$user['u']['depot_id']:0;

            $uid = $user['u']['id'];
            $users[$rid][$did][$uid] = array('uid'=>$user['u']['id'],'name'=> $user['u']['first_name'].' '.$user['u']['last_name'], 'status'=>$user['u']['status'], 'rid'=>$user['u']['role_id'], 'role'=>$user['r']['name'], 'depot'=>$user['d']['title']);
        }


        //pr($users); exit;
        $output['users'] = $users;
        //pr($users);exit;


        /* $orderEntry = $this->query("SELECT count(sl.id) as oentry, sl.user_id, sl.depot_id, sl.brand_group_id, d.title, d.region_id, bg.name FROM sales sl INNER JOIN depots d ON d.id = sl.depot_id INNER JOIN brand_groups bg ON bg.id = sl.brand_group_id WHERE $oC $rgC $dpC GROUP BY sl.depot_id, sl.user_id, sl.brand_group_id"); //pr($orderEntry); */

        //pr($targetQry);
        /* if($targetQry){
            foreach($targetQry as $target){
                $user_id = $target['Target']['user_id'];
                $depot_id = $target['Target']['depot_id'];
                $userTargets = @unserialize($target['Target']['target']);
                $targets[$user_id] = !empty($userTargets[$d1Arrar['1']])?$userTargets[$d1Arrar['1']]:0;
            }
        } */

        //pr($output);
        //$output['targets'] = $targets;
        return $output;
    }
	
/**	
	public function totalNumberOfVisitsPerCustomer($params, &$paginate, &$conditions, &$customer, &$activeCust){
        //pr($params);
        $reportArr = array();
        $date = $params['date'];
        $result = array();
        switch($params['type']){
            case 'daily':
                $cvC = "cv.visiting_date LIKE '".$date."%'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));
                $cvC = "cv.visiting_date between '$d1' AND '$d2'";
                break;
            case 'between':
                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $cvC = "cv.visiting_date between '$d1' AND '$d2'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);
                $cvC = "cv.visiting_date between '$d1' AND '$d2'";
                break;
        }

        $customer->virtualFields['totVisits'] = "COUNT(cv.id)";
        $paginate['order'] = array("Customer.first_name" => "asc", "Customer.last_name" => "asc");


        $paginate['fields'] = array("Customer.id", "Customer.first_name", "Customer.last_name", "COUNT(cv.id) as totVisits");
		
		
		if (!empty($params['query']['q']) ){
			$conditions['OR']['Customer.first_name LIKE'] =  '%'.$params['query']['q'].'%';
			$conditions['OR']['Customer.last_name LIKE'] =  '%'.$params['query']['q'].'%';
		}

        if (!empty($params['query']['dv'])){
            $conditions['Customer.division_id'] = $params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $conditions['Customer.region_id'] = $params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $conditions['Customer.depot_id'] = $params['query']['dp'];
        }

        $join=$paginate['joins'][] = array('table' => 'customer_visits', 'type'=>'inner', 'alias'=>'cv', 'conditions'=>array("Customer.id=cv.customer_id AND $cvC "));
        $paginate['limit'] = 50;
        $group=$paginate['group'] = array('Customer.id');

        if (!empty($this->request->query['export'])){
            $activeCust = $this->Customer->find('all',array('conditions'=>$conditions,'joins'=>$join,'group'=>$group));

        }

    }**/
	
	public function totalNumberOfVisitsPerCustomer($params, &$paginate, &$conditions, &$customer, &$activeCust){
         //pr($params);
        $reportArr = array();
        $date = $params['date'];
        $result = array();
        $cutomerIds = array();
        $cond ='';
        foreach($activeCust as $cust){
            $customerIds[] = $cust['Customer']['id'];
        }

        switch($params['type']){
            case 'daily':
                $sC = "sl.sale_date = '$date'";
                $rsC = "rsi.sale_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
                break;
            case 'weekly':
                $d1 = date('Y-m-d', $params['strtotime']);
                $d2 =  date('Y-m-d', strtotime('+6 days', $params['strtotime']));
                $sC = "sl.sale_date between '$d1' AND '$d2'";
                $rsC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
            case 'between':
                if(empty( $params['query']['from'])){
                    $d1 = date('Y-m-d');
                }else{
                    $d1 =  $params['query']['from'];
                }
                if(empty( $params['query']['to'])){
                    $d2 = date('Y-m-d');
                }else{
                    $d2 =  $params['query']['to'];
                }
                $sC = "sl.sale_date between '$d1' AND '$d2'";
                $rsC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
            case 'monthly':
                $d1 = date('Y-m-01', $params['strtotime']);
                $d2 = date('Y-m-t', $params['strtotime']);
                $sC = "sl.sale_date between '$d1' AND '$d2'";
                $rsC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                break;
        }

        $dv_regC = $rgC = $dpC = $susC = $rsusC ="";
        if (!empty($params['query']['q']) && empty($params['query']['us'])){

            $cond .=' AND  ( concat_ws(" ", Customer.first_name, Customer.last_name) LIKE  "%'.$params['query']['q'].'%" ) ';
        }

        if (!empty($params['query']['dv'])){
            if (empty($params['query']['rg']) && empty($params['query']['dp'])) {
                $divisionRegion=  ClassRegistry::init('DivisionsRegion');
                $rIds = $divisionRegion->find('list', array('fields'=>array('region_id'),'conditions'=>array('division_id'=>$params['query']['dv'])));
                $rIds = implode(",",$rIds); //pr($rIds);exit;
                $dv_regC = " AND d.region_id IN ( ".$rIds.") ";
            }

            $cond .=' AND Customer.division_id ='.$params['query']['dv'];
        }
        if (!empty($params['query']['rg'])){
            $rgC = " AND d.region_id = ".$params['query']['rg'];

            $cond .=' AND Customer.region_id='.$params['query']['rg'];
        }
        if (!empty($params['query']['dp'])){
            $dpC = " AND d.id = ".$params['query']['dp'];

            $cond .=' AND Customer.depot_id='.$params['query']['dp'];
        }
        if (!empty($params['query']['rt'])){
            $cond .=' AND Customer.route_id='.$params['query']['rt'];
        }

        if (!empty($params['query']['us'])){
            $susC = " AND sl.user_id =".$params['query']['us'];
            $rsusC = " AND rsi.user_id =".$params['query']['us'];
            $cond .=' AND cv.user_id ='.$params['query']['us'];
        } //echo $cond;exit;

        $custAC = " AND Customer.status =".ACTIVE;


        $result = array();
        if($activeCust){
            $scIdC = " AND sl.customer_id IN (".implode(",", $customerIds).")";
            $rscIdC = " AND rsi.customer_id IN (".implode(",", $customerIds).")";

            $saleEntry = $this->query("SELECT count(DISTINCT sl.order_id) as sentry, sl.customer_id, sl.user_id, sl.depot_id, sl.sale_date, d.title, d.region_id FROM sales sl INNER JOIN depots d ON d.id = sl.depot_id WHERE $sC $dv_regC $rgC $dpC $scIdC $susC GROUP BY sl.order_id"); //pr($saleEntry);

            $rsaleEntry = $this->query("SELECT count(DISTINCT rsi.redistributor_sale_id) as rsentry, rsi.customer_id, rsi.user_id, rsi.depot_id, rsi.sale_date, d.title, d.region_id FROM redistributor_saleitems rsi INNER JOIN depots d ON d.id = rsi.depot_id WHERE $rsC $dv_regC $rgC $dpC $rscIdC $rsusC GROUP BY rsi.redistributor_sale_id");


            //$customerUserVisits = $this->query("SELECT Customer.id,Customer.route_id, cv.user_id, COUNT(cv.id) AS visits FROM `customers` AS Customer LEFT JOIN `customer_visits` AS cv ON Customer.id=cv.customer_id  WHERE  Customer.id IN (".implode(",", $customerIds).") AND $cvC  $cond $custAC GROUP BY Customer.id, cv.user_id ");
            //$customerUserVisits = $this->query("SELECT Customer.id,Customer.route_id, cv.user_id,cv.visiting_date, IF(cv.id > 0, 1, 0) AS visits FROM `customers` AS Customer LEFT JOIN `customer_visits` AS cv ON Customer.id=cv.customer_id  WHERE  Customer.id IN (".implode(",", $customerIds).") AND $cvC  $cond $custAC");
            if(!empty($params['cvisityear_tables'])){
                foreach ($params['cvisityear_tables'] as $year => $cv_tableName){
                    $customerUserVisitsSel[$year] = $this->query("SELECT Customer.id,Customer.route_id, cv.user_id,cv.visiting_date, IF(cv.id > 0, 1, 0) AS visits FROM `customers` AS Customer LEFT JOIN $cv_tableName AS cv ON Customer.id=cv.customer_id  WHERE  Customer.id IN (".implode(",", $customerIds).") AND $cvC  $cond $custAC");
                }
            }
        }

        $activity = array();
        foreach($saleEntry as $sale){
            $cid = $sale['sl']['customer_id'];
            $uid = !empty($sale['sl']['user_id']) ? $sale['sl']['user_id'] : 0;
			$saledate = $sale['sl']['sale_date'];

            if(isset($activity[$cid][$uid]['sales'])){
                $activity[$cid][$uid]['sales'] += $sale['0']['sentry'];
            }else{
                $activity[$cid][$uid]['sales'] = $sale['0']['sentry'];
            }
			
			if(isset($activity[$cid][$uid]['sale_dates'])){
                $activity[$cid][$uid]['sale_dates'] = $activity[$cid][$uid]['sale_dates'].', '.$saledate;
            }else{
                $activity[$cid][$uid]['sale_dates'] = $saledate;
            }

            if(isset($activity[$cid][$uid]['utotalsales'])){
                $activity[$cid][$uid]['utotalsales'] += $sale['0']['sentry'];
            }else{
                $activity[$cid][$uid]['utotalsales'] = $sale['0']['sentry'];
            }
        }

        foreach($rsaleEntry as $rsale){
            $cid = $rsale['rsi']['customer_id'];
            $uid = !empty($rsale['rsi']['user_id'])? $rsale['rsi']['user_id'] : 0;
			$saledate = $rsale['rsi']['sale_date'];

            if(isset($activity[$cid][$uid]['rsales'])){
                $activity[$cid][$uid]['rsales'] += $rsale['0']['rsentry'];
            }else{
                $activity[$cid][$uid]['rsales'] = $rsale['0']['rsentry'];
            }
			
			if(isset($activity[$cid][$uid]['rsale_dates'])){
                $activity[$cid][$uid]['rsale_dates'] = $activity[$cid][$uid]['rsale_dates'].', '.$saledate;
            }else{
                $activity[$cid][$uid]['rsale_dates'] = $saledate;
            }

            if(isset($activity[$cid][$uid]['utotalsales'])){
                $activity[$cid][$uid]['utotalsales'] += $rsale['0']['rsentry'];
            }else{
                $activity[$cid][$uid]['utotalsales'] = $rsale['0']['rsentry'];
            }
        }

/*
        foreach($customerUserVisits as $cuv){
        ///pr($customerUserVisits);exit;
            $cid = $cuv['Customer']['id'];
            $cvuid = !empty($cuv['cv']['user_id']) ? $cuv['cv']['user_id'] :0;
            $cvdate = date("Y-m-d", strtotime($cuv['cv']['visiting_date']));

            if(isset($activity[$cid][$cvuid]['visits'])){
                $activity[$cid][$cvuid]['visits'] += $cuv['0']['visits'];
                $activity[$cid][$cvuid]['visiting_dates'] = $activity[$cid][$cvuid]['visiting_dates'].', '.$cvdate;
            }else{
                $activity[$cid][$cvuid]['visits'] = $cuv['0']['visits'];
                $activity[$cid][$cvuid]['visiting_dates'] = $cvdate;
            }
        } */

        if (!empty($customerUserVisitsSel)) {
            foreach ($customerUserVisitsSel as $year => $customerUserVisits) {
                foreach($customerUserVisits as $cuv){
                    //pr($customerUserVisits);//exit;
                    $cid = $cuv['Customer']['id'];
                    $cvuid = !empty($cuv['cv']['user_id']) ? $cuv['cv']['user_id'] :0;
                    $cvdate = date("Y-m-d", strtotime($cuv['cv']['visiting_date']));

                    if(isset($activity[$cid][$cvuid]['visits'])){
                        $activity[$cid][$cvuid]['visits'] += $cuv['0']['visits'];
                        $activity[$cid][$cvuid]['visiting_dates'] = $activity[$cid][$cvuid]['visiting_dates'].', '.$cvdate;
                    }else{
                        $activity[$cid][$cvuid]['visits'] = $cuv['0']['visits'];
                        $activity[$cid][$cvuid]['visiting_dates'] = $cvdate;
                    }
                }
            }
        }

       // pr($activity);exit;


        if(!empty($customerUserVisits) || !empty($saleEntry) || !empty($rsaleEntry)){
            foreach ($activeCust as $key => $cust){
                $customer_id = $cust['Customer']['id'];
                if (!empty($activity[$customer_id])){
                    #Set Total Sale which is sale+rsale per customer
                    foreach ($activity[$customer_id] as $uid => $uData){
                        $totalSales = !empty($uData['utotalsales'])? $uData['utotalsales']  : 0;
                        if(isset($activeCust[$key]['0']['totalSales'])){
                            $activeCust[$key]['0']['totalSales'] += $totalSales;
                        }else{
                            $activeCust[$key]['0']['totalSales'] = $totalSales;
                        }
                    }
                    $activeCust[$key]['cvbyUser'] = $activity[$customer_id];

                }
            }
        }

        //pr($activeCust);exit;


    }
	

	function usersCallsFrequencySummary_V3($params){ //pr($params); die();
        $output = array();
		       
		//$date = $params['date'];
		$dateParams = $params['dateParams']; //pr($dateParams); die();
					

		switch($params['type']){
			case 'daily':
				$date = $dateParams['date'];
				$d1 = $d2 = $date;
                $oC = "sl.sale_date = '$date'";
                $fiC = "fi.sale_date = '$date'";
                $rdC = "rsi.sale_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
				//$ccC = "c.created = '$date'";
				$ccC = "c.created <= '$date 23:59:59'";
				$vcC = "c.verified_date <= '$date'";
				$inC = "inc.incentive_date = '$date'";
			break;
			default:
				$d1 = $dateParams['from'];
				$d2 = $dateParams['to'];

                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $fiC = "fi.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                //$ccC = "c.created between '$d1' AND '$d2 23:59:59'";
				$ccC = "c.created <= '$d2 23:59:59'";
				$vcC = "c.verified_date <= '$d2'";
				$inC = "inc.incentive_date between '$d1' AND '$d2'";
			break;					
		}
		
		$userRouteCond = "";
		$rpPeriodByDates = $diffRPPeriodDates = [];
		
        switch($params['type']){
            case 'daily': //pr($params['dateParams']);
			
				$ptg_year 	= date('Y', strtotime($params['dateParams']['date']));
				$ptg_month 	= $params['dateParams']['month'];
				$ptg_week 	= $params['dateParams']['week'];
				$ptg_day 	= date('l', strtotime($params['dateParams']['date']));
				
				$i_ptgPeriod = ['year' => $ptg_year, 'month' => $ptg_month, 'week' => $ptg_week];
				
				$rpPeriod = getRoutePlanPeriod($params['dateParams']['date'], $params['RPTGCalendar']);
				
				$rp_year  	= $rpPeriod['year'];
				$rp_month 	= $rpPeriod['month'];
				$rp_week  	= $rpPeriod['week'];				
				$rp_day 	= date('l', strtotime($params['dateParams']['date']));
			
				$userRouteCond = " AND ur.year = '$rp_year' AND ur.month = '$rp_month' AND ur.week = '$rp_week' AND ur.day = '$rp_day'";
				
				// Check if PTG calendar period differs from route plan period
				if ($i_ptgPeriod['year']  != $rp_year || $i_ptgPeriod['month'] != $rp_month || $i_ptgPeriod['week']  != $rp_week
				){
					$rpPeriodByDates[$params['dateParams']['date']] 	= ['year'  => $rp_year, 'month' => $rp_month, 'week'  => $rp_week, 'day'   => $rp_day];
					$diffRPPeriodDates[] 	= $params['dateParams']['date'];
				}
                
				
				break;
			

			case 'weekly':
				$ptg_year 	= date('Y', strtotime($params['dateParams']['from']));
				$ptg_month 	= $params['dateParams']['month'];
				$ptg_week 	= $params['dateParams']['week'];
				
				$i_ptgPeriod = ['year' => $ptg_year, 'month' => $ptg_month, 'week' => $ptg_week];
				
				$datesInWeekArr = $params['RPTGCalendar']['calendar'][$ptg_month][$ptg_week]; 
				if(count($datesInWeekArr) > 7){
					$buildDailyRouteCondData = buildDailyRouteConditions($datesInWeekArr, $params['RPTGCalendar'], $i_ptgPeriod);

					// Build final condition
					$userRouteCond = " AND (" . implode(" OR ", $buildDailyRouteCondData['sqlConditions']) . ")";
					
					$rpPeriodByDates = $buildDailyRouteCondData['rpPeriodByDates'];
					$diffRPPeriodDates = $buildDailyRouteCondData['diffRPPeriodDates'];

				}else{
					$userRouteCond = " AND ur.year = '$ptg_year' AND ur.month = '$ptg_month' AND ur.week = '$ptg_week'";
				}
			
				
				break;

				
			case 'monthly':
				$ptg_year 	= date('Y', strtotime($params['dateParams']['from']));
				$ptg_month 	= $params['dateParams']['month'];
				
				$monthlyRouteConditions = [];
				
				foreach ($params['RPTGCalendar']['calendar'][$ptg_month] as $i_ptg_weekNo => $datesInWeekArr) {

					// Week with >7 days — process each day
					if (count($datesInWeekArr) > 7) {
						$params['RPTGCalendar']['week'] = $i_ptg_weekNo;
						
						$i_ptgPeriod = ['year' => $ptg_year, 'month' => $ptg_month, 'week' => $i_ptg_weekNo];
						
						$buildDailyRouteCondData = buildDailyRouteConditions($datesInWeekArr,$params['RPTGCalendar'], $i_ptgPeriod ); 
						$monthlyRouteConditions = array_merge($monthlyRouteConditions, $buildDailyRouteCondData['sqlConditions']);
						
						$rpPeriodByDates   = array_merge($rpPeriodByDates, $buildDailyRouteCondData['rpPeriodByDates']);
						$diffRPPeriodDates = array_merge($diffRPPeriodDates, $buildDailyRouteCondData['diffRPPeriodDates']);

					} else {
						// Regular week — use simple condition
						$monthlyRouteConditions[] =
							"ur.year = '$ptg_year' AND ur.month = '$ptg_month' AND ur.week = '$i_ptg_weekNo'";
					}
				}

				// Final combined filter for the month
				$userRouteCond = " AND (" . implode(" OR ", $monthlyRouteConditions) . ")";

				break;
			
			case 'between':
				## NEED TO Work On this
				$userRouteCond = ""; //pr($userRouteCond);
			
                break;
            
        }
    
        $userDVC = $userRC = $userDC = $userId = "";
		$depot_ids = array();
        if (!empty($params['query']['dv'])){
            $userDVC = " AND u.division_id = ".$params['query']['dv'];
			
			$DivisionsRegion=  ClassRegistry::init('DivisionsRegion');
			$rIds = $DivisionsRegion->find('list', array('fields'=>array('region_id'),'conditions'=>array('division_id'=>$params['query']['dv'])));
			
			$Depot = ClassRegistry::init('Depot'); 
			$depot_ids = $Depot ->find('list', array('fields' => array('id'), 'conditions' => array('Depot.region_id' => $rIds )));  
		}
        if (!empty($params['query']['rg'])){
            $userRC = " AND u.region_id = ".$params['query']['rg'];
			
			$Depot = ClassRegistry::init('Depot'); 
			$depot_ids = $Depot ->find('list', array('fields' => array('id'), 'conditions' => array('Depot.region_id' => $params['query']['rg'])));
        }
        if (!empty($params['query']['dp'])){
            $userDC = " AND u.depot_id = ".$params['query']['dp'];
			
			$depot_ids = [$params['query']['dp']];
        }
		
		if (!empty($params['query']['us'])){
            $userId = " AND u.id = ".$params['query']['us'];
        }


        $result =  $customerActivity = array();
		
		//Get All users 
        $users = $user_ids = array();
		$usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.division_id, u.region_id, u.depot_id, u.role_id, u.status, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE  r.grade > 3 $userDVC $userDC $userRC $userId ORDER BY rg.title ASC, u.role_id ASC"); //pr($usersData );
		
		$DH_uids = [];
        foreach($usersData as $user){
			
            $rid = ($user['u']['region_id'])?$user['u']['region_id']:0;
            $did = ($user['u']['depot_id'])?$user['u']['depot_id']:0;

            $uid = $user['u']['id'];
			
            $users[$rid][$did][$uid] = array('name'=> $user['u']['first_name'].' '.$user['u']['last_name'], 'rid'=>$user['u']['role_id'], 'role'=>$user['r']['name'], 'division_id'=>$user['u']['division_id'], 'region_id'=>$user['u']['region_id'], 'depot'=>$user['d']['title'], 'status'=>$user['u']['status']);
			if (!in_array($uid, $user_ids)){
				array_push($user_ids, $uid);
			}
			
			if (!empty($params['query']['us'])){
				$depot_ids = array($did);
			}
			
			## list DH
			if($user['u']['role_id'] == DH){
				$DH_uids[] = $uid;
			}
			
        }
        $output['users'] = $users;
		
		//Expected Frequency
		$userRoutes = $this->query("SELECT ur.route_ids, ur.user_id, ur.year, ur.month, ur.week, ur.day FROM user_routes ur WHERE ur.user_id IN (".implode(', ', $user_ids).") ". $userRouteCond);
		//pr($userRoutes); die();
		
		$structuredUserRoutes = [];  // [uid][year][month][week][day] = structured array
		
		$result['userRouteNames'] = [];

		if(!empty($userRoutes)){
			$user_route_ids = $route_ids = array();

				foreach($userRoutes as $ur){
					$uid 	= !empty($ur['ur']['user_id']) ? $ur['ur']['user_id'] : 0 ;
					$urrids = !empty($ur['ur']['route_ids']) ? explode(',', $ur['ur']['route_ids']) : [];
					$uryr 	= !empty($ur['ur']['year']) ? $ur['ur']['year'] : 0 ;
					$urmn 	= !empty($ur['ur']['month']) ? $ur['ur']['month'] : 0 ;
					$urwk 	= !empty($ur['ur']['week']) ? $ur['ur']['week'] : 0 ;
					$urday  = !empty($ur['ur']['day']) ? $ur['ur']['day'] : "" ;
					
					// Collect all route IDs for later use
					$route_ids = array_unique(array_merge($route_ids, $urrids));
					$user_route_ids[$uid] = isset($user_route_ids[$uid]) ? array_unique(array_merge($user_route_ids[$uid], $urrids)) : $urrids;
					
					// ------------------------------------------------------------
					// Initialize structured routes entry
					// ------------------------------------------------------------
					if (!isset($structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday])) {
						$structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday] = [
							'route_ids'    => [],
							'custno'       => [],
							'custno_total' => []
						];
					}
					
					// ------------------------------------------------------------
					// Add the route IDs to route_ids only
					// ------------------------------------------------------------
					$structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday]['route_ids'] =
						array_unique(array_merge(
							$structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday]['route_ids'],
							$urrids
						));					
				}
				
			
		}  //pr($user_route_ids);
		//pr($structuredUserRoutes); die();
		
		
		$cnameC = " AND NOT (c.first_name IS NULL) AND NOT (c.last_name IS NULL)";
		if(!empty($route_ids)){
			
			// load route names
			$userRouteNames = [];
			
			$routeQuery = $this->query("SELECT id, title FROM routes WHERE id IN (" . implode(',', $route_ids) . ") ");
			
			if(!empty($routeQuery)){
				foreach ($routeQuery as $r) {
					$userRouteNames[$r['routes']['id']] = $r['routes']['title'];
				}
			}
			$result['userRouteNames'] = $userRouteNames;
		
		
		
		 // Prepare COUNT columns for each day in the period
			$custno_cases = [];

			// Loop through each day in the period and create a COUNT for each day			
			for ($dt = $d1; $dt <= $d2; $dt = date('Y-m-d', strtotime('+1 day', strtotime($dt)))) {
				$col = 'cust_' . str_replace('-', '_', $dt);
				$custno_cases[] = "COUNT(CASE WHEN c.created <= '$dt 23:59:59' THEN c.id END) AS $col";
			}
			$custnoCols = implode(', ', $custno_cases);
			
			//Fetch customer counts per route and user
			$userRouteCustomers = $this->query("SELECT $custnoCols, c.route_id, c.user_id FROM customers c WHERE $ccC $cnameC AND c.status = 1 AND c.route_id IN (" . implode(', ', $route_ids) . ") GROUP BY c.route_id, c.user_id");
						
			//pr($userRouteCustomers); //die();
			
			//Preprocess $userRouteCustomers into a lookup map for route counts
			
			$userRouteCustCounts = []; // [user][route][date] = count
			if (!empty($userRouteCustomers)) {
				foreach ($userRouteCustomers as $row) {
					$uid = $row['c']['user_id'];
					$rid = $row['c']['route_id'];
					foreach ($row[0] as $col => $val) {
						if (strpos($col, 'cust_') !== 0) continue;
						$dt = str_replace(['cust_', '_'], ['', '-'], $col);
						$userRouteCustCounts[$uid][$rid][$dt] = intval($val);
					}
				}
			}

		}
		

		// Loop through full period and populate structuredUserRoutes
		for ($dt = $d1; $dt <= $d2; $dt = date('Y-m-d', strtotime('+1 day', strtotime($dt)))) {
			$yr_key = date('Y', strtotime($dt));
			$dy_key = date('l', strtotime($dt));
			$mn_key = $dateParams['month'];

			if (in_array($params['type'], ['daily', 'weekly'])) {
				$wk_key = $dateParams['week'];
			} elseif($params['type'] == 'monthly') { // monthly 
				$wk_key = getWeekNo($params['RPTGCalendar']['calendar'][$dateParams['month']], $dt); 
			}else{
				// between 
				### NEED TO WORK
			}
			
			// Override with route plan period if date is in diffRPPeriodDates
			if (in_array($dt, $diffRPPeriodDates) && isset($rpPeriodByDates[$dt])) {
				$yr_key = $rpPeriodByDates[$dt]['year'];
				$mn_key = $rpPeriodByDates[$dt]['month'];
				$wk_key = $rpPeriodByDates[$dt]['week'];
			}
			
			if(!empty($structuredUserRoutes)){
				foreach ($structuredUserRoutes as $uid => &$yearsArr) {

					if (!isset($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key])) {
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key] = [
							'route_ids' => [],
							'custno' => [],
							'custno_total' => []
						];
					}

					// If routes exist, assign counts
					foreach ($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['route_ids'] as $rid) {
						$count = isset($userRouteCustCounts[$uid][$rid][$dt]) ? $userRouteCustCounts[$uid][$rid][$dt] : 0;
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['custno'][$dt][$rid] = $count;
						if (!isset($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['custno_total'][$dt])) {
							$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['custno_total'][$dt] = 0;
						}
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['custno_total'][$dt] += $count;
					}

					// If no route_ids, still assign zero for custno_total
					if (empty($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['route_ids'])) {
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['custno_total'][$dt] = 0;
					}
				}
			}else{
				$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key] = [
					'route_ids' => [],
					'custno' => [],
					'custno_total' => []
				];
			}
			
			//pr($structuredUserRoutes );
			
		}

		// Build daily & weekly expected frequency for **all dates**, even with no routes
		foreach ($structuredUserRoutes as $uid => $yearsArr) {
			$result[$uid]['expected_freq'] = 0;

			for ($dt = $d1; $dt <= $d2; $dt = date('Y-m-d', strtotime('+1 day', strtotime($dt)))) {
				$yr_key = date('Y', strtotime($dt));
				$dy_key = date('l', strtotime($dt));
				$mn_key = $dateParams['month'];

				if (in_array($params['type'], ['daily', 'weekly'])) {
					$wk_key = $dateParams['week'];
				} else {
					$wk_key = getWeekNo($params['RPTGCalendar']['calendar'][$dateParams['month']], $dt); 
					//$wk_key = getWeekNo($params['RPTGCalendar']['calendar'][$dateParams['month']], $dt); 
				}
				
				$rp_yr_key = $yr_key; $rp_mn_key = $mn_key; $rp_wk_key = $wk_key;
				// Override with route plan period if date is in diffRPPeriodDates
				if (in_array($dt, $diffRPPeriodDates) && isset($rpPeriodByDates[$dt])) {
					$rp_yr_key = $rpPeriodByDates[$dt]['year'];
					$rp_mn_key = $rpPeriodByDates[$dt]['month'];
					$rp_wk_key = $rpPeriodByDates[$dt]['week'];
				}

				$dayInfo = isset($structuredUserRoutes[$uid][$rp_yr_key][$rp_mn_key][$rp_wk_key][$dy_key]) 
						   ? $structuredUserRoutes[$uid][$rp_yr_key][$rp_mn_key][$rp_wk_key][$dy_key] 
						   : ['custno' => [], 'custno_total' => [ $dt => 0 ]];

				$routes = isset($dayInfo['custno'][$dt]) ? $dayInfo['custno'][$dt] : [];
				
				$dateObj = DateTime::createFromFormat('!m', $mn_key);
				$ptgMonthName = $dateObj->format('M');
				$ptgCalPeriod = $ptgMonthName . " " . $yr_key  . ", Week " . $wk_key;

				// Route Plan Period (inline)
				$dateObj = DateTime::createFromFormat('!m', $rp_mn_key);
				$rpMonthName = $dateObj->format('M');
				$routePlanPeriod = "$rpMonthName $rp_yr_key, Week $rp_wk_key";

				if (in_array($params['type'], ['daily', 'weekly'])) {
					$result[$uid]['userDailyExpFreq'][$dt] = [
						'ptgCalPeriod' => $ptgCalPeriod,
						'routePlanPeriod' => $routePlanPeriod,
						'day' => $dy_key,
						'routes' => $routes
					];
				} else {
					if (!isset($result[$uid]['userWklyExpFreq'][$mn_key][$wk_key])) {
						$result[$uid]['userWklyExpFreq'][$mn_key][$wk_key] = [
							'expectedFreq' 		=> 0,
							'ptgWeekRange' 		=> ['from' => $dt, 'to' => $dt],
							'RPPeriodRange' 	=> [['year'  => $rp_yr_key, 'month' => $rp_mn_key, 'week'  => $rp_wk_key, 'from'  => $dt, 'to'    => $dt]]];
					} else {
						$weekData = &$result[$uid]['userWklyExpFreq'][$mn_key][$wk_key]; //pr($weekData); die();
						
						// Update PTG week range
						if (strtotime($dt) < strtotime($weekData['ptgWeekRange']['from'])) $weekData['ptgWeekRange']['from'] = $dt;
						if (strtotime($dt) > strtotime($weekData['ptgWeekRange']['to'])) $weekData['ptgWeekRange']['to'] = $dt;
						
						// Merge or add route plan period ranges
						$lastIndex = count($weekData['RPPeriodRange']) - 1;
						$lastRange = &$weekData['RPPeriodRange'][$lastIndex];
						$expectedNextDate = date('Y-m-d', strtotime($lastRange['to'] . ' +1 day'));

						if ($lastRange['year'] == $rp_yr_key && $lastRange['month'] == $rp_mn_key && $lastRange['week'] == $rp_wk_key && $expectedNextDate == $dt) {
							$lastRange['to'] = $dt; // extend range
						} else {
							$weekData['RPPeriodRange'][] = ['year'  => $rp_yr_key, 'month' => $rp_mn_key, 'week' => $rp_wk_key, 'from' => $dt, 'to' => $dt ];
						}
					}
					
					$result[$uid]['userWklyExpFreq'][$mn_key][$wk_key]['expectedFreq'] += array_sum($routes);
				}

				$result[$uid]['expected_freq'] += array_sum($routes);
			}
		}

		


		
		//pr($depot_ids); die();
		
		$odpC = $fidpC = $rddpC = $indpC = $cvdpC = "";
		// Only build conditions if depot_ids is not empty and not just [0]
		if (!empty($depot_ids) && !(count($depot_ids) === 1 && $depot_ids[0] == 0)) {
			$odpC = " AND sl.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$fidpC = " AND fi.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$rddpC = " AND rsi.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$indpC = " AND inc.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$cvdpC = " AND cv.depot_id IN (" . implode(', ', $depot_ids) . ")";
		}
		
		$orderEntry = $this->query("SELECT SUM(sl.cal_qty) AS totQty, COUNT(DISTINCT CONCAT(sl.customer_id, '-', sl.sale_date)) AS oentry, sl.user_id, sl.depot_id, sl.sale_date, sl.customer_id, sl.via_app FROM sales sl WHERE $oC $odpC GROUP BY sl.user_id, sl.sale_date, sl.customer_id, sl.via_app"); //pr($orderEntry); //die();

		$freeItemEntry = $this->query("SELECT SUM(fi.cal_qty) AS totQtyFi, fi.user_id, fi.depot_id, fi.sale_date, fi.customer_id, fi.via_app FROM free_items fi WHERE $fiC $fidpC GROUP BY fi.user_id, fi.sale_date, fi.customer_id, fi.via_app"); //pr($freeItemEntry); //die();

        
		$rSaleEntry = $this->query("SELECT SUM(rsi.cal_qty) AS totQty, COUNT(DISTINCT CONCAT(rsi.customer_id, '-', rsi.sale_date)) AS rsentry, rsi.user_id, rsi.depot_id, rsi.sale_date, rsi.customer_id, rsi.via_app FROM redistributor_saleitems rsi WHERE $rdC $rddpC GROUP BY rsi.user_id, rsi.sale_date, rsi.customer_id, rsi.via_app"); //pr($rSaleEntry); 
		
		$incentiveEntry = $this->query("SELECT SUM(inc.cal_qty) AS totQty, COUNT(DISTINCT CONCAT(inc.customer_id, '-', inc.incentive_date)) AS incentry, inc.user_id, inc.depot_id, inc.incentive_date, inc.customer_id, inc.via_app FROM incentives inc INNER JOIN customers as c on inc.customer_id = c.id WHERE $inC $indpC GROUP BY inc.user_id, inc.incentive_date, inc.customer_id, inc.via_app"); //pr($incentiveEntry); 
	
        if(!empty($params['cvisityear_tables'])) {
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName) {
				$visitEntries[$year] = $this->query("SELECT COUNT(DISTINCT CONCAT(cv.customer_id, '-', date(cv.visiting_date))) AS ventry, cv.user_id, cv.depot_id, date(cv.visiting_date) as vdate, cv.customer_id, cv.via_app FROM $cv_tableName cv WHERE $cvC $cvdpC GROUP BY cv.user_id, date(cv.visiting_date), cv.customer_id, cv.via_app");
            }
        }
        //pr($visitEntries);  die();

		//Count customers created
        //$customerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM customers c WHERE c.status = ".ACTIVE." AND c.user_id IN (".implode(', ', $user_ids).") GROUP BY c.user_id");
		
		$customerEntry = $this->query("SELECT c.id, c.user_id, c.verified_latitude, c.verified_longitude, c.verified_by, c.verified_date FROM customers c WHERE $ccC $cnameC AND c.status = ".ACTIVE." AND c.user_id IN (".implode(', ', $user_ids).")"); 

        //$vc = 0;
        if (!empty($customerEntry)){
            foreach ($customerEntry as $c){
				$uid = !empty($c['c']['user_id']) ? $c['c']['user_id'] : 0 ;
				
				$result[$uid]['customers'][] = $c['c']['id'];
				
				/*if(!empty($c['c']['verified_latitude']) && !empty($c['c']['verified_longitude']) && !empty($c['c']['verified_by']) && !empty($c['c']['verified_date'])){
					$result[$uid]['verified_customers'][] = $c['c']['id'];
				}*/
                //$result[$uid]['totalCustomer'] = $c['0']['cCreated'];
            }
        }
        
        $verifiedCustomerEntry = $this->query("SELECT c.id, c.user_id, c.verified_latitude, c.verified_longitude, c.verified_by, c.verified_date FROM customers c WHERE $vcC $cnameC AND c.status = ".ACTIVE." AND c.user_id IN (".implode(', ', $user_ids).")"); 
        
        if (!empty($verifiedCustomerEntry)){
            foreach ($verifiedCustomerEntry as $c){
				$uid = !empty($c['c']['user_id']) ? $c['c']['user_id'] : 0 ;
				
				if(!empty($c['c']['verified_latitude']) && !empty($c['c']['verified_longitude']) && !empty($c['c']['verified_by']) && !empty($c['c']['verified_date'])){
					$result[$uid]['verified_customers'][] = $c['c']['id'];
					
					//++$vc;
				}
                //$result[$uid]['totalCustomer'] = $c['0']['cCreated'];
            }
        }
        //pr('Verified Customers '.$vc);
  
		//pr($result);
		//pr($orderEntry);
		if (!empty($orderEntry)){
            foreach ($orderEntry as $oe){
                $uid = !empty($oe['sl']['user_id']) ? $oe['sl']['user_id'] : 0 ;
				$cid = !empty($oe['sl']['customer_id']) ? $oe['sl']['customer_id'] : 0 ; 
                $did = !empty($oe['sl']['depot_id']) ? $oe['sl']['depot_id'] : 0;
                $sale_date = date(DATE_FORMAT_SORT, strtotime($oe['sl']['sale_date']));
				
				if(!empty($oe['sl']['via_app'])){
					if(empty($result[$uid]['call']['saleEntry'])){
						$result[$uid]['call']['saleEntry'] = $oe['0']['oentry'];
					}else{
						$result[$uid]['call']['saleEntry'] += $oe['0']['oentry'];
					}
					
					if(empty($result[$uid]['call']['customerCalls'][$cid]['saleEntry'])){
						$result[$uid]['call']['customerCalls'][$cid]['saleEntry'] = $oe['0']['oentry'];
					}else{
						$result[$uid]['call']['customerCalls'][$cid]['saleEntry'] += $oe['0']['oentry'];
					}
					if(empty($result[$uid]['call']['customersVisited'][$cid])){
						$result[$uid]['call']['customersVisited'][$cid] = array($sale_date);
					}else{
						/* if(!in_array($sale_date, $result[$uid]['call']['customersVisited'][$cid])){
							$result[$uid]['call']['customersVisited'][$cid] = array($sale_date);
						}else{
							array_push($result[$uid]['call']['customersVisited'][$cid], $sale_date);
						} */
						if(!in_array($sale_date, $result[$uid]['call']['customersVisited'][$cid])){ 
							array_push($result[$uid]['call']['customersVisited'][$cid], $sale_date);
						}
					}
					//customer activity 
					$activityCall = ['type' => 'saleEntry', 'saleEntry' => $oe['0']['oentry'], 'saleVol' => $oe['0']['totQty']];
					if (!isset($customerActivity[$cid]['calls'][$sale_date][$uid])) {
						$customerActivity[$cid]['calls'][$sale_date][$uid] = [$activityCall];
					} else {
						$customerActivity[$cid]['calls'][$sale_date][$uid][] = $activityCall;
					}
				}				
				
				if(empty($result[$uid]['call']['saleVol'])){
					$result[$uid]['call']['saleVol'] = $oe['0']['totQty'];
				}else{
					$result[$uid]['call']['saleVol'] += $oe['0']['totQty'];
				}
								
				if(empty($result[$uid]['call']['customerCalls'][$cid]['saleVol'])){
					$result[$uid]['call']['customerCalls'][$cid]['saleVol'] = $oe['0']['totQty'];
				}else{
					$result[$uid]['call']['customerCalls'][$cid]['saleVol'] += $oe['0']['totQty'];
				}

            }
        }
        
        
        if (!empty($freeItemEntry)){
            foreach ($freeItemEntry as $fe){
                $uid = !empty($fe['fi']['user_id']) ? $fe['fi']['user_id'] : 0 ;
				$cid = !empty($fe['fi']['customer_id']) ? $fe['fi']['customer_id'] : 0 ;
                $did = !empty($fe['fi']['depot_id']) ? $fe['fi']['depot_id'] : 0;
                $sale_date = date(DATE_FORMAT_SORT, strtotime($fe['fi']['sale_date']));

				
				if(empty($result[$uid]['call']['saleFiVol'])){
					$result[$uid]['call']['saleFiVol'] = $fe['0']['totQtyFi'];
				}else{
					$result[$uid]['call']['saleFiVol'] += $fe['0']['totQtyFi'];
				}
								
				if(empty($result[$uid]['call']['customerCalls'][$cid]['saleFiVol'])){
					$result[$uid]['call']['customerCalls'][$cid]['saleFiVol'] = $fe['0']['totQtyFi'];
				}else{
					$result[$uid]['call']['customerCalls'][$cid]['saleFiVol'] += $fe['0']['totQtyFi'];
				}
				
				//customer activity 
				$activityCall = ['type' => 'saleFi', 'saleFiVol' => $fe['0']['totQtyFi']];
				if (!isset($customerActivity[$cid]['calls'][$sale_date][$uid])) {
					$customerActivity[$cid]['calls'][$sale_date][$uid] = [$activityCall];
				} else {
					$customerActivity[$cid]['calls'][$sale_date][$uid][] = $activityCall;
				}

            }
        }
	
		if (!empty($rSaleEntry)){
            foreach ($rSaleEntry as $rse){
                $uid = !empty($rse['rsi']['user_id']) ? $rse['rsi']['user_id'] : 0 ;
				$cid = !empty($rse['rsi']['customer_id']) ? $rse['rsi']['customer_id'] : 0 ;
                $did = !empty($rse['rsi']['depot_id']) ? $rse['rsi']['depot_id'] : 0;
				$sale_date = date(DATE_FORMAT_SORT, strtotime($rse['rsi']['sale_date']));
                
				if(!empty($rse['rsi']['via_app'])){
					if(empty($result[$uid]['call']['rsSaleEntry'])){
						$result[$uid]['call']['rsSaleEntry'] = $rse['0']['rsentry'];
					}else{
						$result[$uid]['call']['rsSaleEntry'] += $rse['0']['rsentry'];
					}
					if(empty($result[$uid]['call']['customerCalls'][$cid]['rsSaleEntry'])){
						$result[$uid]['call']['customerCalls'][$cid]['rsSaleEntry'] = $rse['0']['rsentry'];
					}else{
						$result[$uid]['call']['customerCalls'][$cid]['rsSaleEntry'] += $rse['0']['rsentry'];
					}
					if(empty($result[$uid]['call']['customersVisited'][$cid])){
						$result[$uid]['call']['customersVisited'][$cid] = array($sale_date);
					}else{
						if(!in_array($sale_date, $result[$uid]['call']['customersVisited'][$cid])){ 
							array_push($result[$uid]['call']['customersVisited'][$cid], $sale_date);
						}
					}
					
					//customer activity 
					$activityCall = ['type' => 'rsSaleEntry', 'rsSaleEntry' => $rse['0']['rsentry'], 'rsSaleVol' => $rse['0']['totQty']];
					if (!isset($customerActivity[$cid]['calls'][$sale_date][$uid])) {
						$customerActivity[$cid]['calls'][$sale_date][$uid] = [$activityCall];
					} else {
						$customerActivity[$cid]['calls'][$sale_date][$uid][] = $activityCall;
					}
				}
				
				if(empty($result[$uid]['call']['rsSaleVol'])){
					$result[$uid]['call']['rsSaleVol'] = $rse['0']['totQty'];
				}else{
					$result[$uid]['call']['rsSaleVol'] += $rse['0']['totQty'];
				}
							
				if(empty($result[$uid]['call']['customerCalls'][$cid]['rsSaleVol'])){
					$result[$uid]['call']['customerCalls'][$cid]['rsSaleVol'] = $rse['0']['totQty'];
				}else{
					$result[$uid]['call']['customerCalls'][$cid]['rsSaleVol'] += $rse['0']['totQty'];
				}
            }
        }
		
		if (!empty($incentiveEntry)){
            foreach ($incentiveEntry as $ine){
                $uid = !empty($ine['inc']['user_id']) ? $ine['inc']['user_id'] : 0 ;
				$cid = !empty($ine['inc']['customer_id']) ? $ine['inc']['customer_id'] : 0 ; 
                $did = !empty($ine['inc']['depot_id']) ? $ine['inc']['depot_id'] : 0;
				$incentive_date = date(DATE_FORMAT_SORT, strtotime($ine['inc']['incentive_date']));
               	
				if(!empty($ine['inc']['via_app'])){
					if(empty($result[$uid]['call']['incentiveEntry'])){
						$result[$uid]['call']['incentiveEntry'] = $ine['0']['incentry'];
					}else{
						 $result[$uid]['call']['incentiveEntry'] += $ine['0']['incentry'];
					}					
					if(empty($result[$uid]['call']['customerCalls'][$cid]['incentiveEntry'])){
						$result[$uid]['call']['customerCalls'][$cid]['incentiveEntry'] = $ine['0']['incentry'];
					}else{
						$result[$uid]['call']['customerCalls'][$cid]['incentiveEntry'] += $ine['0']['incentry'];
					}
					if(empty($result[$uid]['call']['customersVisited'][$cid])){
						$result[$uid]['call']['customersVisited'][$cid] = array($incentive_date);
					}else{
						if(!in_array($incentive_date, $result[$uid]['call']['customersVisited'][$cid])){
							array_push($result[$uid]['call']['customersVisited'][$cid], $incentive_date);
						}
					}
										
					//customer activity 					
					$activityCall = ['type' => 'incentiveEntry', 'incentiveEntry' => $ine['0']['incentry'], 'incentiveVol' => $ine['0']['totQty']];
					if (!isset($customerActivity[$cid]['calls'][$incentive_date][$uid])) {
						$customerActivity[$cid]['calls'][$incentive_date][$uid] = [$activityCall];
					} else {
						$customerActivity[$cid]['calls'][$incentive_date][$uid][] = $activityCall;
					}
				}
				
				if(empty($result[$uid]['call']['incentiveVol'])){
					$result[$uid]['call']['incentiveVol'] = $ine['0']['totQty'];
				}else{
					$result[$uid]['call']['incentiveVol'] += $ine['0']['totQty'];
				}			
				
				if(empty($result[$uid]['call']['customerCalls'][$cid]['incentiveVol'])){
					$result[$uid]['call']['customerCalls'][$cid]['incentiveVol'] = $ine['0']['totQty'];
				}else{
					$result[$uid]['call']['customerCalls'][$cid]['incentiveVol'] += $ine['0']['totQty'];
				}

            }
        }

		if (!empty($visitEntries)) { //pr($visitEntries);
            foreach ($visitEntries as $year => $visitFrequency) {
                foreach ($visitFrequency as $cve){
                    $uid = !empty($cve['cv']['user_id']) ? $cve['cv']['user_id'] : 0 ;
					$cid = !empty($cve['cv']['customer_id']) ? $cve['cv']['customer_id'] : 0 ;
                    $did = !empty($cve['cv']['depot_id'])?$cve['cv']['depot_id']:0;
					$vdate = date(DATE_FORMAT_SORT, strtotime( $cve[0]['vdate']));
					
					if(!empty($cve['cv']['via_app'])){
						if(empty($result[$uid]['call']['ventry'])){
							 $result[$uid]['call']['ventry'] = $cve['0']['ventry'];
						}else{
							$result[$uid]['call']['ventry'] += $cve['0']['ventry'];
						}
						
						if(empty($result[$uid]['call']['customerCalls'][$cid]['ventry'])){
							$result[$uid]['call']['customerCalls'][$cid]['ventry'] = $cve['0']['ventry'];
						}else{
							$result[$uid]['call']['customerCalls'][$cid]['ventry'] += $cve['0']['ventry'];
						}
						if(empty($result[$uid]['call']['customersVisited'][$cid])){
							$result[$uid]['call']['customersVisited'][$cid] = array($vdate);
						}else{
							if(!in_array($vdate, $result[$uid]['call']['customersVisited'][$cid])){
								array_push($result[$uid]['call']['customersVisited'][$cid], $vdate);
							}
						}

						//customer activity 
						$activityCall = ['type' => 'visitEntry', 'ventry' => $cve['0']['ventry']];
						if (!isset($customerActivity[$cid]['calls'][$vdate][$uid])) {
							$customerActivity[$cid]['calls'][$vdate][$uid] = [$activityCall];
						} else {
							$customerActivity[$cid]['calls'][$vdate][$uid][] = $activityCall;
						}
					}

                }

            }
        }
		
		$customerAddedBy = array(); //cid=>uid	
		
		if(!empty($params['user_id']) && !empty($result[$params['user_id']]['call']['customersVisited'])){
			$uid = $params['user_id']; 
			//$cidArr = array_keys($result[$uid]['call']['customersVisited']); 
			$cidArr = array_keys($customerActivity); 
			//pr(implode(', ', $cidArr));
			
			$customersData = $this->query("SELECT c.id, c.first_name, c.last_name, c.user_id, r.title FROM customers c LEFT JOIN routes r ON c.route_id = r.id WHERE c.id IN (".implode(', ', $cidArr).")");
			$customers = array();
			foreach ($customersData as $c){
				$customers[$c['c']['id']]['name'] = $c['c']['first_name'].' '.$c['c']['last_name'];
				$customers[$c['c']['id']]['route'] = $c['r']['title'];
				$customers[$c['c']['id']]['user_id'] = $c['c']['user_id'];
				
				$customerAddedBy[$c['c']['id']] = $c['c']['user_id'];
				
			} 
			$result[$uid]['customers_visited'] = $customers;

		}else{
			$Customer = ClassRegistry::init('Customer'); 
			$customerAddedBy = $Customer ->find('list', array('fields' => array('id','user_id'), 'conditions' => array('Customer.id' => array_keys($customerActivity))));
		}
		
		$User = ClassRegistry::init('User'); 
		$userNames = $User ->find('list', array('fields' => array('id','name')));
		
		//pr($customerActivity); 
		//pr($customerAddedBy);
		
		//pr($result[$uid]['call']['customersVisited']);
		//pr($result[368]['call']['customersVisited']);
		//pr(count($result[81]['call']['customersVisited'])); 
		
		//pr($result[81]['call']); 
		
		//“If two different users make entry on one customer in a day, the entry should be counted as one entry and the entry should be credited to the user who created the customer”
		
		//Know User IDs of Role RM and Above (Supervision Roles) : Currently, the report is generated only for DMs and roles below. Therefore, we do not need to perform debit-credit operations if the customer is visited by users with the role of RM or above.
		

		
		$supervisionRoleUserIds = $User->find('list', array('fields' => array('User.id'), 'joins' => array(array('table' => 'roles', 'alias' => 'Role', 'type' => 'INNER', 'conditions' => array('User.role_id = Role.id', 'Role.grade <=' => RM)))));  //pr(count($supervisionRoleUserIds));
		
		
		
		//pr($customerActivity);
		foreach($customerActivity as $cid => $calls){
			foreach($calls['calls'] as $date => $userEntries){
				
				$userIds = array_keys($userEntries); // get all user IDs who made entries on this customer on this date
				
				// Exclude supervision role users
				$userIds = array_diff($userIds, $supervisionRoleUserIds);
				
				// ❗Skip processing if only one or zero non-supervisory users are left
				if (count($userIds) <= 1) {
					continue;
				}
				
				//if(count($userIds) > 1){
					if(!empty($customerAddedBy[$cid])){
						$ownerId = $customerAddedBy[$cid];
						$ownerName = !empty($userNames[$ownerId]) ? $userNames[$ownerId] : "";

						// Get users who are NOT the creator of this customer
						$dupUsers = array_diff($userIds, [$ownerId]);
						
						// Create debitCalls / creditCalls
						foreach ($dupUsers as $uid) {  //pr($customerActivity[$cid]['calls'][$date][$uid]);
							if(!empty($customerActivity[$cid]['calls'][$date][$uid])){
								$userName = !empty($userNames[$uid]) ? $userNames[$uid] : "";

								$result['debitCalls'][$uid][] = ['date' => $date, 'creditedTo' => ['id' => $ownerId, 'name' => $ownerName], 'callDetails' => $customerActivity[$cid]['calls'][$date][$uid]];
								$result['creditCalls'][$ownerId][] = ['date' => $date, 'debitedFrom' => ['id' => $uid, 'name' => $userName], 'callDetails' => $customerActivity[$cid]['calls'][$date][$uid]];
								
								foreach($customerActivity[$cid]['calls'][$date][$uid] as $activity){ //pr($activity);
									switch($activity['type']){
										case 'saleEntry':
											// remove from users
												$result[$uid]['call']['saleEntry'] -= $activity['saleEntry'];
												//$result[$uid]['call']['saleVol'] -= $activity['saleVol'];
												
												// Add to owner
												$result[$ownerId]['call']['saleEntry'] = isset($result[$ownerId]['call']['saleEntry']) 
													? $result[$ownerId]['call']['saleEntry'] + $activity['saleEntry']
													: $activity['saleEntry'];

												/* $result[$ownerId]['call']['saleVol'] = isset($result[$ownerId]['call']['saleVol']) 
													? $result[$ownerId]['call']['saleVol'] + $activity['saleVol']
													: $activity['saleVol']; */
											break;
											
										/* case 'saleFi':
											// remove from users
												$result[$uid]['call']['saleFiVol'] -= $activity['saleFiVol'];
												
												// Add to owner
												$result[$ownerId]['call']['saleFiVol'] = isset($result[$ownerId]['call']['saleFiVol']) 
													? $result[$ownerId]['call']['saleFiVol'] + $activity['saleFiVol']
													: $activity['saleFiVol'];
											break; */
											
										case 'rsSaleEntry':
											// remove from users
												$result[$uid]['call']['rsSaleEntry'] -= $activity['rsSaleEntry'];
												//$result[$uid]['call']['rsSaleVol'] -= $activity['rsSaleVol'];
												
												// Add to owner
												$result[$ownerId]['call']['rsSaleEntry'] = isset($result[$ownerId]['call']['rsSaleEntry']) 
													? $result[$ownerId]['call']['rsSaleEntry'] + $activity['rsSaleEntry']
													: $activity['rsSaleEntry'];

												/* $result[$ownerId]['call']['rsSaleVol'] = isset($result[$ownerId]['call']['rsSaleVol']) 
													? $result[$ownerId]['call']['rsSaleVol'] + $activity['rsSaleVol']
													: $activity['rsSaleVol']; */
											break;												
											
										case 'incentiveEntry':
												// remove from users
												$result[$uid]['call']['incentiveEntry'] -= $activity['incentiveEntry'];
												//$result[$uid]['call']['incentiveVol'] -= $activity['incentiveVol'];
												
												// Add to owner
												$result[$ownerId]['call']['incentiveEntry'] = isset($result[$ownerId]['call']['incentiveEntry']) 
													? $result[$ownerId]['call']['incentiveEntry'] + $activity['incentiveEntry']
													: $activity['incentiveEntry'];

												/* $result[$ownerId]['call']['incentiveVol'] = isset($result[$ownerId]['call']['incentiveVol']) 
													? $result[$ownerId]['call']['incentiveVol'] + $activity['incentiveVol']
													: $activity['incentiveVol']; */
											break;
											
										case 'ventry':
											// remove from users
												$result[$uid]['call']['ventry'] -= $activity['ventry'];
												
												// Add to owner
												$result[$ownerId]['call']['ventry'] = isset($result[$ownerId]['call']['ventry']) 
													? $result[$ownerId]['call']['ventry'] + $activity['ventry']
													: $activity['ventry'];
											break;
											
										default:
											break;
									}
								}
							}
						}
						
						// remove customersVisited from other user
						if (!empty($result[$uid]['call']['customersVisited'][$cid])) {
							$dateIndex = array_search($date, $result[$uid]['call']['customersVisited'][$cid]);
							if ($dateIndex !== false) {
								unset($result[$uid]['call']['customersVisited'][$cid][$dateIndex]);
								$result[$uid]['call']['customersVisited'][$cid] = array_values($result[$uid]['call']['customersVisited'][$cid]);
								if (empty($result[$uid]['call']['customersVisited'][$cid])) {
									unset($result[$uid]['call']['customersVisited'][$cid]);
								}
							}
						}

						// Add customersVisited to owner
						if (!isset($result[$ownerId]['call']['customersVisited'][$cid])) {
							$result[$ownerId]['call']['customersVisited'][$cid] = [$date];
						} else {
							if (!in_array($date, $result[$ownerId]['call']['customersVisited'][$cid])) {
								$result[$ownerId]['call']['customersVisited'][$cid][] = $date;
							}
						}
					}
				//}
			}
		}

		//pr($result[$uid]['call']['customersVisited']);
		//pr($result[368]['call']['customersVisited']);
		//pr($result['debitCalls']);
		//pr($result['creditCalls']);
		
		
//pr($result);
        $output['result'] = $result;

        return $output;
    }
	
	function usersCallsFrequencySummary_V4($params){ //pr($params); die();
	
		$User = ClassRegistry::init('User'); 
		
		
        $output = array();
		       
		//$date = $params['date'];
		$dateParams = $params['dateParams']; //pr($dateParams); die();
					

		switch($params['type']){
			case 'daily':
				$date = $dateParams['date'];
				$d1 = $d2 = $date;
                $oC = "sl.sale_date = '$date'";
                $fiC = "fi.sale_date = '$date'";
                $rdC = "rsi.sale_date = '$date'";
                $cvC = "cv.visiting_date LIKE '".$date."%'";
				//$ccC = "c.created = '$date'";
				$ccC = "c.created <= '$date 23:59:59'";
				$vcC = "c.verified_date <= '$date'";
				$inC = "inc.incentive_date = '$date'";
			break;
			default:
				$d1 = $dateParams['from'];
				$d2 = $dateParams['to'];

                $oC = "sl.sale_date between '$d1' AND '$d2'";
                $fiC = "fi.sale_date between '$d1' AND '$d2'";
                $rdC = "rsi.sale_date between '$d1' AND '$d2'";
                $cvC = "cv.visiting_date between '$d1' AND '$d2 23:59:59'";
                //$ccC = "c.created between '$d1' AND '$d2 23:59:59'";
				$ccC = "c.created <= '$d2 23:59:59'";
				$vcC = "c.verified_date <= '$d2'";
				$inC = "inc.incentive_date between '$d1' AND '$d2'";
			break;					
		}
		
		$userRouteCond = "";
		$rpPeriodByDates = $diffRPPeriodDates = [];
		
        switch($params['type']){
            case 'daily': //pr($params['dateParams']);
			
				$ptg_year 	= date('Y', strtotime($params['dateParams']['date']));
				$ptg_month 	= $params['dateParams']['month'];
				$ptg_week 	= $params['dateParams']['week'];
				$ptg_day 	= date('l', strtotime($params['dateParams']['date']));
				
				$i_ptgPeriod = ['year' => $ptg_year, 'month' => $ptg_month, 'week' => $ptg_week];
				
				$rpPeriod = getRoutePlanPeriod($params['dateParams']['date'], $params['RPTGCalendar']);
				
				$rp_year  	= $rpPeriod['year'];
				$rp_month 	= $rpPeriod['month'];
				$rp_week  	= $rpPeriod['week'];				
				$rp_day 	= date('l', strtotime($params['dateParams']['date']));
			
				$userRouteCond = " AND ur.year = '$rp_year' AND ur.month = '$rp_month' AND ur.week = '$rp_week' AND ur.day = '$rp_day'";
				
				// Check if PTG calendar period differs from route plan period
				if ($i_ptgPeriod['year']  != $rp_year || $i_ptgPeriod['month'] != $rp_month || $i_ptgPeriod['week']  != $rp_week
				){
					$rpPeriodByDates[$params['dateParams']['date']] 	= ['year'  => $rp_year, 'month' => $rp_month, 'week'  => $rp_week, 'day'   => $rp_day];
					$diffRPPeriodDates[] 	= $params['dateParams']['date'];
				}
                
				
				break;
			

			case 'weekly':
				$ptg_year 	= date('Y', strtotime($params['dateParams']['from']));
				$ptg_month 	= $params['dateParams']['month'];
				$ptg_week 	= $params['dateParams']['week'];
				
				$i_ptgPeriod = ['year' => $ptg_year, 'month' => $ptg_month, 'week' => $ptg_week];
				
				$datesInWeekArr = $params['RPTGCalendar']['calendar'][$ptg_month][$ptg_week]; 
				if(count($datesInWeekArr) > 7){
					$buildDailyRouteCondData = buildDailyRouteConditions($datesInWeekArr, $params['RPTGCalendar'], $i_ptgPeriod);

					// Build final condition
					$userRouteCond = " AND (" . implode(" OR ", $buildDailyRouteCondData['sqlConditions']) . ")";
					
					$rpPeriodByDates = $buildDailyRouteCondData['rpPeriodByDates'];
					$diffRPPeriodDates = $buildDailyRouteCondData['diffRPPeriodDates'];

				}else{
					$userRouteCond = " AND ur.year = '$ptg_year' AND ur.month = '$ptg_month' AND ur.week = '$ptg_week'";
				}
			
				
				break;

				
			case 'monthly':
				$ptg_year 	= date('Y', strtotime($params['dateParams']['from']));
				$ptg_month 	= $params['dateParams']['month'];
				
				$monthlyRouteConditions = [];
				
				foreach ($params['RPTGCalendar']['calendar'][$ptg_month] as $i_ptg_weekNo => $datesInWeekArr) {

					// Week with >7 days — process each day
					if (count($datesInWeekArr) > 7) {
						$params['RPTGCalendar']['week'] = $i_ptg_weekNo;
						
						$i_ptgPeriod = ['year' => $ptg_year, 'month' => $ptg_month, 'week' => $i_ptg_weekNo];
						
						$buildDailyRouteCondData = buildDailyRouteConditions($datesInWeekArr,$params['RPTGCalendar'], $i_ptgPeriod ); 
						$monthlyRouteConditions = array_merge($monthlyRouteConditions, $buildDailyRouteCondData['sqlConditions']);
						
						$rpPeriodByDates   = array_merge($rpPeriodByDates, $buildDailyRouteCondData['rpPeriodByDates']);
						$diffRPPeriodDates = array_merge($diffRPPeriodDates, $buildDailyRouteCondData['diffRPPeriodDates']);

					} else {
						// Regular week — use simple condition
						$monthlyRouteConditions[] =
							"ur.year = '$ptg_year' AND ur.month = '$ptg_month' AND ur.week = '$i_ptg_weekNo'";
					}
				}

				// Final combined filter for the month
				$userRouteCond = " AND (" . implode(" OR ", $monthlyRouteConditions) . ")";

				break;
			
			case 'between':
				## NEED TO Work On this
				$userRouteCond = ""; //pr($userRouteCond);
			
                break;
            
        }
    
        $userDVC = $userRC = $userDC = $userId = "";
		$depot_ids = array();
        if (!empty($params['query']['dv'])){
            $userDVC = " AND u.division_id = ".$params['query']['dv'];
			
			$DivisionsRegion=  ClassRegistry::init('DivisionsRegion');
			$rIds = $DivisionsRegion->find('list', array('fields'=>array('region_id'),'conditions'=>array('division_id'=>$params['query']['dv'])));
			
			$Depot = ClassRegistry::init('Depot'); 
			$depot_ids = $Depot ->find('list', array('fields' => array('id'), 'conditions' => array('Depot.region_id' => $rIds )));  
		}
        if (!empty($params['query']['rg'])){
            $userRC = " AND u.region_id = ".$params['query']['rg'];
			
			$Depot = ClassRegistry::init('Depot'); 
			$depot_ids = $Depot ->find('list', array('fields' => array('id'), 'conditions' => array('Depot.region_id' => $params['query']['rg'])));
        }
        if (!empty($params['query']['dp'])){
            $userDC = " AND u.depot_id = ".$params['query']['dp'];
			
			$depot_ids = [$params['query']['dp']];
        }
		
		if (!empty($params['query']['us'])){
            $userId = " AND u.id = ".$params['query']['us'];
        }


        $result =  $customerActivity = array();
		
		//Get All users 
        $users = $user_ids = array();
		$usersData = $this->query("SELECT u.id, u.first_name, u.last_name, u.division_id, u.region_id, u.depot_id, u.role_id, u.status, r.name, d.title FROM users AS u INNER JOIN roles AS r ON u.role_id = r.id LEFT JOIN depots d ON d.id = u.depot_id LEFT JOIN regions rg ON rg.id = u.region_id WHERE  r.grade > 3 $userDVC $userDC $userRC $userId ORDER BY rg.title ASC, u.role_id ASC"); //pr($usersData );
		
		$DH_uids = $DH_depotwise = [];
        foreach($usersData as $user){
			
            $rid = ($user['u']['region_id'])?$user['u']['region_id']:0;
            $did = ($user['u']['depot_id'])?$user['u']['depot_id']:0;

            $uid = $user['u']['id'];
			
            $users[$rid][$did][$uid] = array('uid'=>$user['u']['id'], 'name'=> $user['u']['first_name'].' '.$user['u']['last_name'], 'rid'=>$user['u']['role_id'], 'role'=>$user['r']['name'], 'division_id'=>$user['u']['division_id'], 'region_id'=>$user['u']['region_id'], 'depot_id'=>$user['u']['depot_id'], 'depot'=>$user['d']['title'], 'status'=>$user['u']['status']);
			if (!in_array($uid, $user_ids)){
				array_push($user_ids, $uid);
			}
			
			if (!empty($params['query']['us'])){
				$depot_ids = array($did);
			}
			
			// ------------------------------
			// DH DEPOT-WISE GROUPING
			// ------------------------------
			if ($user['u']['role_id'] == DH) {

				## list DH
				// Add to standalone DH_uids list 
				$DH_uids[] = $uid;

				// Add inside DH_depotwise
				if (!isset($DH_depotwise[$did])) {
					$DH_depotwise[$did] = [];
				}

				// Store user id only
				$DH_depotwise[$did][] = $uid;
				
				if (!empty($params['query']['us'])){
					//Find other DH 
					$otherDH = $User->find('list', array('fields' => array('id'), 'conditions' => array('User.role_id' => DH, 'User.depot_id' => $did))); //pr($otherDH);
					
					if(!empty($otherDH)){
						foreach ($otherDH as $odid) {

							// Skip current user
							if ($odid == $uid) continue;

							// Add to master DH list
							if (!in_array($odid, $DH_uids)) {
								$DH_uids[] = $odid;
							}

							// Add to depotwise list
							if (!in_array($odid, $DH_depotwise[$did])) {
								$DH_depotwise[$did][] = $odid;
							}

							// Add to user_ids list
							if (!in_array($odid, $user_ids)) {
								$user_ids[] = $odid;
							}
						}
					}
				}
			}
        }
        $output['users'] = $users;
		
		$result['DH_depotwise'] = $DH_depotwise;
		
		//Expected Frequency
		$userRoutes = $this->query("SELECT ur.route_ids, ur.user_id, ur.year, ur.month, ur.week, ur.day FROM user_routes ur WHERE ur.user_id IN (".implode(', ', $user_ids).") ". $userRouteCond);
		//pr($userRoutes); die();
		
		$structuredUserRoutes = [];  // [uid][year][month][week][day] = structured array
		
		$result['userRouteNames'] = [];

		if(!empty($userRoutes)){
			$user_route_ids = $route_ids = array();

				foreach($userRoutes as $ur){
					$uid 	= !empty($ur['ur']['user_id']) ? $ur['ur']['user_id'] : 0 ;
					$urrids = !empty($ur['ur']['route_ids']) ? explode(',', $ur['ur']['route_ids']) : [];
					$uryr 	= !empty($ur['ur']['year']) ? $ur['ur']['year'] : 0 ;
					$urmn 	= !empty($ur['ur']['month']) ? $ur['ur']['month'] : 0 ;
					$urwk 	= !empty($ur['ur']['week']) ? $ur['ur']['week'] : 0 ;
					$urday  = !empty($ur['ur']['day']) ? $ur['ur']['day'] : "" ;
					
					// Collect all route IDs for later use
					$route_ids = array_unique(array_merge($route_ids, $urrids));
					$user_route_ids[$uid] = isset($user_route_ids[$uid]) ? array_unique(array_merge($user_route_ids[$uid], $urrids)) : $urrids;
					
					// ------------------------------------------------------------
					// Initialize structured routes entry
					// ------------------------------------------------------------
					if (!isset($structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday])) {
						$structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday] = [
							'route_ids'    => [],
							'us_custno'       => [], 'us_custno_total' => [],
							'rt_custno'       => [], 'rt_custno_total' => [],
						];
					}
					
					// ------------------------------------------------------------
					// Add the route IDs to route_ids only
					// ------------------------------------------------------------
					$structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday]['route_ids'] =
						array_unique(array_merge(
							$structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday]['route_ids'],
							$urrids
						));					
				}
				
			
		}  //pr($user_route_ids);
		//pr($structuredUserRoutes); die();
		
		
		$cnameC = " AND NOT (c.first_name IS NULL) AND NOT (c.last_name IS NULL)";
		if(!empty($route_ids)){
			
			// load route names
			$userRouteNames = [];
			
			$routeQuery = $this->query("SELECT id, title FROM routes WHERE id IN (" . implode(',', $route_ids) . ") ");
			
			if(!empty($routeQuery)){
				foreach ($routeQuery as $r) {
					$userRouteNames[$r['routes']['id']] = $r['routes']['title'];
				}
			}
			$result['userRouteNames'] = $userRouteNames;
		
		
		
		 // Prepare COUNT columns for each day in the period
			$custno_cases = [];

			// Loop through each day in the period and create a COUNT for each day			
			for ($dt = $d1; $dt <= $d2; $dt = date('Y-m-d', strtotime('+1 day', strtotime($dt)))) {
				$col = 'cust_' . str_replace('-', '_', $dt);
				$custno_cases[] = "COUNT(CASE WHEN c.created <= '$dt 23:59:59' THEN c.id END) AS $col";
			}
			$custnoCols = implode(', ', $custno_cases);
			
			//Fetch customer counts per route and user
			//$userRouteCustomers = $this->query("SELECT $custnoCols, c.route_id, c.user_id FROM customers c WHERE $ccC $cnameC AND c.status = 1 AND c.route_id IN (" . implode(', ', $route_ids) . ") GROUP BY c.route_id, c.user_id");
			
			//Fetch customer counts per route
			$routeCustomers = $this->query("SELECT $custnoCols, c.route_id, c.user_id FROM customers c WHERE $ccC $cnameC AND c.status = 1 AND c.route_id IN (" . implode(', ', $route_ids) . ") GROUP BY c.route_id");
			
			//Preprocess $userRouteCustomers into a lookup map for route counts
			
			$routeCustCounts = []; // [user][route][date] = count
			if (!empty($routeCustomers)) {
				foreach ($routeCustomers as $row) {
					$rid = $row['c']['route_id'];
					foreach ($row[0] as $col => $val) {
						if (strpos($col, 'cust_') !== 0) continue;
						$dt = str_replace(['cust_', '_'], ['', '-'], $col);
						$routeCustCounts[$rid][$dt] = intval($val);
					}
				}
			}

		}
		

		// Loop through full period and populate structuredUserRoutes
		for ($dt = $d1; $dt <= $d2; $dt = date('Y-m-d', strtotime('+1 day', strtotime($dt)))) {
			$yr_key = date('Y', strtotime($dt));
			$dy_key = date('l', strtotime($dt));
			$mn_key = $dateParams['month'];

			if (in_array($params['type'], ['daily', 'weekly'])) {
				$wk_key = $dateParams['week'];
			} elseif($params['type'] == 'monthly') { // monthly 
				$wk_key = getWeekNo($params['RPTGCalendar']['calendar'][$dateParams['month']], $dt); 
			}else{
				// between 
				### NEED TO WORK
			}
			
			// Override with route plan period if date is in diffRPPeriodDates
			if (in_array($dt, $diffRPPeriodDates) && isset($rpPeriodByDates[$dt])) {
				$yr_key = $rpPeriodByDates[$dt]['year'];
				$mn_key = $rpPeriodByDates[$dt]['month'];
				$wk_key = $rpPeriodByDates[$dt]['week'];
			}
			
			if(!empty($structuredUserRoutes)){
				foreach ($structuredUserRoutes as $uid => &$yearsArr) {

					if (!isset($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key])) {
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key] = [
							'route_ids' => [],
							'us_custno' => [], 'us_custno_total' => [],
							'rt_custno' => [], 'rt_custno_total' => []
						];
					}

					// If routes exist, assign counts
					foreach ($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['route_ids'] as $rid) {
						$count = isset($routeCustCounts[$rid][$dt]) ? $routeCustCounts[$rid][$dt] : 0;
						$us_count = $count;
						if (in_array($uid, $DH_uids)) {
							$us_count = ceil($count / 2);
							$us_count = ($count / 2);
						}
						
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['us_custno'][$dt][$rid] = $us_count;
											
						if (!isset($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['us_custno_total'][$dt])) {
							$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['us_custno_total'][$dt] = 0;
						}
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['us_custno_total'][$dt] += $us_count;
						
						// For Route custno
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['rt_custno'][$dt][$rid] = $count;
						if (!isset($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['rt_custno_total'][$dt])) {
							$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['rt_custno_total'][$dt] = 0;
						}
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['rt_custno_total'][$dt] += $count;
						
					}

					// If no route_ids, still assign zero for us_custno_total , rt_custno_total
					if (empty($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['route_ids'])) {
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['us_custno_total'][$dt] = 0;
						
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['rt_custno_total'][$dt] = 0;
					}
				}
			}else{
				$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key] = [
					'route_ids' => [],
					'us_custno' => [], 'us_custno_total' => [],
					'rt_custno' => [], 'rt_custno_total' => []
				];
			}
			
			//pr($structuredUserRoutes );
			
		}

		// Build daily & weekly expected frequency for **all dates**, even with no routes
		foreach ($structuredUserRoutes as $uid => $yearsArr) {
			$result[$uid]['expected_freq'] = $result[$uid]['route_expected_freq'] = 0;

			for ($dt = $d1; $dt <= $d2; $dt = date('Y-m-d', strtotime('+1 day', strtotime($dt)))) {
				$yr_key = date('Y', strtotime($dt));
				$dy_key = date('l', strtotime($dt));
				$mn_key = $dateParams['month'];

				if (in_array($params['type'], ['daily', 'weekly'])) {
					$wk_key = $dateParams['week'];
				} else {
					$wk_key = getWeekNo($params['RPTGCalendar']['calendar'][$dateParams['month']], $dt); 
					//$wk_key = getWeekNo($params['RPTGCalendar']['calendar'][$dateParams['month']], $dt); 
				}
				
				$rp_yr_key = $yr_key; $rp_mn_key = $mn_key; $rp_wk_key = $wk_key;
				// Override with route plan period if date is in diffRPPeriodDates
				if (in_array($dt, $diffRPPeriodDates) && isset($rpPeriodByDates[$dt])) {
					$rp_yr_key = $rpPeriodByDates[$dt]['year'];
					$rp_mn_key = $rpPeriodByDates[$dt]['month'];
					$rp_wk_key = $rpPeriodByDates[$dt]['week'];
				}

				$dayInfo = isset($structuredUserRoutes[$uid][$rp_yr_key][$rp_mn_key][$rp_wk_key][$dy_key]) 
						   ? $structuredUserRoutes[$uid][$rp_yr_key][$rp_mn_key][$rp_wk_key][$dy_key] 
						   : ['us_custno' => [], 'us_custno_total' => [ $dt => 0 ]];

				$us_routes = isset($dayInfo['us_custno'][$dt]) ? $dayInfo['us_custno'][$dt] : [];
				
				$rt_routes = isset($dayInfo['rt_custno'][$dt]) ? $dayInfo['rt_custno'][$dt] : [];
				
				$dateObj = DateTime::createFromFormat('!m', $mn_key);
				$ptgMonthName = $dateObj->format('M');
				$ptgCalPeriod = $ptgMonthName . " " . $yr_key  . ", Week " . $wk_key;

				// Route Plan Period (inline)
				$dateObj = DateTime::createFromFormat('!m', $rp_mn_key);
				$rpMonthName = $dateObj->format('M');
				$routePlanPeriod = "$rpMonthName $rp_yr_key, Week $rp_wk_key";

				if (in_array($params['type'], ['daily', 'weekly'])) {
					$result[$uid]['userDailyExpFreq'][$dt] = [
						'ptgCalPeriod' => $ptgCalPeriod,
						'routePlanPeriod' => $routePlanPeriod,
						'day' => $dy_key,
						'us_routes' => $us_routes,
						'rt_routes' => $rt_routes,
					];
				} else {
					if (!isset($result[$uid]['userWklyExpFreq'][$mn_key][$wk_key])) {
						$result[$uid]['userWklyExpFreq'][$mn_key][$wk_key] = [
							'us_expectedFreq' 	=> 0, 'rt_expectedFreq' 	=> 0,
							'ptgWeekRange' 		=> ['from' => $dt, 'to' => $dt],
							'RPPeriodRange' 	=> [['year'  => $rp_yr_key, 'month' => $rp_mn_key, 'week'  => $rp_wk_key, 'from'  => $dt, 'to'    => $dt]]];
					} else {
						$weekData = &$result[$uid]['userWklyExpFreq'][$mn_key][$wk_key]; //pr($weekData); die();
						
						// Update PTG week range
						if (strtotime($dt) < strtotime($weekData['ptgWeekRange']['from'])) $weekData['ptgWeekRange']['from'] = $dt;
						if (strtotime($dt) > strtotime($weekData['ptgWeekRange']['to'])) $weekData['ptgWeekRange']['to'] = $dt;
						
						// Merge or add route plan period ranges
						$lastIndex = count($weekData['RPPeriodRange']) - 1;
						$lastRange = &$weekData['RPPeriodRange'][$lastIndex];
						$expectedNextDate = date('Y-m-d', strtotime($lastRange['to'] . ' +1 day'));

						if ($lastRange['year'] == $rp_yr_key && $lastRange['month'] == $rp_mn_key && $lastRange['week'] == $rp_wk_key && $expectedNextDate == $dt) {
							$lastRange['to'] = $dt; // extend range
						} else {
							$weekData['RPPeriodRange'][] = ['year'  => $rp_yr_key, 'month' => $rp_mn_key, 'week' => $rp_wk_key, 'from' => $dt, 'to' => $dt ];
						}
					}
					
					$result[$uid]['userWklyExpFreq'][$mn_key][$wk_key]['us_expectedFreq'] += array_sum($us_routes);
					
					$result[$uid]['userWklyExpFreq'][$mn_key][$wk_key]['rt_expectedFreq'] += array_sum($rt_routes);
				}

				$result[$uid]['expected_freq'] += array_sum($us_routes);
				
				$result[$uid]['route_expected_freq'] += array_sum($rt_routes);
			}
		}

		


		
		//pr($depot_ids); die();
		
		$odpC = $fidpC = $rddpC = $indpC = $cvdpC = "";
		// Only build conditions if depot_ids is not empty and not just [0]
		if (!empty($depot_ids) && !(count($depot_ids) === 1 && $depot_ids[0] == 0)) {
			$odpC = " AND sl.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$fidpC = " AND fi.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$rddpC = " AND rsi.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$indpC = " AND inc.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$cvdpC = " AND cv.depot_id IN (" . implode(', ', $depot_ids) . ")";
		}
		
		$orderEntry = $this->query("SELECT SUM(sl.cal_qty) AS totQty, COUNT(DISTINCT CONCAT(sl.customer_id, '-', sl.sale_date)) AS oentry, sl.user_id, sl.depot_id, sl.sale_date, sl.customer_id, sl.via_app, MIN(sl.created) AS first_entry_time FROM sales sl WHERE $oC $odpC GROUP BY sl.user_id, sl.sale_date, sl.customer_id, sl.via_app");
		//pr($orderEntry); die();

		$freeItemEntry = $this->query("SELECT SUM(fi.cal_qty) AS totQtyFi, fi.user_id, fi.depot_id, fi.sale_date, fi.customer_id, fi.via_app FROM free_items fi WHERE $fiC $fidpC GROUP BY fi.user_id, fi.sale_date, fi.customer_id, fi.via_app"); //pr($freeItemEntry); //die();

        
		$rSaleEntry = $this->query("SELECT SUM(rsi.cal_qty) AS totQty, COUNT(DISTINCT CONCAT(rsi.customer_id, '-', rsi.sale_date)) AS rsentry, rsi.user_id, rsi.depot_id, rsi.sale_date, rsi.customer_id, rsi.via_app, MIN(rsi.created) AS first_entry_time FROM redistributor_saleitems rsi WHERE $rdC $rddpC GROUP BY rsi.user_id, rsi.sale_date, rsi.customer_id, rsi.via_app"); //pr($rSaleEntry); 
		
		$incentiveEntry = $this->query("SELECT SUM(inc.cal_qty) AS totQty, COUNT(DISTINCT CONCAT(inc.customer_id, '-', inc.incentive_date)) AS incentry, inc.user_id, inc.depot_id, inc.incentive_date, inc.customer_id, inc.via_app, MIN(inc.created) AS first_entry_time FROM incentives inc INNER JOIN customers as c on inc.customer_id = c.id WHERE $inC $indpC GROUP BY inc.user_id, inc.incentive_date, inc.customer_id, inc.via_app"); //pr($incentiveEntry); 
	
        if(!empty($params['cvisityear_tables'])) {
            foreach ($params['cvisityear_tables'] as $year => $cv_tableName) {
				$visitEntries[$year] = $this->query("SELECT COUNT(DISTINCT CONCAT(cv.customer_id, '-', date(cv.visiting_date))) AS ventry, cv.user_id, cv.depot_id, date(cv.visiting_date) as vdate, cv.customer_id, cv.via_app, MIN(cv.created) AS first_entry_time FROM $cv_tableName cv WHERE $cvC $cvdpC GROUP BY cv.user_id, date(cv.visiting_date), cv.customer_id, cv.via_app");
            }
        }
        //pr($visitEntries);  die();

		//Count customers created
        //$customerEntry = $this->query("SELECT count(c.id) as cCreated, c.user_id FROM customers c WHERE c.status = ".ACTIVE." AND c.user_id IN (".implode(', ', $user_ids).") GROUP BY c.user_id");
		
		$customerEntry = $this->query("SELECT c.id, c.user_id, c.verified_latitude, c.verified_longitude, c.verified_by, c.verified_date FROM customers c WHERE $ccC $cnameC AND c.status = ".ACTIVE." AND c.user_id IN (".implode(', ', $user_ids).")"); 

        //$vc = 0;
        if (!empty($customerEntry)){
            foreach ($customerEntry as $c){
				$uid = !empty($c['c']['user_id']) ? $c['c']['user_id'] : 0 ;
				
				$result[$uid]['customers'][] = $c['c']['id'];
				
				/*if(!empty($c['c']['verified_latitude']) && !empty($c['c']['verified_longitude']) && !empty($c['c']['verified_by']) && !empty($c['c']['verified_date'])){
					$result[$uid]['verified_customers'][] = $c['c']['id'];
				}*/
                //$result[$uid]['totalCustomer'] = $c['0']['cCreated'];
            }
        }
        
        $verifiedCustomerEntry = $this->query("SELECT c.id, c.user_id, c.verified_latitude, c.verified_longitude, c.verified_by, c.verified_date FROM customers c WHERE $vcC $cnameC AND c.status = ".ACTIVE." AND c.user_id IN (".implode(', ', $user_ids).")"); 
        
        if (!empty($verifiedCustomerEntry)){
            foreach ($verifiedCustomerEntry as $c){
				$uid = !empty($c['c']['user_id']) ? $c['c']['user_id'] : 0 ;
				
				if(!empty($c['c']['verified_latitude']) && !empty($c['c']['verified_longitude']) && !empty($c['c']['verified_by']) && !empty($c['c']['verified_date'])){
					$result[$uid]['verified_customers'][] = $c['c']['id'];
					
					//++$vc;
				}
                //$result[$uid]['totalCustomer'] = $c['0']['cCreated'];
            }
        }
        //pr('Verified Customers '.$vc);
		
		$firstCallPerCustomer = [];
  
		//pr($result);
		//pr($orderEntry);
		if (!empty($orderEntry)){
            foreach ($orderEntry as $oe){
                $uid = !empty($oe['sl']['user_id']) ? $oe['sl']['user_id'] : 0 ;
				$cid = !empty($oe['sl']['customer_id']) ? $oe['sl']['customer_id'] : 0 ; 
                $did = !empty($oe['sl']['depot_id']) ? $oe['sl']['depot_id'] : 0;
                $sale_date = date(DATE_FORMAT_SORT, strtotime($oe['sl']['sale_date']));
				$created_time = $oe['0']['first_entry_time'];
				
				if(!empty($oe['sl']['via_app'])){
					if(empty($result[$uid]['call']['saleEntry'])){
						$result[$uid]['call']['saleEntry'] = $oe['0']['oentry'];
					}else{
						$result[$uid]['call']['saleEntry'] += $oe['0']['oentry'];
					}
					
					if(empty($result[$uid]['call']['customerCalls'][$cid]['saleEntry'])){
						$result[$uid]['call']['customerCalls'][$cid]['saleEntry'] = $oe['0']['oentry'];
					}else{
						$result[$uid]['call']['customerCalls'][$cid]['saleEntry'] += $oe['0']['oentry'];
					}
					if(empty($result[$uid]['call']['customersVisited'][$cid])){
						$result[$uid]['call']['customersVisited'][$cid] = array($sale_date);
					}else{
						/* if(!in_array($sale_date, $result[$uid]['call']['customersVisited'][$cid])){
							$result[$uid]['call']['customersVisited'][$cid] = array($sale_date);
						}else{
							array_push($result[$uid]['call']['customersVisited'][$cid], $sale_date);
						} */
						if(!in_array($sale_date, $result[$uid]['call']['customersVisited'][$cid])){ 
							array_push($result[$uid]['call']['customersVisited'][$cid], $sale_date);
						}
					}
					//customer activity 
					$activityCall = ['type' => 'saleEntry', 'saleEntry' => $oe['0']['oentry'], 'saleVol' => $oe['0']['totQty']];
					if (!isset($customerActivity[$cid]['calls'][$sale_date][$uid])) {
						$customerActivity[$cid]['calls'][$sale_date][$uid] = [$activityCall];
					} else {
						$customerActivity[$cid]['calls'][$sale_date][$uid][] = $activityCall;
					}
					
					// --- Track first call per customer/day ---
					if (!isset($firstCallPerCustomer[$cid][$sale_date]) || 
						$created_time < $firstCallPerCustomer[$cid][$sale_date]['time']) {
						$firstCallPerCustomer[$cid][$sale_date] = [
							'time' => $created_time,
							'user_id' => $uid,
							'type' => 'Sale'
						];
					}
					
					
				}				
				
				if(empty($result[$uid]['call']['saleVol'])){
					$result[$uid]['call']['saleVol'] = $oe['0']['totQty'];
				}else{
					$result[$uid]['call']['saleVol'] += $oe['0']['totQty'];
				}
								
				if(empty($result[$uid]['call']['customerCalls'][$cid]['saleVol'])){
					$result[$uid]['call']['customerCalls'][$cid]['saleVol'] = $oe['0']['totQty'];
				}else{
					$result[$uid]['call']['customerCalls'][$cid]['saleVol'] += $oe['0']['totQty'];
				}

            }
        }
        
        
        if (!empty($freeItemEntry)){
            foreach ($freeItemEntry as $fe){
                $uid = !empty($fe['fi']['user_id']) ? $fe['fi']['user_id'] : 0 ;
				$cid = !empty($fe['fi']['customer_id']) ? $fe['fi']['customer_id'] : 0 ;
                $did = !empty($fe['fi']['depot_id']) ? $fe['fi']['depot_id'] : 0;
                $sale_date = date(DATE_FORMAT_SORT, strtotime($fe['fi']['sale_date']));

				
				if(empty($result[$uid]['call']['saleFiVol'])){
					$result[$uid]['call']['saleFiVol'] = $fe['0']['totQtyFi'];
				}else{
					$result[$uid]['call']['saleFiVol'] += $fe['0']['totQtyFi'];
				}
								
				if(empty($result[$uid]['call']['customerCalls'][$cid]['saleFiVol'])){
					$result[$uid]['call']['customerCalls'][$cid]['saleFiVol'] = $fe['0']['totQtyFi'];
				}else{
					$result[$uid]['call']['customerCalls'][$cid]['saleFiVol'] += $fe['0']['totQtyFi'];
				}
				
				//customer activity 
				$activityCall = ['type' => 'saleFi', 'saleFiVol' => $fe['0']['totQtyFi']];
				if (!isset($customerActivity[$cid]['calls'][$sale_date][$uid])) {
					$customerActivity[$cid]['calls'][$sale_date][$uid] = [$activityCall];
				} else {
					$customerActivity[$cid]['calls'][$sale_date][$uid][] = $activityCall;
				}

            }
        }
	
		if (!empty($rSaleEntry)){
            foreach ($rSaleEntry as $rse){
                $uid = !empty($rse['rsi']['user_id']) ? $rse['rsi']['user_id'] : 0 ;
				$cid = !empty($rse['rsi']['customer_id']) ? $rse['rsi']['customer_id'] : 0 ;
                $did = !empty($rse['rsi']['depot_id']) ? $rse['rsi']['depot_id'] : 0;
				$sale_date = date(DATE_FORMAT_SORT, strtotime($rse['rsi']['sale_date']));
				$created_time = $rse['0']['first_entry_time'];
                
				if(!empty($rse['rsi']['via_app'])){
					if(empty($result[$uid]['call']['rsSaleEntry'])){
						$result[$uid]['call']['rsSaleEntry'] = $rse['0']['rsentry'];
					}else{
						$result[$uid]['call']['rsSaleEntry'] += $rse['0']['rsentry'];
					}
					if(empty($result[$uid]['call']['customerCalls'][$cid]['rsSaleEntry'])){
						$result[$uid]['call']['customerCalls'][$cid]['rsSaleEntry'] = $rse['0']['rsentry'];
					}else{
						$result[$uid]['call']['customerCalls'][$cid]['rsSaleEntry'] += $rse['0']['rsentry'];
					}
					if(empty($result[$uid]['call']['customersVisited'][$cid])){
						$result[$uid]['call']['customersVisited'][$cid] = array($sale_date);
					}else{
						if(!in_array($sale_date, $result[$uid]['call']['customersVisited'][$cid])){ 
							array_push($result[$uid]['call']['customersVisited'][$cid], $sale_date);
						}
					}
					
					//customer activity 
					$activityCall = ['type' => 'rsSaleEntry', 'rsSaleEntry' => $rse['0']['rsentry'], 'rsSaleVol' => $rse['0']['totQty']];
					if (!isset($customerActivity[$cid]['calls'][$sale_date][$uid])) {
						$customerActivity[$cid]['calls'][$sale_date][$uid] = [$activityCall];
					} else {
						$customerActivity[$cid]['calls'][$sale_date][$uid][] = $activityCall;
					}
					
					// --- Track first call per customer/day ---
					if (!isset($firstCallPerCustomer[$cid][$sale_date]) || 
						$created_time < $firstCallPerCustomer[$cid][$sale_date]['time']) {
						$firstCallPerCustomer[$cid][$sale_date] = [
							'time' => $created_time,
							'user_id' => $uid,
							'type' => 'RSale'
						];
					}
				}
				
				if(empty($result[$uid]['call']['rsSaleVol'])){
					$result[$uid]['call']['rsSaleVol'] = $rse['0']['totQty'];
				}else{
					$result[$uid]['call']['rsSaleVol'] += $rse['0']['totQty'];
				}
							
				if(empty($result[$uid]['call']['customerCalls'][$cid]['rsSaleVol'])){
					$result[$uid]['call']['customerCalls'][$cid]['rsSaleVol'] = $rse['0']['totQty'];
				}else{
					$result[$uid]['call']['customerCalls'][$cid]['rsSaleVol'] += $rse['0']['totQty'];
				}
            }
        }
		
		if (!empty($incentiveEntry)){
            foreach ($incentiveEntry as $ine){
                $uid = !empty($ine['inc']['user_id']) ? $ine['inc']['user_id'] : 0 ;
				$cid = !empty($ine['inc']['customer_id']) ? $ine['inc']['customer_id'] : 0 ; 
                $did = !empty($ine['inc']['depot_id']) ? $ine['inc']['depot_id'] : 0;
				$incentive_date = date(DATE_FORMAT_SORT, strtotime($ine['inc']['incentive_date']));
				$created_time = $ine['0']['first_entry_time'];
               	
				if(!empty($ine['inc']['via_app'])){
					if(empty($result[$uid]['call']['incentiveEntry'])){
						$result[$uid]['call']['incentiveEntry'] = $ine['0']['incentry'];
					}else{
						 $result[$uid]['call']['incentiveEntry'] += $ine['0']['incentry'];
					}					
					if(empty($result[$uid]['call']['customerCalls'][$cid]['incentiveEntry'])){
						$result[$uid]['call']['customerCalls'][$cid]['incentiveEntry'] = $ine['0']['incentry'];
					}else{
						$result[$uid]['call']['customerCalls'][$cid]['incentiveEntry'] += $ine['0']['incentry'];
					}
					if(empty($result[$uid]['call']['customersVisited'][$cid])){
						$result[$uid]['call']['customersVisited'][$cid] = array($incentive_date);
					}else{
						if(!in_array($incentive_date, $result[$uid]['call']['customersVisited'][$cid])){
							array_push($result[$uid]['call']['customersVisited'][$cid], $incentive_date);
						}
					}
										
					//customer activity 					
					$activityCall = ['type' => 'incentiveEntry', 'incentiveEntry' => $ine['0']['incentry'], 'incentiveVol' => $ine['0']['totQty']];
					if (!isset($customerActivity[$cid]['calls'][$incentive_date][$uid])) {
						$customerActivity[$cid]['calls'][$incentive_date][$uid] = [$activityCall];
					} else {
						$customerActivity[$cid]['calls'][$incentive_date][$uid][] = $activityCall;
					}
					
					// --- Track first call per customer/day ---
					if (!isset($firstCallPerCustomer[$cid][$incentive_date]) || 
						$created_time < $firstCallPerCustomer[$cid][$incentive_date]['time']) {
						$firstCallPerCustomer[$cid][$incentive_date] = [
							'time' => $created_time,
							'user_id' => $uid,
							'type' => 'Incentive'
						];
					}
				}
				
				if(empty($result[$uid]['call']['incentiveVol'])){
					$result[$uid]['call']['incentiveVol'] = $ine['0']['totQty'];
				}else{
					$result[$uid]['call']['incentiveVol'] += $ine['0']['totQty'];
				}			
				
				if(empty($result[$uid]['call']['customerCalls'][$cid]['incentiveVol'])){
					$result[$uid]['call']['customerCalls'][$cid]['incentiveVol'] = $ine['0']['totQty'];
				}else{
					$result[$uid]['call']['customerCalls'][$cid]['incentiveVol'] += $ine['0']['totQty'];
				}

            }
        }

		if (!empty($visitEntries)) { //pr($visitEntries);
            foreach ($visitEntries as $year => $visitFrequency) {
                foreach ($visitFrequency as $cve){
                    $uid = !empty($cve['cv']['user_id']) ? $cve['cv']['user_id'] : 0 ;
					$cid = !empty($cve['cv']['customer_id']) ? $cve['cv']['customer_id'] : 0 ;
                    $did = !empty($cve['cv']['depot_id'])?$cve['cv']['depot_id']:0;
					$vdate = date(DATE_FORMAT_SORT, strtotime( $cve[0]['vdate']));
					$created_time = $cve['0']['first_entry_time'];
					
					if(!empty($cve['cv']['via_app'])){
						if(empty($result[$uid]['call']['ventry'])){
							 $result[$uid]['call']['ventry'] = $cve['0']['ventry'];
						}else{
							$result[$uid]['call']['ventry'] += $cve['0']['ventry'];
						}
						
						if(empty($result[$uid]['call']['customerCalls'][$cid]['ventry'])){
							$result[$uid]['call']['customerCalls'][$cid]['ventry'] = $cve['0']['ventry'];
						}else{
							$result[$uid]['call']['customerCalls'][$cid]['ventry'] += $cve['0']['ventry'];
						}
						if(empty($result[$uid]['call']['customersVisited'][$cid])){
							$result[$uid]['call']['customersVisited'][$cid] = array($vdate);
						}else{
							if(!in_array($vdate, $result[$uid]['call']['customersVisited'][$cid])){
								array_push($result[$uid]['call']['customersVisited'][$cid], $vdate);
							}
						}

						//customer activity 
						$activityCall = ['type' => 'visitEntry', 'ventry' => $cve['0']['ventry']];
						if (!isset($customerActivity[$cid]['calls'][$vdate][$uid])) {
							$customerActivity[$cid]['calls'][$vdate][$uid] = [$activityCall];
						} else {
							$customerActivity[$cid]['calls'][$vdate][$uid][] = $activityCall;
						}
						
						// --- Track first call per customer/day ---
						if (!isset($firstCallPerCustomer[$cid][$vdate]) || 
							$created_time < $firstCallPerCustomer[$cid][$vdate]['time']) {
							$firstCallPerCustomer[$cid][$vdate] = [
								'time' => $created_time,
								'user_id' => $uid,
								'type' => 'CustomerVisit'
							];
						}
					}

                }

            }
        }
		
		//$customerAddedBy = array(); //cid=>uid	
		
		if(!empty($params['user_id']) && !empty($result[$params['user_id']]['call']['customersVisited'])){
			$uid = $params['user_id']; 
			//$cidArr = array_keys($result[$uid]['call']['customersVisited']); 
			$cidArr = array_keys($customerActivity); 
			//pr(implode(', ', $cidArr));
			
			$customersData = $this->query("SELECT c.id, c.first_name, c.last_name, c.user_id, r.title FROM customers c LEFT JOIN routes r ON c.route_id = r.id WHERE c.id IN (".implode(', ', $cidArr).")");
			$customers = array();
			foreach ($customersData as $c){
				$customers[$c['c']['id']]['name'] = $c['c']['first_name'].' '.$c['c']['last_name'];
				$customers[$c['c']['id']]['route'] = $c['r']['title'];
				$customers[$c['c']['id']]['user_id'] = $c['c']['user_id'];
				
				//$customerAddedBy[$c['c']['id']] = $c['c']['user_id'];
				
			} 
			$result[$uid]['customers_visited'] = $customers; 

		}/* else{
			$Customer = ClassRegistry::init('Customer'); 
			$customerAddedBy = $Customer ->find('list', array('fields' => array('id','user_id'), 'conditions' => array('Customer.id' => array_keys($customerActivity))));
		} */
		
		
		$userNames = $User ->find('list', array('fields' => array('id','name')));
		
		//pr($customerActivity); 
		
		//pr($result[$uid]['call']['customersVisited']);
		//pr($result[368]['call']['customersVisited']);
		//pr(count($result[81]['call']['customersVisited'])); 
		
		//pr($result[81]['call']); 
		
		//“If two different users make entry on one customer in a day, the entry should be counted as one entry and the entry should be credited to the user who created the customer”
		
		//Know User IDs of Role RM and Above (Supervision Roles) : Currently, the report is generated only for DMs and roles below. Therefore, we do not need to perform debit-credit operations if the customer is visited by users with the role of RM or above.
		
//pr($firstCallPerCustomer[424655]);
		
		$supervisionRoleUserIds = $User->find('list', array('fields' => array('User.id'), 'joins' => array(array('table' => 'roles', 'alias' => 'Role', 'type' => 'INNER', 'conditions' => array('User.role_id = Role.id', 'Role.grade <=' => RM)))));  //pr(count($supervisionRoleUserIds));
		
		
		//pr($firstCallPerCustomer);
		//pr($customerActivity);
		foreach($customerActivity as $cid => $calls){
			foreach($calls['calls'] as $date => $userEntries){
				
				$userIds = array_keys($userEntries); // get all user IDs who made entries on this customer on this date
				
				// Exclude supervision role users
				$userIds = array_diff($userIds, $supervisionRoleUserIds);
				
				// ❗Skip processing if only one or zero non-supervisory users are left
				if (count($userIds) <= 1) {
					continue;
				}
				//pr($date); pr($cid);
				//pr($userIds);
				
				
				
				//if(count($userIds) > 1){
					//if(!empty($customerAddedBy[$cid])){
					if(!empty($firstCallPerCustomer[$cid][$date])){
						//$ownerId = $customerAddedBy[$cid];
						$ownerId = 	$firstCallPerCustomer[$cid][$date]['user_id'];
						$ownerName = !empty($userNames[$ownerId]) ? $userNames[$ownerId] : "";
						
						// Get users who are NOT the creator of this customer
						$dupUsers = array_diff($userIds, [$ownerId]);
						
						// Create debitCalls / creditCalls
						foreach ($dupUsers as $uid) {  //pr($customerActivity[$cid]['calls'][$date][$uid]);
							if(!empty($customerActivity[$cid]['calls'][$date][$uid])){
								$userName = !empty($userNames[$uid]) ? $userNames[$uid] : "";	

								if(isset($result[$ownerId]['customers_visited'][$cid])){ //pr($uid);
									$result[$ownerId]['customers_visited'][$cid]['ownerId'] = $uid;
								}

								$result['debitCalls'][$uid][] = ['date' => $date, 'creditedTo' => ['id' => $ownerId, 'name' => $ownerName], 'callDetails' => $customerActivity[$cid]['calls'][$date][$uid]];
								$result['creditCalls'][$ownerId][] = ['date' => $date, 'debitedFrom' => ['id' => $uid, 'name' => $userName], 'callDetails' => $customerActivity[$cid]['calls'][$date][$uid]];
								
								foreach($customerActivity[$cid]['calls'][$date][$uid] as $activity){ //pr($activity);
									switch($activity['type']){
										case 'saleEntry':
											// remove from users
												$result[$uid]['call']['saleEntry'] -= $activity['saleEntry'];
												//$result[$uid]['call']['saleVol'] -= $activity['saleVol'];
												
												// Add to owner
												$result[$ownerId]['call']['saleEntry'] = isset($result[$ownerId]['call']['saleEntry']) 
													? $result[$ownerId]['call']['saleEntry'] + $activity['saleEntry']
													: $activity['saleEntry'];

												/* $result[$ownerId]['call']['saleVol'] = isset($result[$ownerId]['call']['saleVol']) 
													? $result[$ownerId]['call']['saleVol'] + $activity['saleVol']
													: $activity['saleVol']; */
											break;
											
										/* case 'saleFi':
											// remove from users
												$result[$uid]['call']['saleFiVol'] -= $activity['saleFiVol'];
												
												// Add to owner
												$result[$ownerId]['call']['saleFiVol'] = isset($result[$ownerId]['call']['saleFiVol']) 
													? $result[$ownerId]['call']['saleFiVol'] + $activity['saleFiVol']
													: $activity['saleFiVol'];
											break; */
											
										case 'rsSaleEntry':
											// remove from users
												$result[$uid]['call']['rsSaleEntry'] -= $activity['rsSaleEntry'];
												//$result[$uid]['call']['rsSaleVol'] -= $activity['rsSaleVol'];
												
												// Add to owner
												$result[$ownerId]['call']['rsSaleEntry'] = isset($result[$ownerId]['call']['rsSaleEntry']) 
													? $result[$ownerId]['call']['rsSaleEntry'] + $activity['rsSaleEntry']
													: $activity['rsSaleEntry'];

												/* $result[$ownerId]['call']['rsSaleVol'] = isset($result[$ownerId]['call']['rsSaleVol']) 
													? $result[$ownerId]['call']['rsSaleVol'] + $activity['rsSaleVol']
													: $activity['rsSaleVol']; */
											break;												
											
										case 'incentiveEntry':
												// remove from users
												$result[$uid]['call']['incentiveEntry'] -= $activity['incentiveEntry'];
												//$result[$uid]['call']['incentiveVol'] -= $activity['incentiveVol'];
												
												// Add to owner
												$result[$ownerId]['call']['incentiveEntry'] = isset($result[$ownerId]['call']['incentiveEntry']) 
													? $result[$ownerId]['call']['incentiveEntry'] + $activity['incentiveEntry']
													: $activity['incentiveEntry'];

												/* $result[$ownerId]['call']['incentiveVol'] = isset($result[$ownerId]['call']['incentiveVol']) 
													? $result[$ownerId]['call']['incentiveVol'] + $activity['incentiveVol']
													: $activity['incentiveVol']; */
											break;
											
										case 'ventry':
											// remove from users
												$result[$uid]['call']['ventry'] -= $activity['ventry'];
												
												// Add to owner
												$result[$ownerId]['call']['ventry'] = isset($result[$ownerId]['call']['ventry']) 
													? $result[$ownerId]['call']['ventry'] + $activity['ventry']
													: $activity['ventry'];
											break;
											
										default:
											break;
									}
								}
							}
						}
						
						// remove customersVisited from other user
						if (!empty($result[$uid]['call']['customersVisited'][$cid])) {
							$dateIndex = array_search($date, $result[$uid]['call']['customersVisited'][$cid]);
							if ($dateIndex !== false) {
								unset($result[$uid]['call']['customersVisited'][$cid][$dateIndex]);
								$result[$uid]['call']['customersVisited'][$cid] = array_values($result[$uid]['call']['customersVisited'][$cid]);
								if (empty($result[$uid]['call']['customersVisited'][$cid])) {
									unset($result[$uid]['call']['customersVisited'][$cid]);
								}
							}
						}

						// Add customersVisited to owner
						if (!isset($result[$ownerId]['call']['customersVisited'][$cid])) {
							$result[$ownerId]['call']['customersVisited'][$cid] = [$date];
						} else {
							if (!in_array($date, $result[$ownerId]['call']['customersVisited'][$cid])) {
								$result[$ownerId]['call']['customersVisited'][$cid][] = $date;
							}
						}
					}
				//}
			}
		}

		//pr($result[$uid]['call']['customersVisited']);
		//pr($result[16]['call']['customersVisited']);
		//pr($result['debitCalls']);
		//pr($result['creditCalls']);
		//pr($result[16]['call']['customersVisited']); pr("----------------------------------------------------------------------------------------------------------");
		//pr($result[248]['call']['customersVisited']);
		
//pr($result);
        $output['result'] = $result;

        return $output;
    }
	
	
	function usersCallsFrequencySummary_V5($params){
		

		// ================================
		// 1. DATE CONDITIONS
		// ================================
		extract($this->_buildDateConditions($params));
		
		$dateParams = $params['dateParams']; 

		// ================================
		// 2. ROUTE PLAN CONDITIONS
		// ================================
		$routePlan  = $this->_buildRoutePlanConditions($params);
		$userRouteCond      = $routePlan['userRouteCond'];
		$rpPeriodByDates    = $routePlan['rpPeriodByDates'];
		$diffRPPeriodDates  = $routePlan['diffRPPeriodDates'];

		// ================================
		// 3. USER FILTERS
		// ================================
		$filters = $this->_buildUserFilters(isset($params['query']) ? $params['query'] : []);
		extract($filters);

		// ================================
		// 4. FETCH USERS
		// ================================
		$usersData  = $this->_fetchFreqReportUsers($filters, $params);

		$users     = $usersData['users'];
		$user_ids  = $usersData['user_ids'];
		$DH_uids   = $usersData['DH_uids'];
		$DH_depotwise = $usersData['DH_depotwise'];

		$output['users'] = $users;
		$result['DH_depotwise'] = $DH_depotwise;

		// ================================
		// 5. USER ROUTES
		// ================================
		$userRoutes = $this->query("
			SELECT ur.route_ids, ur.user_id, ur.year, ur.month, ur.week, ur.day 
			FROM user_routes ur 
			WHERE ur.user_id IN (".implode(',', $user_ids).") $userRouteCond
		");
		
		
		// ================================
		// 6. Initialized structured routes + ROUTE IDS + NAMES
		// ================================
		$routeData = $this->_processUserRoutes($userRoutes); //buildStructuredRoutes

		$structuredUserRoutes 		= $routeData['structuredUserRoutes']; // Initialized structured routes -- [uid][year][month][week][day] = structured array
		$route_ids            		= $routeData['route_ids'];
		$user_route_ids       		= $routeData['user_route_ids'];
		$result['userRouteNames'] 	= $routeData['userRouteNames'];


		// ================================
		// 7. ROUTE CUSTOMER COUNTS
		// ================================
		$routeCustCounts = $this->_getRouteCustomerCounts($route_ids, $d1, $d2, $ccC); //fetchRouteCustomerCounts

		// ================================
		// 8. POPULATE ROUTE COUNTS
		// ================================
		/* $this->_populateRouteCounts(
			$structuredUserRoutes, $routeCustCounts, $DH_uids,
			$d1, $d2, $params, $rpPeriodByDates, $diffRPPeriodDates
		); */

		// ================================
		// 9. EXPECTED FREQUENCY
		// ================================
		// STEP 1
		$structuredUserRoutes = $this->_populateStructuredRoutes(
			$structuredUserRoutes, $routeCustCounts, $DH_uids,
			$d1, $d2, $params, $dateParams, $diffRPPeriodDates, $rpPeriodByDates
		);

		// STEP 2
		$exFreqResult = $this->_buildExpectedFrequency(
			$structuredUserRoutes,
			$d1, $d2, $params, $dateParams, $diffRPPeriodDates, $rpPeriodByDates
		);

		// merge into main result
		foreach ($exFreqResult as $uid => $data) {
			if (!isset($result[$uid])) {
				$result[$uid] = array();
			}
			$result[$uid] = array_merge($result[$uid], $data);
		}

		// ================================
		// 10. CALL ACTIVITY (UNCHANGED LOGIC)
		// ================================
		
		
		$odpC = $fidpC = $rddpC = $indpC = $cvdpC = "";
		// Only build conditions if depot_ids is not empty and not just [0]
		if (!empty($depot_ids) && !(count($depot_ids) === 1 && $depot_ids[0] == 0)) {
			$odpC = " AND sl.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$fidpC = " AND fi.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$rddpC = " AND rsi.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$indpC = " AND inc.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$cvdpC = " AND cv.depot_id IN (" . implode(', ', $depot_ids) . ")";
		}

		$callConds = [
			'oC' => $oC,
			'fiC' => $fiC,
			'rdC' => $rdC,
			'inC' => $inC,
			'cvC' => $cvC,
			'ccC' => $ccC,
			'vcC'  => $vcC,
			'cnameC' => " AND NOT (c.first_name IS NULL) AND NOT (c.last_name IS NULL)",

			'odpC' => $odpC,
			'fidpC' => $fidpC,
			'rddpC' => $rddpC,
			'indpC' => $indpC,
			'cvdpC' => $cvdpC,
		];
		
		//“If two different users make entry on one customer in a day, the entry should be counted as one entry and the entry should be credited to the user who created the customer” - Updated later to credit the entry to the user who visited first
			
		//Know User IDs of Role RM and Above (Supervision Roles) : Currently, the report is generated only for DMs and roles below. Therefore, we do not need to perform debit-credit operations if the customer is visited by users with the role of RM or above.

		// Supervision roles (RM and above)
		
		$User = ClassRegistry::init('User');
		$supervisionRoleUserIds = $User->find('list', array('fields' => array('User.id'), 'joins' => array(array('table' => 'roles', 'alias' => 'Role', 'type' => 'INNER', 'conditions' => array('User.role_id = Role.id', 'Role.grade <=' => RM)))));  //pr(count($supervisionRoleUserIds));

		/* $callData = $this->_processCallActivities($result, $params, $user_ids, $depot_ids, $callConds); //buildCallMetrics

		$result = array_merge_recursive($result, $callData['result']);
		$customerActivity = $callData['customerActivity'];
		$firstCallPerCustomer = $callData['firstCallPerCustomer'];	 */
		
		$callData = $this->_processCallActivities($result, $params, $user_ids, $depot_ids, $callConds, $supervisionRoleUserIds); 
		 
		$customerActivity = $callData['customerActivity'];
		//$firstCallPerCustomer = $callData['firstCallPerCustomer'];
		$customerAddedBy = $callData['customerAddedBy'];
		
		/* $creditDebitData = $this->_processCreditDebit($result, $customerActivity, $firstCallPerCustomer, $user_ids);
		
		$result = array_merge($result, $creditDebitData['result']); */
		
		//$this->_processCreditDebit($result, $customerActivity, $firstCallPerCustomer, $supervisionRoleUserIds);
		
		$isDatewise = !empty($params['datewise_monitoring']);
		$this->_processCreditDebit($result, $customerActivity, $customerAddedBy, $supervisionRoleUserIds, $isDatewise);
		
		//$result['debitCalls'] = $creditDebitData['debitCalls'];
		//$result['creditCalls'] = $creditDebitData['creditCalls'];
		
		
		//$callData = $this->processCallActivities($params, $filters, $user_ids);

		// ================================
		// 11. MERGE
		// ================================
		//$result = $this->_mergeCallData($result, $callData);

		$output['result'] = $result;

		return $output;
	}
	
	function _buildDateConditions($params){
		$dateParams = $params['dateParams'];

		switch ($params['type']) {

			case 'daily':
				$date = $dateParams['date'];

				return [
					'd1' => $date,
					'd2' => $date,
					'oC' => "sl.sale_date = '$date'",
					'fiC' => "fi.sale_date = '$date'",
					'rdC' => "rsi.sale_date = '$date'",
					'cvC' => "cv.visiting_date LIKE '".$date."%'",
					'ccC' => "c.created <= '$date 23:59:59'",
					'vcC' => "c.verified_date <= '$date'",
					'inC' => "inc.incentive_date = '$date'"
				];

			default:
				$d1 = $dateParams['from'];
				$d2 = $dateParams['to'];

				return [
					'd1' => $d1,
					'd2' => $d2,
					'oC' => "sl.sale_date between '$d1' AND '$d2'",
					'fiC' => "fi.sale_date between '$d1' AND '$d2'",
					'rdC' => "rsi.sale_date between '$d1' AND '$d2'",
					'cvC' => "cv.visiting_date between '$d1' AND '$d2 23:59:59'",
					'ccC' => "c.created <= '$d2 23:59:59'",
					'vcC' => "c.verified_date <= '$d2'",
					'inC' => "inc.incentive_date between '$d1' AND '$d2'"
				];
		}
	}
	
	function _buildRoutePlanConditions($params) {
		$userRouteCond = "";
		$rpPeriodByDates = $diffRPPeriodDates = [];

		switch($params['type']){
			case 'daily':

				$ptg_year 	= date('Y', strtotime($params['dateParams']['date']));
				$ptg_month 	= $params['dateParams']['month'];
				$ptg_week 	= $params['dateParams']['week'];
				$ptg_day 	= date('l', strtotime($params['dateParams']['date']));

				$i_ptgPeriod = ['year' => $ptg_year, 'month' => $ptg_month, 'week' => $ptg_week];

				$rpPeriod = getRoutePlanPeriod($params['dateParams']['date'], $params['RPTGCalendar']);

				$rp_year  = $rpPeriod['year'];
				$rp_month = $rpPeriod['month'];
				$rp_week  = $rpPeriod['week'];
				$rp_day 	= date('l', strtotime($params['dateParams']['date']));

				$userRouteCond =
					" AND ur.year = '$rp_year'
					  AND ur.month = '$rp_month'
					  AND ur.week = '$rp_week'
					  AND ur.day = '$rp_day'";

				// Check if PTG calendar period differs from route plan period
				if (
					$i_ptgPeriod['year']  != $rp_year ||
					$i_ptgPeriod['month'] != $rp_month ||
					$i_ptgPeriod['week']  != $rp_week
				) {
					$rpPeriodByDates[$params['dateParams']['date']] = [
						'year'  => $rp_year,
						'month' => $rp_month,
						'week'  => $rp_week,
						'day'   => $rp_day
					];

					$diffRPPeriodDates[] = $date;
				}

			break;



			case 'weekly':

				$ptg_year 	= date('Y', strtotime($params['dateParams']['from']));
				$ptg_month 	= $params['dateParams']['month'];
				$ptg_week 	= $params['dateParams']['week'];

				$i_ptgPeriod = [
					'year'  => $ptg_year,
					'month' => $ptg_month,
					'week'  => $ptg_week
				];

				$datesInWeekArr = $params['RPTGCalendar']['calendar'][$ptg_month][$ptg_week];

				if (count($datesInWeekArr) > 7) {

					$buildDailyRouteCondData = buildDailyRouteConditions($datesInWeekArr, $params['RPTGCalendar'], $i_ptgPeriod);

					// Build final condition
					$userRouteCond = " AND (" . implode(" OR ", $buildDailyRouteCondData['sqlConditions']) . ")";
					
					$rpPeriodByDates = $buildDailyRouteCondData['rpPeriodByDates'];
					$diffRPPeriodDates = $buildDailyRouteCondData['diffRPPeriodDates'];

				} else {

					$userRouteCond =
						" AND ur.year = '$ptg_year'
						  AND ur.month = '$ptg_month'
						  AND ur.week = '$ptg_week'";
				}

			break;


			case 'monthly':

				$ptg_year 	= date('Y', strtotime($params['dateParams']['from']));
				$ptg_month 	= $params['dateParams']['month'];

				$monthlyRouteConditions = [];
					
				foreach ($params['RPTGCalendar']['calendar'][$ptg_month] as $i_ptg_weekNo => $datesInWeekArr) {

					// Week with >7 days — process each day
					if (count($datesInWeekArr) > 7) {
						$params['RPTGCalendar']['week'] = $i_ptg_weekNo;
						
						$i_ptgPeriod = ['year' => $ptg_year, 'month' => $ptg_month, 'week' => $i_ptg_weekNo];
						
						$buildDailyRouteCondData = buildDailyRouteConditions($datesInWeekArr,$params['RPTGCalendar'], $i_ptgPeriod ); 
						$monthlyRouteConditions = array_merge($monthlyRouteConditions, $buildDailyRouteCondData['sqlConditions']);
						
						$rpPeriodByDates   = array_merge($rpPeriodByDates, $buildDailyRouteCondData['rpPeriodByDates']);
						$diffRPPeriodDates = array_merge($diffRPPeriodDates, $buildDailyRouteCondData['diffRPPeriodDates']);

					} else {
						// Regular week — use simple condition
						$monthlyRouteConditions[] =
							"ur.year = '$ptg_year' AND ur.month = '$ptg_month' AND ur.week = '$i_ptg_weekNo'";
					}
				}

				// Final combined filter for the month
				$userRouteCond = " AND (" . implode(" OR ", $monthlyRouteConditions) . ")";

			break;


			case 'between':
					## NEED TO Work On this
					$userRouteCond = ""; //pr($userRouteCond);
				
					break;
		}

		return [
			'userRouteCond'      => $userRouteCond,
			'rpPeriodByDates'    => $rpPeriodByDates,
			'diffRPPeriodDates'  => $diffRPPeriodDates
		];
	}
	
	function _buildUserFilters($query){
		$Depot = ClassRegistry::init('Depot');
		$filters = [
			'userDVC' => '',
			'userRC'  => '',
			'userDC'  => '',
			'userId'  => '',
			'depot_ids' => []
		];

		// ================================
		// Division Filter
		// ================================
		if (!empty($query['dv'])) {
			$filters['userDVC'] = " AND u.division_id = ".$query['dv'];

			// get regions under division
			$DivisionsRegion = ClassRegistry::init('DivisionsRegion');
			$rIds = $DivisionsRegion->find('list', [
				'fields' => ['region_id'],
				'conditions' => ['division_id' => $query['dv']]
			]);

			// get depots under those regions
			if (!empty($rIds)) {
				
				$filters['depot_ids'] = $Depot->find('list', [
					'fields' => ['id'],
					'conditions' => ['Depot.region_id' => $rIds]
				]);
			}
		}

		// ================================
		// Region Filter
		// ================================
		if (!empty($query['rg'])) {
			$filters['userRC'] = " AND u.region_id = ".$query['rg'];

			$filters['depot_ids'] = $Depot->find('list', [
				'fields' => ['id'],
				'conditions' => ['Depot.region_id' => $query['rg']]
			]);
		}

		// ================================
		// Depot Filter
		// ================================
		if (!empty($query['dp'])) {
			$filters['userDC'] = " AND u.depot_id = ".$query['dp'];

			$filters['depot_ids'] = [$query['dp']];
		}

		// ================================
		// User Filter
		// ================================
		if (!empty($query['us'])) {
			$filters['userId'] = " AND u.id = ".$query['us'];
		}

		return $filters;
	}
	
	function _fetchFreqReportUsers($filters, $params){
		$usersData = $this->query("
			SELECT u.id, u.first_name, u.last_name, u.division_id,
				   u.region_id, u.depot_id, u.role_id, u.status,
				   r.name, d.title
			FROM users u
			INNER JOIN roles r ON u.role_id = r.id
			LEFT JOIN depots d ON d.id = u.depot_id
			LEFT JOIN regions rg ON rg.id = u.region_id
			WHERE r.grade > 3
			{$filters['userDVC']} {$filters['userRC']} {$filters['userDC']} {$filters['userId']}
			ORDER BY rg.title ASC, u.role_id ASC
		");
	
		$users = $user_ids = [];
		$DH_uids = $DH_depotwise = [];
		$depot_ids = [];

		foreach ($usersData as $u) {
			$uid = $u['u']['id'];
			$rid = ($u['u']['region_id']) ? $u['u']['region_id']:0;
			$did = ($u['u']['depot_id']) ? $u['u']['depot_id']:0;

			$users[$rid][$did][$uid] = [
				'uid' => $uid,
				'name' => $u['u']['first_name'].' '.$u['u']['last_name'],
				'rid'=>$u['u']['role_id'],
				'role' => $u['r']['name'],
				'division_id'=>$u['u']['division_id'],
				'region_id'=>$u['u']['region_id'],
				'depot_id'=>$u['u']['depot_id'],
				'depot'=>$u['d']['title'],
				'status'=>$u['u']['status']
			];

			if (!in_array($uid, $user_ids)){
				array_push($user_ids, $uid);
			}
			if (!empty($params['query']['us'])){
				$depot_ids = array($did);
			}
			
			// ------------------------------
			// DH DEPOT-WISE GROUPING
			// ------------------------------
			if ($u['u']['role_id'] == DH) {
				## list DH
				// Add to standalone DH_uids list 
				$DH_uids[] = $uid;

				// Add inside DH_depotwise
				if (!isset($DH_depotwise[$did])) {
					$DH_depotwise[$did] = [];
				}

				// Store user id only
				$DH_depotwise[$did][] = $uid;
				
				if (!empty($params['query']['us'])){
					$User = ClassRegistry::init('User');
					//Find other DH 
					$otherDH = $User->find('list', array('fields' => array('id'), 'conditions' => array('User.role_id' => DH, 'User.depot_id' => $did))); //pr($otherDH);
					
					if(!empty($otherDH)){
						foreach ($otherDH as $odid) {

							// Skip current user
							if ($odid == $uid) continue;

							// Add to master DH list
							if (!in_array($odid, $DH_uids)) {
								$DH_uids[] = $odid;
							}

							// Add to depotwise list
							if (!in_array($odid, $DH_depotwise[$did])) {
								$DH_depotwise[$did][] = $odid;
							}

							// Add to user_ids list
							if (!in_array($odid, $user_ids)) {
								$user_ids[] = $odid;
							}
						}
					}
				}
			}
		}

		return compact('users','user_ids','DH_uids','DH_depotwise', 'depot_ids');
	}
	
	function _processUserRoutes($userRoutes){
		$structuredUserRoutes = [];
		$route_ids = [];
		$user_route_ids = [];
		// load route names
		$userRouteNames = [];

		if (!empty($userRoutes)) {

			foreach ($userRoutes as $ur) {

				$uid   = !empty($ur['ur']['user_id']) ? $ur['ur']['user_id'] : 0;
				$urrids = !empty($ur['ur']['route_ids']) ? explode(',', $ur['ur']['route_ids']) : [];
				$uryr  = !empty($ur['ur']['year']) ? $ur['ur']['year'] : 0;
				$urmn  = !empty($ur['ur']['month']) ? $ur['ur']['month'] : 0;
				$urwk  = !empty($ur['ur']['week']) ? $ur['ur']['week'] : 0;
				$urday = !empty($ur['ur']['day']) ? $ur['ur']['day'] : "";

				// Collect all route IDs for later use
				$route_ids = array_unique(array_merge($route_ids, $urrids));

				// per user route ids
				if (!isset($user_route_ids[$uid])) {
					$user_route_ids[$uid] = $urrids;
				} else {
					$user_route_ids[$uid] = array_unique(array_merge($user_route_ids[$uid], $urrids));
				}

				// Initialize structured routes entry
				if (!isset($structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday])) {
					$structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday] = [
						'route_ids' => [],
						'us_custno' => [],
						'us_custno_total' => [],
						'rt_custno' => [],
						'rt_custno_total' => []
					];
				}

				// assign route ids - Add the route IDs to route_ids only
				$structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday]['route_ids'] =
					array_unique(array_merge(
						$structuredUserRoutes[$uid][$uryr][$urmn][$urwk][$urday]['route_ids'],
						$urrids
					));
			}
			
			if(!empty($route_ids)){
				$routeQuery = $this->query("SELECT id, title FROM routes WHERE id IN (" . implode(',', $route_ids) . ") ");
				
				if(!empty($routeQuery)){
					foreach ($routeQuery as $r) {
						$userRouteNames[$r['routes']['id']] = $r['routes']['title'];
					}
				}
			}
		}

		return [
			'structuredUserRoutes' => $structuredUserRoutes,
			'route_ids' => $route_ids,
			'user_route_ids' => $user_route_ids,
			'userRouteNames' => $userRouteNames
		];
	}
	
	function _getRouteCustomerCounts($route_ids, $d1, $d2, $ccC){
		$routeCustCounts = [];

		if (empty($route_ids)) {
			return $routeCustCounts;
		}

		// ==============================
		// Build dynamic COUNT columns -- Prepare COUNT columns for each day in the period
		// ==============================
		$custno_cases = [];

		// Loop through each day in the period and create a COUNT for each day	
		for ($dt = $d1; $dt <= $d2; $dt = date('Y-m-d', strtotime('+1 day', strtotime($dt)))) {

			$col = 'cust_' . str_replace('-', '_', $dt);

			$custno_cases[] = "
				COUNT(CASE 
					WHEN c.created <= '$dt 23:59:59' 
					THEN c.id 
				END) AS $col
			";
		}

		$custnoCols = implode(', ', $custno_cases);

		// ==============================
		// Query -- Fetch customer counts per route
		// ==============================
		$routeCustomers = $this->query("
			SELECT $custnoCols, c.route_id, c.user_id
			FROM customers c
			WHERE $ccC
			AND NOT (c.first_name IS NULL)
			AND NOT (c.last_name IS NULL)
			AND c.status = 1
			AND c.route_id IN (" . implode(',', $route_ids) . ")
			GROUP BY c.route_id
		");

		// ==============================
		// Map result -- Preprocess $userRouteCustomers into a lookup map for route counts
		// ==============================
		if (!empty($routeCustomers)) {

			foreach ($routeCustomers as $row) {

				$rid = $row['c']['route_id'];

				foreach ($row[0] as $col => $val) {

					if (strpos($col, 'cust_') !== 0) continue;

					$dt = str_replace(['cust_', '_'], ['', '-'], $col);

					$routeCustCounts[$rid][$dt] = intval($val);
				}
			}
		}

		return $routeCustCounts;
	}
	

	function _populateStructuredRoutes(
		$structuredUserRoutes, $routeCustCounts, $DH_uids,
		$d1, $d2, $params, $dateParams, $diffRPPeriodDates, $rpPeriodByDates
	) {

		for ($dt = $d1; $dt <= $d2; $dt = date('Y-m-d', strtotime('+1 day', strtotime($dt)))) {

			$yr_key = date('Y', strtotime($dt));
			$dy_key = date('l', strtotime($dt));
			$mn_key = $dateParams['month'];

			if (in_array($params['type'], array('daily', 'weekly'))) {
				$wk_key = $dateParams['week'];
			} elseif ($params['type'] == 'monthly') {
				$wk_key = getWeekNo($params['RPTGCalendar']['calendar'][$dateParams['month']], $dt);
			} else {
				// between 
				### NEED TO WORK
				$wk_key = 0; // between (same as your current behavior)
				
			}

			// Override route plan period  if date is in diffRPPeriodDates
			if (in_array($dt, $diffRPPeriodDates) && isset($rpPeriodByDates[$dt])) {
				$yr_key = $rpPeriodByDates[$dt]['year'];
				$mn_key = $rpPeriodByDates[$dt]['month'];
				$wk_key = $rpPeriodByDates[$dt]['week'];
			}

			if (!empty($structuredUserRoutes)) {

				foreach ($structuredUserRoutes as $uid => $yearsArr) {

					if (!isset($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key])) {

						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key] = array(
							'route_ids' => array(),
							'us_custno' => array(), 'us_custno_total' => array(),
							'rt_custno' => array(), 'rt_custno_total' => array()
						);
					}

					// If routes exist, assign counts
					foreach ($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['route_ids'] as $rid) {

						$count = isset($routeCustCounts[$rid][$dt]) ? $routeCustCounts[$rid][$dt] : 0;

						$us_count = $count;

						if (in_array($uid, $DH_uids)) {
							//$us_count = ceil($count / 2);
							$us_count = ($count / 2);
						}

						// USER
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['us_custno'][$dt][$rid] = $us_count;

						if (!isset($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['us_custno_total'][$dt])) {
							$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['us_custno_total'][$dt] = 0;
						}

						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['us_custno_total'][$dt] += $us_count;

						// For Route custno
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['rt_custno'][$dt][$rid] = $count;

						if (!isset($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['rt_custno_total'][$dt])) {
							$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['rt_custno_total'][$dt] = 0;
						}

						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['rt_custno_total'][$dt] += $count;
					}

					// no routes case -- If no route_ids, still assign zero for us_custno_total , rt_custno_total
					if (empty($structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['route_ids'])) {

						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['us_custno_total'][$dt] = 0;
						$structuredUserRoutes[$uid][$yr_key][$mn_key][$wk_key][$dy_key]['rt_custno_total'][$dt] = 0;
					}
				}

			}
		}

		return $structuredUserRoutes;
	}
	
	function _buildExpectedFrequency(
		$structuredUserRoutes,
		$d1, $d2, $params, $dateParams, $diffRPPeriodDates, $rpPeriodByDates
	) {
		
		$isDatewise = !empty($params['datewise_monitoring']);

		$exFreqResult = array();
		
		// Build daily & weekly expected frequency for **all dates**, even with no routes
		
		foreach ($structuredUserRoutes as $uid => $yearsArr) {

			$exFreqResult[$uid]['expected_freq'] = 0;
			$exFreqResult[$uid]['route_expected_freq'] = 0;

			for ($dt = $d1; $dt <= $d2; $dt = date('Y-m-d', strtotime('+1 day', strtotime($dt)))) {

				$yr_key = date('Y', strtotime($dt));
				$dy_key = date('l', strtotime($dt));
				$mn_key = $dateParams['month'];

				if (in_array($params['type'], array('daily', 'weekly'))) {
					$wk_key = $dateParams['week'];
				} else {
					$wk_key = getWeekNo($params['RPTGCalendar']['calendar'][$dateParams['month']], $dt);
				}

				$rp_yr_key = $yr_key;
				$rp_mn_key = $mn_key;
				$rp_wk_key = $wk_key;

				// Override with route plan period if date is in diffRPPeriodDates
				if (in_array($dt, $diffRPPeriodDates) && isset($rpPeriodByDates[$dt])) {
					$rp_yr_key = $rpPeriodByDates[$dt]['year'];
					$rp_mn_key = $rpPeriodByDates[$dt]['month'];
					$rp_wk_key = $rpPeriodByDates[$dt]['week'];
				}

				$dayInfo = isset($structuredUserRoutes[$uid][$rp_yr_key][$rp_mn_key][$rp_wk_key][$dy_key])
					? $structuredUserRoutes[$uid][$rp_yr_key][$rp_mn_key][$rp_wk_key][$dy_key]
					: ['us_custno' => [], 'us_custno_total' => [ $dt => 0 ]];

				$us_routes = isset($dayInfo['us_custno'][$dt]) ? $dayInfo['us_custno'][$dt] : [];
					
				$rt_routes = isset($dayInfo['rt_custno'][$dt]) ? $dayInfo['rt_custno'][$dt] : [];
				
				$dateObj = DateTime::createFromFormat('!m', $mn_key);
				$ptgMonthName = $dateObj->format('M');
				$ptgCalPeriod = $ptgMonthName . " " . $yr_key  . ", Week " . $wk_key;
				
				// Route Plan Period (inline)
				$dateObj = DateTime::createFromFormat('!m', $rp_mn_key);
				$rpMonthName = $dateObj->format('M');
				$routePlanPeriod = "$rpMonthName $rp_yr_key, Week $rp_wk_key";

				if (in_array($params['type'], array('daily', 'weekly')) || $isDatewise) {

					$exFreqResult[$uid]['userDailyExpFreq'][$dt] = [
						'ptgCalPeriod' => $ptgCalPeriod,
						'routePlanPeriod' => $routePlanPeriod,
						'day' => $dy_key,
						
						'us_routes' => $us_routes,
						'rt_routes' => $rt_routes,
					];
					
					//For Monitoring Report
					if($isDatewise){
						$exFreqResult[$uid]['userDailyExpFreq'][$dt]['us_expectedFreq'] = !empty($us_routes) ? array_sum($us_routes) : 0;
						$exFreqResult[$uid]['userDailyExpFreq'][$dt]['rt_expectedFreq'] = !empty($rt_routes) ? array_sum($rt_routes) : 0;
					}

				} else {

					if (!isset($exFreqResult[$uid]['userWklyExpFreq'][$mn_key][$wk_key])) {

						$exFreqResult[$uid]['userWklyExpFreq'][$mn_key][$wk_key] = [
							'us_expectedFreq' 	=> 0, 'rt_expectedFreq' 	=> 0,
							'ptgWeekRange' 		=> ['from' => $dt, 'to' => $dt],
							'RPPeriodRange' 	=> [['year'  => $rp_yr_key, 'month' => $rp_mn_key, 'week'  => $rp_wk_key, 'from'  => $dt, 'to'    => $dt]]];
					} else {
						$weekData = &$exFreqResult[$uid]['userWklyExpFreq'][$mn_key][$wk_key]; //pr($weekData); die();
						
						// Update PTG week range
						if (strtotime($dt) < strtotime($weekData['ptgWeekRange']['from'])) $weekData['ptgWeekRange']['from'] = $dt;
						if (strtotime($dt) > strtotime($weekData['ptgWeekRange']['to'])) $weekData['ptgWeekRange']['to'] = $dt;
						
						// Merge or add route plan period ranges
						$lastIndex = count($weekData['RPPeriodRange']) - 1;
						$lastRange = &$weekData['RPPeriodRange'][$lastIndex];
						$expectedNextDate = date('Y-m-d', strtotime($lastRange['to'] . ' +1 day'));

						if ($lastRange['year'] == $rp_yr_key && $lastRange['month'] == $rp_mn_key && $lastRange['week'] == $rp_wk_key && $expectedNextDate == $dt) {
							$lastRange['to'] = $dt; // extend range
						} else {
							$weekData['RPPeriodRange'][] = ['year'  => $rp_yr_key, 'month' => $rp_mn_key, 'week' => $rp_wk_key, 'from' => $dt, 'to' => $dt ];
						}
					}

					$exFreqResult[$uid]['userWklyExpFreq'][$mn_key][$wk_key]['us_expectedFreq'] += array_sum($us_routes);
					$exFreqResult[$uid]['userWklyExpFreq'][$mn_key][$wk_key]['rt_expectedFreq'] += array_sum($rt_routes);
				}
				
				$exFreqResult[$uid]['expected_freq'] += array_sum($us_routes);
				$exFreqResult[$uid]['route_expected_freq'] += array_sum($rt_routes);

				
			}
		}
		
		/* if($isDatewise){
			pr($exFreqResult); die();
		} */

		return $exFreqResult;
	}
	
	function _processCallActivities(&$result, $params, $user_ids, $depot_ids, $callConds, $supervisionRoleUserIds) {
		extract($callConds);
		
		
		
		$callResult = [];
		$customerActivity = [];
		$firstCallPerCustomer = [];
		
		$isDatewise = !empty($params['datewise_monitoring']);
		$firstLastCallPerUserForDay = [];

		// =========================
		// Calls
		// =========================
		
		$orderEntry = $this->query("SELECT SUM(sl.cal_qty) AS totQty, COUNT(DISTINCT CONCAT(sl.customer_id, '-', sl.sale_date)) AS oentry, sl.user_id, sl.depot_id, sl.sale_date, sl.customer_id, sl.via_app, MIN(sl.created) AS first_entry_time FROM sales sl WHERE $oC $odpC GROUP BY sl.user_id, sl.sale_date, sl.customer_id, sl.via_app");
			//pr($orderEntry); die();

		$freeItemEntry = $this->query("SELECT SUM(fi.cal_qty) AS totQtyFi, fi.user_id, fi.depot_id, fi.sale_date, fi.customer_id, fi.via_app FROM free_items fi WHERE $fiC $fidpC GROUP BY fi.user_id, fi.sale_date, fi.customer_id, fi.via_app"); //pr($freeItemEntry); //die();

		
		$rSaleEntry = $this->query("SELECT SUM(rsi.cal_qty) AS totQty, COUNT(DISTINCT CONCAT(rsi.customer_id, '-', rsi.sale_date)) AS rsentry, rsi.user_id, rsi.depot_id, rsi.sale_date, rsi.customer_id, rsi.via_app, MIN(rsi.created) AS first_entry_time FROM redistributor_saleitems rsi WHERE $rdC $rddpC GROUP BY rsi.user_id, rsi.sale_date, rsi.customer_id, rsi.via_app"); //pr($rSaleEntry); 
		
		$incentiveEntry = $this->query("SELECT SUM(inc.cal_qty) AS totQty, COUNT(DISTINCT CONCAT(inc.customer_id, '-', inc.incentive_date)) AS incentry, inc.user_id, inc.depot_id, inc.incentive_date, inc.customer_id, inc.via_app, MIN(inc.created) AS first_entry_time FROM incentives inc INNER JOIN customers as c on inc.customer_id = c.id WHERE $inC $indpC GROUP BY inc.user_id, inc.incentive_date, inc.customer_id, inc.via_app"); //pr($incentiveEntry); 

		
		$visitEntries = [];

		if(!empty($params['cvisityear_tables'])) {
				foreach ($params['cvisityear_tables'] as $year => $cv_tableName) {
					$visitEntries[$year] = $this->query("SELECT COUNT(DISTINCT CONCAT(cv.customer_id, '-', date(cv.visiting_date))) AS ventry, cv.user_id, cv.depot_id, date(cv.visiting_date) as vdate, cv.customer_id, cv.via_app, MIN(cv.created) AS first_entry_time FROM $cv_tableName cv WHERE $cvC $cvdpC GROUP BY cv.user_id, date(cv.visiting_date), cv.customer_id, cv.via_app");
				}
			}

		// ---- For Frequency Report ----
		if(!$isDatewise){
			// =========================
			// CUSTOMER MASTER DATA
			// =========================
			$customerEntry = $this->query("SELECT c.id, c.user_id, c.verified_latitude, c.verified_longitude, c.verified_by, c.verified_date FROM customers c WHERE $ccC $cnameC AND c.status = ".ACTIVE." AND c.user_id IN (".implode(', ', $user_ids).")");

			if (!empty($customerEntry)){
				foreach ($customerEntry as $c) {
					$uid = !empty($c['c']['user_id']) ? $c['c']['user_id'] : 0;
					$result[$uid]['customers'][] = $c['c']['id'];
				}
			}

			$verifiedCustomerEntry = $this->query("SELECT c.id, c.user_id, c.verified_latitude, c.verified_longitude, c.verified_by, c.verified_date FROM customers c WHERE $vcC $cnameC AND c.status = ".ACTIVE." AND c.user_id IN (".implode(', ', $user_ids).")"); 

			if (!empty($verifiedCustomerEntry)){
				foreach ($verifiedCustomerEntry as $c) {
					$uid = !empty($c['c']['user_id']) ? $c['c']['user_id'] : 0;

					if (
						!empty($c['c']['verified_latitude']) &&
						!empty($c['c']['verified_longitude']) &&
						!empty($c['c']['verified_by']) &&
						!empty($c['c']['verified_date'])
					) {
						$result[$uid]['verified_customers'][] = $c['c']['id'];
					}
				}
			}
			//pr('Verified Customers '.$vc);
		}	
		

		// =========================
		// PROCESS SALES ENTRY
		// =========================
		if (!empty($orderEntry)){
			foreach ($orderEntry as $oe){
				$uid = !empty($oe['sl']['user_id']) ? $oe['sl']['user_id'] : 0 ;
				$cid = !empty($oe['sl']['customer_id']) ? $oe['sl']['customer_id'] : 0 ; 
				$did = !empty($oe['sl']['depot_id']) ? $oe['sl']['depot_id'] : 0;
				$sale_date = date(DATE_FORMAT_SORT, strtotime($oe['sl']['sale_date']));
				$created_time = $oe['0']['first_entry_time'];
				
				if(!empty($oe['sl']['via_app'])){
					
					// ---- For Frequency Report ----
					if(!$isDatewise){
						if(empty($result[$uid]['call']['saleEntry'])){
							$result[$uid]['call']['saleEntry'] = $oe['0']['oentry'];
						}else{
							$result[$uid]['call']['saleEntry'] += $oe['0']['oentry'];
						}
						
						if(empty($result[$uid]['call']['customerCalls'][$cid]['saleEntry'])){
							$result[$uid]['call']['customerCalls'][$cid]['saleEntry'] = $oe['0']['oentry'];
						}else{
							$result[$uid]['call']['customerCalls'][$cid]['saleEntry'] += $oe['0']['oentry'];
						}
						
						if(empty($result[$uid]['call']['customersVisited'][$cid])){
							$result[$uid]['call']['customersVisited'][$cid] = array($sale_date);
						}else{
							if(!in_array($sale_date, $result[$uid]['call']['customersVisited'][$cid])){ 
								array_push($result[$uid]['call']['customersVisited'][$cid], $sale_date);
							}
						}
					}	
					//----------------------------------
					
					// ---- For Both Frequency & Monitoring Report ----
					//customer activity 
					$activityCall = ['type' => 'saleEntry', 'saleEntry' => $oe['0']['oentry'], 'saleVol' => $oe['0']['totQty']];
					if (!isset($customerActivity[$cid]['calls'][$sale_date][$uid])) {
						$customerActivity[$cid]['calls'][$sale_date][$uid] = [$activityCall];
					} else {
						$customerActivity[$cid]['calls'][$sale_date][$uid][] = $activityCall;
					}

					// --- Track first call per customer/day ---
					if (!in_array($uid, $supervisionRoleUserIds)) {
						if (!isset($firstCallPerCustomer[$cid][$sale_date]) || 
							$created_time < $firstCallPerCustomer[$cid][$sale_date]['time']) {
							$firstCallPerCustomer[$cid][$sale_date] = ['time' => $created_time, 'user_id' => $uid, 'type' => 'Sale'];
						}
					}
				}				
				
				// ---- For Frequency Report ----
				if(!$isDatewise){
					if(empty($result[$uid]['call']['saleVol'])){
						$result[$uid]['call']['saleVol'] = $oe['0']['totQty'];
					}else{
						$result[$uid]['call']['saleVol'] += $oe['0']['totQty'];
					}
									
					if(empty($result[$uid]['call']['customerCalls'][$cid]['saleVol'])){
						$result[$uid]['call']['customerCalls'][$cid]['saleVol'] = $oe['0']['totQty'];
					}else{
						$result[$uid]['call']['customerCalls'][$cid]['saleVol'] += $oe['0']['totQty'];
					}
				}
				
				// ---- For Monitoring Report ----
				if($isDatewise){
					
					if(empty($result[$uid]['call']['dailyCustomersVisited'][$sale_date])){
						$result[$uid]['call']['dailyCustomersVisited'][$sale_date] = array($cid);
					}else{
						if(!in_array($cid, $result[$uid]['call']['dailyCustomersVisited'][$sale_date])){ 
							array_push($result[$uid]['call']['dailyCustomersVisited'][$sale_date], $cid);
						}
					}
					
					if(empty($result[$uid]['call']['userDailyCalls'][$sale_date]['saleVol'])){
						$result[$uid]['call']['userDailyCalls'][$sale_date]['saleVol'] = $oe['0']['totQty'];
					}else{
						$result[$uid]['call']['userDailyCalls'][$sale_date]['saleVol'] += $oe['0']['totQty'];
					}
					
					// --- Track first-last call per user/day ---
					if (!isset($firstLastCallPerUserForDay[$uid][$sale_date]['first_call']) || 
						$created_time < $firstLastCallPerUserForDay[$uid][$sale_date]['first_call']['time']) {
						$firstLastCallPerUserForDay[$uid][$sale_date]['first_call'] = ['time' => $created_time, 'customer_id' => $cid, 'type' => 'Sale'];
					}
					if (!isset($firstLastCallPerUserForDay[$uid][$sale_date]['last_call']) || 
						$created_time > $firstLastCallPerUserForDay[$uid][$sale_date]['last_call']['time']) {
						$firstLastCallPerUserForDay[$uid][$sale_date]['last_call'] = ['time' => $created_time, 'customer_id' => $cid, 'type' => 'Sale'];
					}
				}
			}
		}

		// =========================
		// FREE ITEMS
		// =========================
		if (!empty($freeItemEntry)){
			foreach ($freeItemEntry as $fe){
				$uid = !empty($fe['fi']['user_id']) ? $fe['fi']['user_id'] : 0 ;
				$cid = !empty($fe['fi']['customer_id']) ? $fe['fi']['customer_id'] : 0 ;
				$did = !empty($fe['fi']['depot_id']) ? $fe['fi']['depot_id'] : 0;
				$sale_date = date(DATE_FORMAT_SORT, strtotime($fe['fi']['sale_date']));
				
				// ---- For Frequency Report ----
				if(!$isDatewise){
					if(empty($result[$uid]['call']['saleFiVol'])){
						$result[$uid]['call']['saleFiVol'] = $fe['0']['totQtyFi'];
					}else{
						$result[$uid]['call']['saleFiVol'] += $fe['0']['totQtyFi'];
					}
									
					if(empty($result[$uid]['call']['customerCalls'][$cid]['saleFiVol'])){
						$result[$uid]['call']['customerCalls'][$cid]['saleFiVol'] = $fe['0']['totQtyFi'];
					}else{
						$result[$uid]['call']['customerCalls'][$cid]['saleFiVol'] += $fe['0']['totQtyFi'];
					}
				}	
				
				//----------------------------------
					
				// ---- For Both Frequency & Monitoring Report ----
				//customer activity 
				$activityCall = ['type' => 'saleFi', 'saleFiVol' => $fe['0']['totQtyFi']];
				if (!isset($customerActivity[$cid]['calls'][$sale_date][$uid])) {
					$customerActivity[$cid]['calls'][$sale_date][$uid] = [$activityCall];
				} else {
					$customerActivity[$cid]['calls'][$sale_date][$uid][] = $activityCall;
				}
				
				
				// ---- For Monitoring Report ----
				if($isDatewise){
					if(empty($result[$uid]['call']['userDailyCalls'][$sale_date]['saleFiVol'])){
						$result[$uid]['call']['userDailyCalls'][$sale_date]['saleFiVol'] = $fe['0']['totQtyFi'];
					}else{
						$result[$uid]['call']['userDailyCalls'][$sale_date]['saleFiVol'] += $fe['0']['totQtyFi'];
					}
				}
			}
		}

		// =========================
		// RS SALES
		// =========================
		if (!empty($rSaleEntry)){
			foreach ($rSaleEntry as $rse){
				$uid = !empty($rse['rsi']['user_id']) ? $rse['rsi']['user_id'] : 0 ;
				$cid = !empty($rse['rsi']['customer_id']) ? $rse['rsi']['customer_id'] : 0 ;
				$did = !empty($rse['rsi']['depot_id']) ? $rse['rsi']['depot_id'] : 0;
				$sale_date = date(DATE_FORMAT_SORT, strtotime($rse['rsi']['sale_date']));
				$created_time = $rse['0']['first_entry_time'];
				
				if(!empty($rse['rsi']['via_app'])){
					// ---- For Frequency Report ----
					if(!$isDatewise){
						if(empty($result[$uid]['call']['rsSaleEntry'])){
							$result[$uid]['call']['rsSaleEntry'] = $rse['0']['rsentry'];
						}else{
							$result[$uid]['call']['rsSaleEntry'] += $rse['0']['rsentry'];
						}
						if(empty($result[$uid]['call']['customerCalls'][$cid]['rsSaleEntry'])){
							$result[$uid]['call']['customerCalls'][$cid]['rsSaleEntry'] = $rse['0']['rsentry'];
						}else{
							$result[$uid]['call']['customerCalls'][$cid]['rsSaleEntry'] += $rse['0']['rsentry'];
						}
						
						if(empty($result[$uid]['call']['customersVisited'][$cid])){
							$result[$uid]['call']['customersVisited'][$cid] = array($sale_date);
						}else{
							if(!in_array($sale_date, $result[$uid]['call']['customersVisited'][$cid])){ 
								array_push($result[$uid]['call']['customersVisited'][$cid], $sale_date);
							}
						}
						
					}	
					//----------------------------------
					
					// ---- For Both Frequency & Monitoring Report ----

					//customer activity 
					$activityCall = ['type' => 'rsSaleEntry', 'rsSaleEntry' => $rse['0']['rsentry'], 'rsSaleVol' => $rse['0']['totQty']];
					if (!isset($customerActivity[$cid]['calls'][$sale_date][$uid])) {
						$customerActivity[$cid]['calls'][$sale_date][$uid] = [$activityCall];
					} else {
						$customerActivity[$cid]['calls'][$sale_date][$uid][] = $activityCall;
					}
					
					// --- Track first call per customer/day ---
					if (!in_array($uid, $supervisionRoleUserIds)) {
						if (!isset($firstCallPerCustomer[$cid][$sale_date]) || 
							$created_time < $firstCallPerCustomer[$cid][$sale_date]['time']) {
							$firstCallPerCustomer[$cid][$sale_date] = [
								'time' => $created_time,
								'user_id' => $uid,
								'type' => 'RSale'
							];
						}
					}
				}
				
				// ---- For Frequency Report ----
				if(!$isDatewise){
					if(empty($result[$uid]['call']['rsSaleVol'])){
						$result[$uid]['call']['rsSaleVol'] = $rse['0']['totQty'];
					}else{
						$result[$uid]['call']['rsSaleVol'] += $rse['0']['totQty'];
					}
								
					if(empty($result[$uid]['call']['customerCalls'][$cid]['rsSaleVol'])){
						$result[$uid]['call']['customerCalls'][$cid]['rsSaleVol'] = $rse['0']['totQty'];
					}else{
						$result[$uid]['call']['customerCalls'][$cid]['rsSaleVol'] += $rse['0']['totQty'];
					}
				}
				 
				// ---- For Monitoring Report ----
				if($isDatewise){
					
					if(empty($result[$uid]['call']['dailyCustomersVisited'][$sale_date])){
						$result[$uid]['call']['dailyCustomersVisited'][$sale_date] = array($cid);
					}else{
						if(!in_array($cid, $result[$uid]['call']['dailyCustomersVisited'][$sale_date])){ 
							array_push($result[$uid]['call']['dailyCustomersVisited'][$sale_date], $cid);
						}
					}					
					
					if(empty($result[$uid]['call']['userDailyCalls'][$sale_date]['rsSaleVol'])){
						$result[$uid]['call']['userDailyCalls'][$sale_date]['rsSaleVol'] = $rse['0']['totQty'];
					}else{
						$result[$uid]['call']['userDailyCalls'][$sale_date]['rsSaleVol'] += $rse['0']['totQty'];
					}
					
					// --- Track first-last call per user/day ---
					if (!isset($firstLastCallPerUserForDay[$uid][$sale_date]['first_call']) || 
						$created_time < $firstLastCallPerUserForDay[$uid][$sale_date]['first_call']['time']) {
						$firstLastCallPerUserForDay[$uid][$sale_date]['first_call'] = ['time' => $created_time, 'customer_id' => $cid, 'type' => 'RSale'];
					}
					if (!isset($firstLastCallPerUserForDay[$uid][$sale_date]['last_call']) || 
						$created_time > $firstLastCallPerUserForDay[$uid][$sale_date]['last_call']['time']) {
						$firstLastCallPerUserForDay[$uid][$sale_date]['last_call'] = ['time' => $created_time, 'customer_id' => $cid, 'type' => 'RSale'];
					}
				}
			}
		}

		// =========================
		// INCENTIVES
		// =========================
		if (!empty($incentiveEntry)){
			foreach ($incentiveEntry as $ine){
				$uid = !empty($ine['inc']['user_id']) ? $ine['inc']['user_id'] : 0 ;
				$cid = !empty($ine['inc']['customer_id']) ? $ine['inc']['customer_id'] : 0 ; 
				$did = !empty($ine['inc']['depot_id']) ? $ine['inc']['depot_id'] : 0;
				$incentive_date = date(DATE_FORMAT_SORT, strtotime($ine['inc']['incentive_date']));
				$created_time = $ine['0']['first_entry_time'];
				
				if(!empty($ine['inc']['via_app'])){
					// ---- For Frequency Report ----
					if(!$isDatewise){
						if(empty($result[$uid]['call']['incentiveEntry'])){
							$result[$uid]['call']['incentiveEntry'] = $ine['0']['incentry'];
						}else{
							 $result[$uid]['call']['incentiveEntry'] += $ine['0']['incentry'];
						}					
						if(empty($result[$uid]['call']['customerCalls'][$cid]['incentiveEntry'])){
							$result[$uid]['call']['customerCalls'][$cid]['incentiveEntry'] = $ine['0']['incentry'];
						}else{
							$result[$uid]['call']['customerCalls'][$cid]['incentiveEntry'] += $ine['0']['incentry'];
						}
						
						if(empty($result[$uid]['call']['customersVisited'][$cid])){
							$result[$uid]['call']['customersVisited'][$cid] = array($incentive_date);
						}else{
							if(!in_array($incentive_date, $result[$uid]['call']['customersVisited'][$cid])){
								array_push($result[$uid]['call']['customersVisited'][$cid], $incentive_date);
							}
						}
					}
						
					//----------------------------------
					
					// ---- For Both Frequency & Monitoring Report ----
																				
					//customer activity 					
					$activityCall = ['type' => 'incentiveEntry', 'incentiveEntry' => $ine['0']['incentry'], 'incentiveVol' => $ine['0']['totQty']];
					if (!isset($customerActivity[$cid]['calls'][$incentive_date][$uid])) {
						$customerActivity[$cid]['calls'][$incentive_date][$uid] = [$activityCall];
					} else {
						$customerActivity[$cid]['calls'][$incentive_date][$uid][] = $activityCall;
					}
					
					
					// --- Track first call per customer/day ---
					if (!in_array($uid, $supervisionRoleUserIds)) {
						if (!isset($firstCallPerCustomer[$cid][$incentive_date]) || 
							$created_time < $firstCallPerCustomer[$cid][$incentive_date]['time']) {
							$firstCallPerCustomer[$cid][$incentive_date] = [
								'time' => $created_time,
								'user_id' => $uid,
								'type' => 'Incentive'
							];
						}
					}
				}
				
				// ---- For Frequency Report ----
				if(!$isDatewise){
					if(empty($result[$uid]['call']['incentiveVol'])){
						$result[$uid]['call']['incentiveVol'] = $ine['0']['totQty'];
					}else{
						$result[$uid]['call']['incentiveVol'] += $ine['0']['totQty'];
					}			
					
					if(empty($result[$uid]['call']['customerCalls'][$cid]['incentiveVol'])){
						$result[$uid]['call']['customerCalls'][$cid]['incentiveVol'] = $ine['0']['totQty'];
					}else{
						$result[$uid]['call']['customerCalls'][$cid]['incentiveVol'] += $ine['0']['totQty'];
					}
				}
				
				// ---- For Monitoring Report ----
				if($isDatewise){
					
					if(empty($result[$uid]['call']['dailyCustomersVisited'][$incentive_date])){
						$result[$uid]['call']['dailyCustomersVisited'][$incentive_date] = array($cid);
					}else{
						if(!in_array($cid, $result[$uid]['call']['dailyCustomersVisited'][$incentive_date])){ 
							array_push($result[$uid]['call']['dailyCustomersVisited'][$incentive_date], $cid);
						}
					}
					
					if(empty($result[$uid]['call']['userDailyCalls'][$incentive_date]['incentiveVol'])){
						$result[$uid]['call']['userDailyCalls'][$incentive_date]['incentiveVol'] = $ine['0']['totQty'];
					}else{
						$result[$uid]['call']['userDailyCalls'][$incentive_date]['incentiveVol'] += $ine['0']['totQty'];
					}	
					
					// --- Track first-last call per user/day ---
					if (!isset($firstLastCallPerUserForDay[$uid][$incentive_date]['first_call']) || 
						$created_time < $firstLastCallPerUserForDay[$uid][$incentive_date]['first_call']['time']) {
						$firstLastCallPerUserForDay[$uid][$incentive_date]['first_call'] = ['time' => $created_time, 'customer_id' => $cid, 'type' => 'Incentive'];
					}
					if (!isset($firstLastCallPerUserForDay[$uid][$incentive_date]['last_call']) || 
						$created_time > $firstLastCallPerUserForDay[$uid][$incentive_date]['last_call']['time']) {
						$firstLastCallPerUserForDay[$uid][$incentive_date]['last_call'] = ['time' => $created_time, 'customer_id' => $cid, 'type' => 'Incentive'];
					}
				}
			}
		}

		// =========================
		// VISITS
		// =========================
		if (!empty($visitEntries)) { //pr($visitEntries);
			foreach ($visitEntries as $year => $visitFrequency) {
				foreach ($visitFrequency as $cve){
					$uid = !empty($cve['cv']['user_id']) ? $cve['cv']['user_id'] : 0 ;
					$cid = !empty($cve['cv']['customer_id']) ? $cve['cv']['customer_id'] : 0 ;
					$did = !empty($cve['cv']['depot_id'])?$cve['cv']['depot_id']:0;
					$vdate = date(DATE_FORMAT_SORT, strtotime( $cve[0]['vdate']));
					$created_time = $cve['0']['first_entry_time'];
					
					if(!empty($cve['cv']['via_app'])){
						// ---- For Frequency Report ----
						if(!$isDatewise){
							if(empty($result[$uid]['call']['ventry'])){
								 $result[$uid]['call']['ventry'] = $cve['0']['ventry'];
							}else{
								$result[$uid]['call']['ventry'] += $cve['0']['ventry'];
							}
							
							if(empty($result[$uid]['call']['customerCalls'][$cid]['ventry'])){
								$result[$uid]['call']['customerCalls'][$cid]['ventry'] = $cve['0']['ventry'];
							}else{
								$result[$uid]['call']['customerCalls'][$cid]['ventry'] += $cve['0']['ventry'];
							}
							
							if(empty($result[$uid]['call']['customersVisited'][$cid])){
								$result[$uid]['call']['customersVisited'][$cid] = array($vdate);
							}else{
								if(!in_array($vdate, $result[$uid]['call']['customersVisited'][$cid])){
									array_push($result[$uid]['call']['customersVisited'][$cid], $vdate);
								}
							}

						}
						//----------------------------------
						
						// ---- For Both Frequency & Monitoring Report ----
						
						//customer activity 
						$activityCall = ['type' => 'visitEntry', 'ventry' => $cve['0']['ventry']];
						if (!isset($customerActivity[$cid]['calls'][$vdate][$uid])) {
							$customerActivity[$cid]['calls'][$vdate][$uid] = [$activityCall];
						} else {
							$customerActivity[$cid]['calls'][$vdate][$uid][] = $activityCall;
						}
						
						
						// --- Track first call per customer/day ---
						if (!in_array($uid, $supervisionRoleUserIds)) {
							if (!isset($firstCallPerCustomer[$cid][$vdate]) || 
								$created_time < $firstCallPerCustomer[$cid][$vdate]['time']) {
								$firstCallPerCustomer[$cid][$vdate] = [
									'time' => $created_time,
									'user_id' => $uid,
									'type' => 'CustomerVisit'
								];
							}
						}
					}
					
					// ---- For Monitoring Report ----
					if($isDatewise){
						
						if(empty($result[$uid]['call']['dailyCustomersVisited'][$vdate])){
							$result[$uid]['call']['dailyCustomersVisited'][$vdate] = array($cid);
						}else{
							if(!in_array($cid, $result[$uid]['call']['dailyCustomersVisited'][$vdate])){ 
								array_push($result[$uid]['call']['dailyCustomersVisited'][$vdate], $cid);
							}
						}
					
						// --- Track first-last call per user/day ---
						if (!isset($firstLastCallPerUserForDay[$uid][$vdate]['first_call']) || 
							$created_time < $firstLastCallPerUserForDay[$uid][$vdate]['first_call']['time']) {
							$firstLastCallPerUserForDay[$uid][$vdate]['first_call'] = ['time' => $created_time, 'customer_id' => $cid, 'type' => 'Sale'];
						}
						if (!isset($firstLastCallPerUserForDay[$uid][$vdate]['last_call']) || 
							$created_time > $firstLastCallPerUserForDay[$uid][$vdate]['last_call']['time']) {
							$firstLastCallPerUserForDay[$uid][$vdate]['last_call'] = ['time' => $created_time, 'customer_id' => $cid, 'type' => 'CustomerVisit'];
						}
					}

				}

			}
		}
		
		$customerAddedBy = array(); //cid=>uid
		
		if(!empty($params['user_id']) && !empty($result[$params['user_id']]['call']['customersVisited'])){
			$uid = $params['user_id']; 
			$cidArr = array_keys($customerActivity);  //pr(count($customerActivity));
			
			$customersData = $this->query("SELECT c.id, c.first_name, c.last_name, c.user_id, r.title FROM customers c LEFT JOIN routes r ON c.route_id = r.id WHERE c.id IN (".implode(', ', $cidArr).")");
			$customers = array();
			foreach ($customersData as $c){
				$customers[$c['c']['id']]['name'] = $c['c']['first_name'].' '.$c['c']['last_name'];
				$customers[$c['c']['id']]['route'] = $c['r']['title'];
				$customers[$c['c']['id']]['user_id'] = $c['c']['user_id'];
				
				$customerAddedBy[$c['c']['id']] = $c['c']['user_id'];
			} 
			$result[$uid]['customers_visited'] = $customers; 

		}else{
			$Customer = ClassRegistry::init('Customer'); 
			$customerAddedBy = $Customer ->find('list', array('fields' => array('id','user_id'), 'conditions' => array('Customer.id' => array_keys($customerActivity))));
		}
			
		return [
			'result' => $result,
			'customerActivity' => $customerActivity,
			//'firstCallPerCustomer' => $firstCallPerCustomer,
			'customerAddedBy' => $customerAddedBy
		]; 
	}
	
	//private function _processCreditDebit(&$result, $customerActivity, $firstCallPerCustomer, $supervisionRoleUserIds) {
	private function _processCreditDebit(&$result, $customerActivity, $customerAddedBy, $supervisionRoleUserIds, $isDatewise) {	

		$User = ClassRegistry::init('User');

		// User names
		$userNames = $User ->find('list', array('fields' => array('id','name')));
		
		//“If two different users make entry on one customer in a day, the entry should be counted as one entry and the entry should be credited to the user who created the customer” - (Updated later to credit the entry to the user who visited first - This is no longer use -- Call credited to the user who created the customer only )
			
		//Know User IDs of Role RM and Above (Supervision Roles) : Currently, the report is generated only for DMs and roles below. Therefore, we do not need to perform debit-credit operations if the customer is visited by users with the role of RM or above.

		// Loop customer activity
		foreach ($customerActivity as $cid => $calls) {

			if (empty($calls['calls'])) continue;


			foreach ($calls['calls'] as $date => $userEntries) {

				$userIds = array_keys($userEntries); // get all user IDs who made entries on this customer on this date

				// Exclude supervision role users
				$userIds = array_diff($userIds, $supervisionRoleUserIds);

				// ❗Skip processing if only one or zero non-supervisory users are left
				if (count($userIds) <= 1) continue;

				//if (empty($firstCallPerCustomer[$cid][$date])) continue;
				if (empty($customerAddedBy[$cid])) continue;

				//$ownerId 	= $firstCallPerCustomer[$cid][$date]['user_id'];
				$ownerId 	= $customerAddedBy[$cid];
				$ownerName 	= !empty($userNames[$ownerId]) ? $userNames[$ownerId] : "";

				// Get users who are NOT the creator of this customer
				$dupUsers = array_diff($userIds, [$ownerId]); 

				// Create debitCalls / creditCalls
				foreach ($dupUsers as $uid) {

					if (empty($customerActivity[$cid]['calls'][$date][$uid])) {
						continue;
					}

					$userName = !empty($userNames[$uid]) ? $userNames[$uid] : "";

					if(isset($result[$ownerId]['customers_visited'][$cid])){ //pr($uid);
						$result[$ownerId]['customers_visited'][$cid]['ownerId'] = $uid;
					}

					// --------------------------
					// Debit / Credit logs
					// --------------------------
					$result['debitCalls'][$uid][] = array(
						'customerId' => $cid,
						'date' => $date,
						'creditedTo' => array(
							'id' => $ownerId,
							'name' => $ownerName
						),
						'callDetails' => $customerActivity[$cid]['calls'][$date][$uid]
					);

					$result['creditCalls'][$ownerId][] = array(
						'customerId' => $cid,
						'date' => $date,
						'debitedFrom' => array(
							'id' => $uid,
							'name' => $userName
						),
						'callDetails' => $customerActivity[$cid]['calls'][$date][$uid]
					);

					// --------------------------
					// Reassign metrics
					// --------------------------
					$customerActivityTypes = [
						'saleEntry',
						'rsSaleEntry',
						'incentiveEntry',
						'ventry'
					];

					foreach ($customerActivity[$cid]['calls'][$date][$uid] as $activity) {

						$activityType = $activity['type'];
						if ($activityType == 'visitEntry') {
							$activityType = 'ventry';
						}

						if (!in_array($activityType, $customerActivityTypes)) {
							continue;
						}

						// get activity call count
						$count = isset($activity[$activityType]) ? $activity[$activityType] : 0;

						// initialize safely (user side)
						if (!isset($result[$uid]['call'][$activityType])) {
							$result[$uid]['call'][$activityType] = 0;
						}

						// initialize safely (owner side)
						if (!isset($result[$ownerId]['call'][$activityType])) {
							$result[$ownerId]['call'][$activityType] = 0;
						}

						// 🔻 remove from user
						$result[$uid]['call'][$activityType] -= $count;

						// 🔺 add to owner
						$result[$ownerId]['call'][$activityType] += $count;
						
						
						// ---- For Frequency Report ----
						if(!$isDatewise){
							// --------------------------
							// For Customer Table
							// --------------------------
							
							// initialize safely (user side)
							if (!isset($result[$uid]['call']['customerCalls'][$cid][$activityType])) {
								$result[$uid]['call']['customerCalls'][$cid][$activityType] = 0;
							}

							// initialize safely (owner side)
							if (!isset($result[$ownerId]['call']['customerCalls'][$cid][$activityType])) {
								$result[$ownerId]['call']['customerCalls'][$cid][$activityType] = 0;
							}

							// 🔻 remove from user
							$result[$uid]['call']['customerCalls'][$cid][$activityType] -= $count;

							// 🔺 add to owner
							$result[$ownerId]['call']['customerCalls'][$cid][$activityType] += $count;
						}
						
						
						
					}


					// --------------------------
					// customersVisited cleanup -- remove customersVisited from other user
					// --------------------------
					if (!empty($result[$uid]['call']['customersVisited'][$cid])) {

						$dateIndex = array_search($date, $result[$uid]['call']['customersVisited'][$cid]);

						if ($dateIndex !== false) {
							unset($result[$uid]['call']['customersVisited'][$cid][$dateIndex]);
							$result[$uid]['call']['customersVisited'][$cid] =
								array_values($result[$uid]['call']['customersVisited'][$cid]);

							if (empty($result[$uid]['call']['customersVisited'][$cid])) {
								unset($result[$uid]['call']['customersVisited'][$cid]);
							}
						}
					}
					

					// --------------------------
					// Add customersVisited to owner
					// --------------------------
					if (!isset($result[$ownerId]['call']['customersVisited'][$cid])) {
						$result[$ownerId]['call']['customersVisited'][$cid] = array($date);
					} else {
						if (!in_array($date, $result[$ownerId]['call']['customersVisited'][$cid])) {
							$result[$ownerId]['call']['customersVisited'][$cid][] = $date;
						}
					}
					
					
					
				}
			}
		}
//pr($result[29]['call']['customersVisited']);


		// ---- For Frequency Report ----
		if(!$isDatewise){
			// --------------------------
			// Debit / Credit logs for Customers
			// --------------------------
			$result['customerTransfers'] = array();

			if (!empty($result['debitCalls'])) {
				foreach ($result['debitCalls'] as $entries) {
					foreach ($entries as $entry) {
						$cid = $entry['customerId'];

						$result['customerTransfers'][$cid]['debit'][] = $entry;
					}
				}
			}

			if (!empty($result['creditCalls'])) {
				foreach ($result['creditCalls'] as $entries) {
					foreach ($entries as $entry) {
						$cid = $entry['customerId'];

						$result['customerTransfers'][$cid]['credit'][] = $entry;
					}
				}
			}
		}
		
		



		return [
			'result' => $result
			//'debitCalls' => $debitCalls,
			//'creditCalls' => $creditCalls
		];
	}
	
	function _mergeCallData($result, $callData)
	{
		foreach ($callData['result'] as $uid => $data) {
			$result[$uid]['call'] = $data;
		}
		return $result;
	}
	
	
	function usersMonitoringReport($params){
		

		// ================================
		// 1. DATE CONDITIONS
		// ================================
		extract($this->_buildDateConditions($params));
		
		$dateParams = $params['dateParams']; 

		// ================================
		// 2. ROUTE PLAN CONDITIONS
		// ================================
		$routePlan  = $this->_buildRoutePlanConditions($params);
		$userRouteCond      = $routePlan['userRouteCond'];
		$rpPeriodByDates    = $routePlan['rpPeriodByDates'];
		$diffRPPeriodDates  = $routePlan['diffRPPeriodDates'];

		// ================================
		// 3. USER FILTERS
		// ================================
		$filters = $this->_buildUserFilters(isset($params['query']) ? $params['query'] : []);
		extract($filters);

		// ================================
		// 4. FETCH USERS
		// ================================
		$usersData  = $this->_fetchFreqReportUsers($filters, $params);

		$users     = $usersData['users'];
		$user_ids  = $usersData['user_ids'];
		$DH_uids   = $usersData['DH_uids'];
		$DH_depotwise = $usersData['DH_depotwise'];

		$output['users'] = $users;
		$result['DH_depotwise'] = $DH_depotwise;

		// ================================
		// 5. USER ROUTES
		// ================================
		$userRoutes = $this->query("
			SELECT ur.route_ids, ur.user_id, ur.year, ur.month, ur.week, ur.day 
			FROM user_routes ur 
			WHERE ur.user_id IN (".implode(',', $user_ids).") $userRouteCond
		");
		
		
		// ================================
		// 6. Initialized structured routes + ROUTE IDS + NAMES
		// ================================
		$routeData = $this->_processUserRoutes($userRoutes); //buildStructuredRoutes

		$structuredUserRoutes 		= $routeData['structuredUserRoutes']; // Initialized structured routes -- [uid][year][month][week][day] = structured array
		$route_ids            		= $routeData['route_ids'];
		$user_route_ids       		= $routeData['user_route_ids'];
		$result['userRouteNames'] 	= $routeData['userRouteNames'];


		// ================================
		// 7. ROUTE CUSTOMER COUNTS
		// ================================
		$routeCustCounts = $this->_getRouteCustomerCounts($route_ids, $d1, $d2, $ccC); //fetchRouteCustomerCounts

		// ================================
		// 8. EXPECTED FREQUENCY
		// ================================
		// STEP 1
		$structuredUserRoutes = $this->_populateStructuredRoutes(
			$structuredUserRoutes, $routeCustCounts, $DH_uids,
			$d1, $d2, $params, $dateParams, $diffRPPeriodDates, $rpPeriodByDates
		);

		// STEP 2
		$exFreqResult = $this->_buildExpectedFrequency(
			$structuredUserRoutes,
			$d1, $d2, $params, $dateParams, $diffRPPeriodDates, $rpPeriodByDates
		);

		// merge into main result
		foreach ($exFreqResult as $uid => $data) {
			if (!isset($result[$uid])) {
				$result[$uid] = array();
			}
			$result[$uid] = array_merge($result[$uid], $data);
		}

		// ================================
		// 10. CALL ACTIVITY (UNCHANGED LOGIC)
		// ================================
		
		
		$odpC = $fidpC = $rddpC = $indpC = $cvdpC = "";
		// Only build conditions if depot_ids is not empty and not just [0]
		if (!empty($depot_ids) && !(count($depot_ids) === 1 && $depot_ids[0] == 0)) {
			$odpC = " AND sl.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$fidpC = " AND fi.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$rddpC = " AND rsi.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$indpC = " AND inc.depot_id IN (" . implode(', ', $depot_ids) . ")";
			$cvdpC = " AND cv.depot_id IN (" . implode(', ', $depot_ids) . ")";
		}

		$callConds = [
			'oC' => $oC,
			'fiC' => $fiC,
			'rdC' => $rdC,
			'inC' => $inC,
			'cvC' => $cvC,
			'ccC' => $ccC,
			'vcC'  => $vcC,
			'cnameC' => " AND NOT (c.first_name IS NULL) AND NOT (c.last_name IS NULL)",

			'odpC' => $odpC,
			'fidpC' => $fidpC,
			'rddpC' => $rddpC,
			'indpC' => $indpC,
			'cvdpC' => $cvdpC,
		];
		
		//“If two different users make entry on one customer in a day, the entry should be counted as one entry and the entry should be credited to the user who created the customer” - Updated later to credit the entry to the user who visited first
			
		//Know User IDs of Role RM and Above (Supervision Roles) : Currently, the report is generated only for DMs and roles below. Therefore, we do not need to perform debit-credit operations if the customer is visited by users with the role of RM or above.

		// Supervision roles (RM and above)
		
		$User = ClassRegistry::init('User');
		$supervisionRoleUserIds = $User->find('list', array('fields' => array('User.id'), 'joins' => array(array('table' => 'roles', 'alias' => 'Role', 'type' => 'INNER', 'conditions' => array('User.role_id = Role.id', 'Role.grade <=' => RM)))));  //pr(count($supervisionRoleUserIds));


		$callData = $this->_processCallActivities($result, $params, $user_ids, $depot_ids, $callConds, $supervisionRoleUserIds); 
		 
		$customerActivity = $callData['customerActivity'];
		$firstCallPerCustomer = $callData['firstCallPerCustomer'];
		$customerAddedBy = $callData['customerAddedBy'];
		
		
		//$this->_processCreditDebit($result, $customerActivity, $firstCallPerCustomer, $supervisionRoleUserIds);
		$isDatewise = !empty($params['datewise_monitoring']);
		$this->_processCreditDebit($result, $customerActivity, $customerAddedBy, $supervisionRoleUserIds, $isDatewise);
		

		$output['result'] = $result;

		return $output;
	}
	

}
