<?php

namespace app\models;

use DateTime;
use Yii;
use yii\db\Expression;

class Common extends \yii\db\ActiveRecord
{
    public $role = array('1' => 'Team Lead', '2' => 'Manager', '3' => 'Executive');
    public $customer_type = array('1' => 'Hot', '2' => 'Warm', '3' => 'Cold');
    public $lead_status = array('1' => 'Active', '2' => 'InActive');
    public $tag_status = array('0' => 'In Progress', '1' => 'Visited', '2' => 'Not Visited', '3' => 'Clashed', '4' => 'Booked', '5' => 'Lead Dead', '6' => 'Registered', '7' => 'Lead Rejected');

    public $status = array('1' => 'Active', '2' => 'Pending', '0' => 'InActive');
    public $cp_company_type = array('1' => 'Sole Proprietorship', '2' => 'Partnership', '3' => 'Private Limited', '4' => 'Public Limited', '5' => 'Individual');
    public $cp_nature_business = array('1' => 'Residential Sales', '2' => 'Commercial Sales', '3' => 'Land sourcing for Developers', '4' => 'Agricultural Land Sales', '5' => 'Industrial Sales', '6' => 'Project Consultancy');
    public $project_status = array('1' => 'Completed', '2' => 'Ongoing', '3' => 'Launching');
    public $project_segment = array('1' => 'Affordable', '2' => 'Luxury', '3' => 'Ultra Luxury', '4' => 'Value');
    public $project_type = array('1' => 'New Project', '2' => 'Exclusive Project', '3' => 'Trending Project', '4' => 'Ready to move Project', '5' => 'Under construction Project', '6' => 'Upcoming Project');
    public $flat_type_id = array('1' => '1 BHK', '2' => '1.5 BHK', '3' => '2 BHK', '4' => '3 BHK', '5' => '4 BHK', '6' => '-');
    public $flat_property_type = array('1' => 'Flat', '2' => 'Office Space', '3' => 'Shop');
    public $tagging_done = array('0' => 'False', '1' => 'True');
    public $month = array('1' => 'January', '2' => 'February', '3' => 'March', '4' => 'April', '5' => 'May', '6' => 'June', '7' => 'July', '8' => 'August', '9' => 'September', '10' => 'October', '11' => 'November', '12' => 'December');

    public $ticket_issue_type = array(1 => 'CP Registration', 2 => 'Login', 3 => 'Profile Changes', 4 => 'Leads', 5 => 'Tagging', 6 => 'Others');
    public $ticket_status = array(1 => 'Received', 2 => 'In Progress', 3 => 'Resolved');


    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'snse_admin';
    }

    public function getloggeduser($smcp_obj)
    {
        $loggedUser = null;
        if (!empty($smcp_obj)) {
            $loggedUser['sm_cp_id'] = $smcp_obj->sm_cp_id;
            if (!empty($smcp_obj->channelpartner_id)) {
                $loggedUser['channelpartner_id'] = $smcp_obj->channelpartner_id;
                $loggedUser['user_type'] = '1';
                $loggedUser['builder_id'] = null;
            }
            if (!empty($smcp_obj->builder_id)) {
                $loggedUser['builder_id'] = $smcp_obj->builder_id;

                if ($smcp_obj->staff_type == 1) {
                    $loggedUser['user_type'] = '2';
                } else {
                    $loggedUser['user_type'] = '3';
                }

                $loggedUser['channelpartner_id'] = null;
            }
            $loggedUser['name'] = $smcp_obj->name;
            $loggedUser['email'] = $smcp_obj->email;
            $loggedUser['contact'] = $smcp_obj->contact;

            $loggedUser['role'] = $this->role[$smcp_obj->role];

            $loggedUser['status'] = $this->status[$smcp_obj->status];
            $loggedUser['created_on'] = $smcp_obj->created_on;
            $loggedUser['modified_on'] = $smcp_obj->modified_on;
        }
        return $loggedUser;
    }

    public function getmanagers($smcp_obj)
    {
        $members = null;
        if (!empty($smcp_obj) && $smcp_obj->role == 1) {
            $members['team_lead']['sm_cp_id'] = $smcp_obj->sm_cp_id;
            $members['team_lead']['name'] = $smcp_obj->name;
            $smData = (new \yii\db\Query())
                ->select('sm_cp1.sm_cp_id,sm_cp1.name')
                ->from('sm_cp sm_cp1')
                ->where('sm_cp1.parent_id="' . $smcp_obj->sm_cp_id . '" AND sm_cp1.status=1 AND sm_cp1.role=2 AND sm_cp1.is_deleted=0 ')->createCommand()
                ->queryAll();
            if (!empty($smData)) {
                $count = 0;
                foreach ($smData as $smData_k => $smData_v) {
                    $members['managers'][$count] = $smData_v;
                    $count++;
                }
            } else {
                $members['managers'] = null;
            }
        }
        return $members;
    }




    public function getcp($cp_id)
    {
        $Channelpartner = null;
        $cp_data = Channelpartner::find()->select('id,name,email_id,rera_number,pan_number,contact,company_name,address,location_id,company_type,gstin,nature_business,website,status,created_on,modified_on')->where(['id' => $cp_id])->one();
        if (!empty($cp_data)) {

            $location_arr = Location::findAll([
                'status' => 1
            ]);
            foreach ($location_arr as $location_arr_val) {
                $locations[$location_arr_val->id] = $location_arr_val->name;
            }
            $Channelpartner = $cp_data->toArray();

            if (!empty($Channelpartner['location_id'])) {
                $loc_seperated = $Channelpartner['location_id'];
                $Channelpartner['location_ids'] = $loc_seperated;
                $get_loc_set = explode(",", $Channelpartner['location_id']);
                $loc_final_val = '';
                foreach ($get_loc_set as $get_loc_set_val) {
                    if (empty($loc_final_val)) {
                        $loc_final_val = $locations[$get_loc_set_val];
                    } else {
                        $loc_final_val .= ", " . $locations[$get_loc_set_val];
                    }
                }
                $Channelpartner['location_id'] = $loc_final_val;
            } else {
                $Channelpartner['location_id'] = null;
                $Channelpartner['location_ids'] = null;
            }
            if (!empty($Channelpartner['company_type'])) {
                $Channelpartner['company_type'] = $this->cp_company_type[$Channelpartner['company_type']];
            }
            if (!empty($Channelpartner['nature_business'])) {
                $Channelpartner['nature_business'] = $this->cp_nature_business[$Channelpartner['nature_business']];
            }
            $Channelpartner['status'] = $this->status[$Channelpartner['status']];
        }
        return $Channelpartner;
    }

    public function getbuilder($builder_id)
    {
        $builder = null;
        $builder_data = Builder::find()->select('id,name,email,address,mobile_no,status,created_on,modified_on')->where(['id' => $builder_id])->one();
        if (!empty($builder_data)) {

            $builder = $builder_data->toArray();
            $builder['status'] = $this->status[$builder['status']];
        }
        return $builder;
    }

    public function getmembersapiold($sm_cp_id)
    {
        $members = null;
        $sm_cp_data = SmCp::find()->where(['sm_cp_id' => $sm_cp_id])->one();
        if (!empty($sm_cp_data)) {
            if ($sm_cp_data->status == 1 || $sm_cp_data->status == 2) {

                if ($sm_cp_data->status == 1) {
                    $smData = (new \yii\db\Query())
                        ->select('sm_cp1.sm_cp_id,sm_cp1.name,sm_cp1.email,sm_cp1.contact,sm_cp1.role,sm_cp1.parent_id,sm_cp1.status,sm_cp1.created_on,sm_cp1.modified_on')
                        ->from('sm_cp sm_cp1')
                        ->leftJoin('sm_cp sm_cp2', 'sm_cp1.parent_id=sm_cp2.sm_cp_id')
                        ->leftJoin('sm_cp sm_cp3', 'sm_cp2.parent_id=sm_cp3.sm_cp_id')
                        ->where('((' . $sm_cp_id . ' in (sm_cp1.parent_id,sm_cp2.parent_id, sm_cp3.parent_id)) AND sm_cp1.sm_cp_id!=' . $sm_cp_id . ')')->createCommand()
                        ->queryAll();
                    if (!empty($smData)) {
                        $count = 0;
                        foreach ($smData as $smData_k => $smData_v) {
                            $members[$count] = $smData_v;
                            $members[$count]['role'] = $this->role[$smData_v['role']];
                            $get_parent = $this->getparentapi($smData_v['parent_id']);
                            $members[$count]['parent_id'] = ($get_parent) ? $get_parent->name : '';
                            $members[$count]['status'] = $this->status[$smData_v['status']];
                            $count++;
                        }
                    }
                } elseif ($sm_cp_data->status == 2) {
                    $smData = (new \yii\db\Query())
                        ->select('sm_cp1.sm_cp_id,sm_cp1.name,sm_cp1.email,sm_cp1.contact,sm_cp1.role,sm_cp1.parent_id,sm_cp1.status,sm_cp1.created_on,sm_cp1.modified_on')
                        ->from('sm_cp sm_cp1')
                        ->leftJoin('sm_cp sm_cp2', 'sm_cp1.parent_id=sm_cp2.sm_cp_id')
                        ->where('((' . $sm_cp_id . ' in (sm_cp1.parent_id,sm_cp2.parent_id)) AND sm_cp1.sm_cp_id!=' . $sm_cp_id . ')')->createCommand()
                        ->queryAll();
                    if (!empty($smData)) {
                        $count = 0;
                        foreach ($smData as $smData_k => $smData_v) {
                            $members[$count] = $smData_v;
                            $members[$count]['role'] = $this->role[$smData_v['role']];
                            $get_parent = $this->getparentapi($smData_v['parent_id']);
                            $members[$count]['parent_id'] = ($get_parent) ? $get_parent->name : '';
                            $members[$count]['status'] = $this->status[$smData_v['status']];
                            $count++;
                        }
                    }
                }
            }
        }
        return $members;
    }

    public function getteamunderapi($sm_cp_id)
    {
        $members = null;
        $sm_cp_data = SmCp::find()->where(['sm_cp_id' => $sm_cp_id, 'is_deleted' => 0])->one();
        if (!empty($sm_cp_data)) {
            $smData = (new \yii\db\Query())
                ->select('sm_cp1.sm_cp_id,sm_cp1.name,sm_cp1.email,sm_cp1.contact,sm_cp1.role,sm_cp1.parent_id,sm_cp1.status,sm_cp1.created_on,sm_cp1.modified_on,sm_cp1.builder_id,sm_cp1.channelpartner_id,sm_cp1.staff_type')
                ->from('sm_cp sm_cp1')
                ->where('sm_cp1.parent_id="' . $sm_cp_id . '" AND sm_cp1.is_deleted=0 ')->createCommand()
                ->queryAll();
            if (!empty($smData)) {
                $count = 0;
                foreach ($smData as $smData_k => $smData_v) {
                    $members[$count] = $smData_v;
                    $members[$count]['role'] = $this->role[$smData_v['role']];
                    $members[$count]['roleId'] = $smData_v['role'];
                    $get_parent = $this->getparentapi($smData_v['parent_id']);
                    $members[$count]['parent_id'] = $smData_v['parent_id'];
                    $members[$count]['parent_id_name'] = ($get_parent) ? $get_parent->name : '';
                    $members[$count]['status'] = $this->status[$smData_v['status']];
                    if (!empty($smData_v['builder_id'])) {
                        if ($smData_v['staff_type'] == 1) {
                            $members[$count]['user_type'] = '2';
                        } else {
                            $members[$count]['user_type'] = '3';
                        }
                    }
                    if (!empty($smData_v['channelpartner_id'])) {
                        $members[$count]['user_type'] = '1';
                    }
                    if ($smData_v['role'] == 2) {
                        $members[$count]['executiveList'] = $this->getteamunderapi($smData_v['sm_cp_id']);
                    }
                    //get list of each executive under manager
                    $count++;
                }
            }
        }
        return $members;
    }

    public function getmembersapi($sm_cp_id)
    {
        $members = null;
        $sm_cp_data = SmCp::find()->where(['sm_cp_id' => $sm_cp_id, 'is_deleted' => 0])->one();
        if (!empty($sm_cp_data)) {
            if ($sm_cp_data->role == 1 || $sm_cp_data->role == 2) {
                if ($sm_cp_data->role == 1) {
                    $members['managersList'] = $this->getteamunderapi($sm_cp_id);
                } elseif ($sm_cp_data->role == 2) {
                    $members['executiveList'] = $this->getteamunderapi($sm_cp_id);
                }
            }
        }
        return $members;
    }

    public function getsinglesmcpapi($sm_cp_id)
    {
        $member = null;

        $smData = (new \yii\db\Query())
            ->select('sm_cp1.sm_cp_id,sm_cp1.name,sm_cp1.email,sm_cp1.contact,sm_cp1.role,sm_cp1.parent_id,sm_cp1.status,sm_cp1.created_on,sm_cp1.modified_on,sm_cp1.builder_id,sm_cp1.channelpartner_id,sm_cp1.staff_type')
            ->from('sm_cp sm_cp1')
            ->where(' sm_cp1.sm_cp_id="' . $sm_cp_id . '" AND sm_cp1.is_deleted=0')->createCommand()
            ->queryAll();
        if (!empty($smData)) {
            $member = $smData[0];
            $member['role'] = $this->role[$member['role']];
            $get_parent = $this->getparentapi($member['parent_id']);
            $member['parent_id'] = $member['parent_id'];
            $member['parent_id_name'] = ($get_parent) ? $get_parent->name : '';
            $member['status'] = $this->status[$member['status']];
            if (!empty($member['builder_id'])) {
                if ($member['staff_type'] == 1) {
                    $member['user_type'] = '2';
                } else {
                    $member['user_type'] = '3';
                }
            }
            if (!empty($member['channelpartner_id'])) {
                $member['user_type'] = '1';
            }
        }
        return $member;
    }

    public function getleader($sm_cp_id)
    {
        $get_leader = array();
        $sm_cp_data = SmCp::find()->where(['sm_cp_id' => $sm_cp_id, 'is_deleted' => 0])->one();
        if (!empty($sm_cp_data)) {
            if ($sm_cp_data->role == 1) {
                $get_leader = $sm_cp_data;
            } else {
                if (!empty($sm_cp_data->builder_id)) {
                    $get_leader = SmCp::find()->where(['builder_id' => $sm_cp_data->builder_id, 'is_deleted' => 0, 'role' => 1])->one();
                } else {
                    $get_leader = SmCp::find()->where(['channelpartner_id' => $sm_cp_data->channelpartner_id, 'is_deleted' => 0, 'role' => 1])->one();
                }
            }
        }
        return $get_leader;
    }

    public function getaccessmembers($sm_cp_id)
    {
        $members = null;
        $sm_cp_data = SmCp::find()->where(['sm_cp_id' => $sm_cp_id, 'is_deleted' => 0])->one();
        if (!empty($sm_cp_data)) {
            if ($sm_cp_data->role == 1 || $sm_cp_data->role == 2) {

                if ($sm_cp_data->role == 1) {
                    $smData = (new \yii\db\Query())
                        ->select('sm_cp1.sm_cp_id')
                        ->from('sm_cp sm_cp1')
                        ->leftJoin('sm_cp sm_cp2', 'sm_cp1.parent_id=sm_cp2.sm_cp_id AND sm_cp2.is_deleted=0')
                        ->leftJoin('sm_cp sm_cp3', 'sm_cp2.parent_id=sm_cp3.sm_cp_id AND sm_cp3.is_deleted=0')
                        ->where('((' . $sm_cp_id . ' in (sm_cp1.parent_id,sm_cp2.parent_id, sm_cp3.parent_id)) AND sm_cp1.sm_cp_id!=' . $sm_cp_id . ') AND sm_cp1.is_deleted=0')->createCommand()
                        ->queryAll();
                    if (!empty($smData)) {
                        $count = 0;
                        foreach ($smData as $smData_k => $smData_v) {
                            $members[] = $smData_v['sm_cp_id'];
                        }
                    }
                } elseif ($sm_cp_data->role == 2) {
                    $smData = (new \yii\db\Query())
                        ->select('sm_cp1.sm_cp_id')
                        ->from('sm_cp sm_cp1')
                        ->leftJoin('sm_cp sm_cp2', 'sm_cp1.parent_id=sm_cp2.sm_cp_id AND sm_cp2.is_deleted=0')
                        ->where('((' . $sm_cp_id . ' in (sm_cp1.parent_id,sm_cp2.parent_id)) AND sm_cp1.sm_cp_id!=' . $sm_cp_id . ') AND sm_cp1.is_deleted=0')->createCommand()
                        ->queryAll();
                    if (!empty($smData)) {
                        $count = 0;
                        foreach ($smData as $smData_k => $smData_v) {
                            $members[] = $smData_v['sm_cp_id'];
                        }
                    }
                }
            }
        }
        return $members;
    }

    public function getaccessmemberswithname($sm_cp_id)
    {
        $members = null;
        $sm_cp_data = SmCp::find()->where(['sm_cp_id' => $sm_cp_id, 'is_deleted' => 0])->one();
        if (!empty($sm_cp_data)) {
            $members[0]['sm_cp_id'] = $sm_cp_id;
            $members[0]['name'] = $sm_cp_data->name;
            if ($sm_cp_data->role == 1 || $sm_cp_data->role == 2) {

                if ($sm_cp_data->role == 1) {
                    $smData = (new \yii\db\Query())
                        ->select('sm_cp1.sm_cp_id,sm_cp1.name')
                        ->from('sm_cp sm_cp1')
                        ->leftJoin('sm_cp sm_cp2', 'sm_cp1.parent_id=sm_cp2.sm_cp_id AND sm_cp2.is_deleted=0')
                        ->leftJoin('sm_cp sm_cp3', 'sm_cp2.parent_id=sm_cp3.sm_cp_id AND sm_cp3.is_deleted=0')
                        ->where('((' . $sm_cp_id . ' in (sm_cp1.parent_id,sm_cp2.parent_id, sm_cp3.parent_id)) AND sm_cp1.sm_cp_id!=' . $sm_cp_id . ') AND sm_cp1.is_deleted=0')->createCommand()
                        ->queryAll();
                    if (!empty($smData)) {
                        $count = 1;
                        foreach ($smData as $smData_k => $smData_v) {
                            $members[$count]['sm_cp_id'] = $smData_v['sm_cp_id'];
                            $members[$count]['name'] = $smData_v['name'];
                            $count++;
                        }
                    }
                } elseif ($sm_cp_data->role == 2) {
                    $smData = (new \yii\db\Query())
                        ->select('sm_cp1.sm_cp_id')
                        ->from('sm_cp sm_cp1')
                        ->leftJoin('sm_cp sm_cp2', 'sm_cp1.parent_id=sm_cp2.sm_cp_id AND sm_cp2.is_deleted=0')
                        ->where('((' . $sm_cp_id . ' in (sm_cp1.parent_id,sm_cp2.parent_id)) AND sm_cp1.sm_cp_id!=' . $sm_cp_id . ') AND sm_cp1.is_deleted=0')->createCommand()
                        ->queryAll();
                    if (!empty($smData)) {
                        $count = 1;
                        foreach ($smData as $smData_k => $smData_v) {
                            $members[$count]['sm_cp_id'] = $smData_v['sm_cp_id'];
                            $members[$count]['name'] = $smData_v['name'];
                            $count++;
                        }
                    }
                }
            }

            /* $members[$count + 1]['sm_cp_id'] = $sm_cp_id;
            $members[$count + 1]['name'] = $sm_cp_data->name; */
        }
        return $members;
    }


    public function getnotification($sm_cp_id, $querydata)
    {
        $notification_arr = null;
        $notification = null;

        if (!empty($querydata)) {

            $notify_status = (!empty($querydata['status']) ? trim($querydata['status']) : '');

            $notify_start_date = (!empty($querydata['start_date']) ? trim($querydata['start_date']) : '');
            $notify_end_date = (!empty($querydata['end_date']) ? trim($querydata['end_date']) : '');
        }

        $order_name = (isset($querydata['sort_name']) ? trim($querydata['sort_name']) : 'notification_list.id');
        $order_type = (isset($querydata['sort_type']) ? trim($querydata['sort_type']) : 'DESC');


        $page_count = (isset($querydata['page_count']) ? trim($querydata['page_count']) : 25);
        $page = (isset($querydata['page']) ? trim($querydata['page']) : 1);
        if ($page == 1) {
            $offset = 0;
        } else {
            $offset = (($page - 1) * $page_count);
        }

        $where_sql = 'notification_list.status NOT IN(1) AND notification_list.success=1 AND notification_list.sm_cp_id="' . $sm_cp_id . '" ';
        if (!empty($notify_status)) {
            $where_sql .= ' AND notification_list.status IN(' . $notify_status . ')';
        }

        if (!empty($notify_start_date)) {
            $where_sql .= ' AND notification_list.modified_on>="' . $notify_start_date . '"';
        }
        if (!empty($notify_end_date)) {
            $where_sql .= ' AND notification_list.modified_on<="' . $notify_end_date . '"';
        }

        $sort_text = $order_name . ' ' . $order_type;


        $notify_query = (new \yii\db\Query())
            ->select('notification_list.id,notification_list.title,notification_list.message,notification_list.link,notification_list.modified_on,notification_list.status,notification_list.read_on')
            ->from('notification_list')
            ->where($where_sql)
            ->orderBy($sort_text);
        $notify_count = $notify_query->count();

        $notify_data = $notify_query->limit($page_count)->offset($offset)->createCommand()->queryAll();

        if (!empty($notify_data)) {

            foreach ($notify_data as $notify_data_key => $notify_data_val) {

                $notification[$notify_data_key] = $notify_data_val;

                $notification[$notify_data_key]['received_on'] = null;

                if ($notify_data_val['status'] == 2) {
                    $notification[$notify_data_key]['statusText'] = 'Received';
                    $notification[$notify_data_key]['received_on'] = $notify_data_val['modified_on'];
                    $notification[$notify_data_key]['read_on'] = null;
                } else if ($notify_data_val['status'] == 3) {
                    $notification[$notify_data_key]['statusText'] = 'Read';
                    $notification[$notify_data_key]['received_on'] = $notify_data_val['modified_on'];
                    $notification[$notify_data_key]['read_on'] = $notify_data_val['read_on'];
                }
            }
        }

        //pagination code start
        $pgdata['page'] = $page;
        //$pgdata['content_count'] = $proj_count * 5;     //added for testing
        $pgdata['content_count'] = $notify_count;
        $pgdata['page_count'] = $page_count;
        $pagination = $this->getpagination($pgdata);
        //pagination code end

        $notification_arr['notification'] = $notification;
        $notification_arr['pagination'] = $pagination;

        return $notification_arr;
    }

    /* public function getnotification($sm_cp_id)
    {
        $notification = null;
        $notify_arr = (new \yii\db\Query())
            ->select('nl.sm_cp_id,nl.title,nl.message,nl.link,nl.modified_on,nl.status,nl.read_on')
            ->from('notification_list nl')
            ->where('status IN(2,3) AND success=1 AND sm_cp_id="' . $sm_cp_id . '"')->createCommand()
            ->queryAll();
        if (!empty($notify_arr)) {
            $count = 1;
            foreach ($notify_arr as $notify_arr_k => $notify_arr_v) {
                $notification[$count]['title'] = $notify_arr_v['title'];
                $notification[$count]['message'] = $notify_arr_v['message'];
                $notification[$count]['link'] = $notify_arr_v['link'];
                $notification[$count]['received_on'] = null;
                $get_status = '';
                if ($notify_arr_v['status'] == 2) {
                    $notification[$count]['status'] = $notify_arr_v['status'];
                    $notification[$count]['statusText'] = 'Received';
                    $notification[$count]['received_on'] = $notify_arr_v['modified_on'];
                    $notification[$count]['read_on'] = null;
                } else if ($notify_arr_v['status'] == 3) {
                    $notification[$count]['status'] = $notify_arr_v['status'];
                    $notification[$count]['statusText'] = 'Read';
                    $notification[$count]['received_on'] = $notify_arr_v['modified_on'];
                    $notification[$count]['read_on'] = $notify_arr_v['read_on'];
                }
                $count++;
            }
        }

        return $notification;
    } */

    public function getparentapi($sm_cp_id)
    {
        if (!empty($sm_cp_id)) {
            $sm_cp_data = SmCp::find()->where(['sm_cp_id' => $sm_cp_id, 'is_deleted' => 0])->one();
            return $sm_cp_data;
        }
        return false;
    }

    public function getsmofcp($cp_id)
    {
        $sm_arr = null;
        if (!empty($cp_id)) {
            $smcp_arr = SmCpNetwork::findAll([
                'status' => 1,
                'channelpartner_id' => $cp_id
            ]);
            if (!empty($smcp_arr)) {
                foreach ($smcp_arr as $smcp_arr_val) {
                    $sm_arr[] = $smcp_arr_val->sm_cp_id;
                }
            }
        }
        return $sm_arr;
    }

    public function getbuilderofcp($cp_id)
    {
        $builder_arr = null;
        $get_sm = $this->getsmofcp($cp_id);
        if (!empty($get_sm)) {
            $get_sm_txt = implode(",", $get_sm);
            $getbuilder = SmCp::findAll(array('sm_cp_id' => $get_sm, 'is_deleted' => 0));
            if (!empty($getbuilder)) {
                foreach ($getbuilder as $getbuilder_val) {
                    $builder_arr[] = $getbuilder_val->builder_id;
                }
            }
        }
        return $builder_arr;
    }

    public function getbookmarkprojects($sm_cp_id)
    {
        $proj = null;
        $getbookmark = SmCpBookmark::findAll([
            'sm_cp_id' => $sm_cp_id,
        ]);
        if (!empty($getbookmark)) {
            foreach ($getbookmark as $getbookmark_val) {
                $proj[] = $getbookmark_val->projects_id;
            }
        }
        return $proj;
    }

    public function getsmofproject($project_id)
    {
        //get sourcing
        $sourcingData = (new \yii\db\Query())
            ->select('sm.sm_cp_id')
            ->from('sm_projects sp')
            ->leftJoin("sm_cp as sm", 'sp.sm_cp_id = sm.sm_cp_id')
            ->where('FIND_IN_SET("' . (int) $project_id . '",projects_id) AND sp.status=1 AND sm.is_deleted=0')->groupBy('sp.sm_cp_id')->createCommand()
            ->queryAll();
        $sourcing = null;
        if (!empty($sourcingData)) {
            $s_count = 0;
            foreach ($sourcingData as $sourcingData_val) {
                $sourcing[$s_count] = $sourcingData_val['sm_cp_id'];
                $s_count++;
            }
        }
        return $sourcing;
    }

    public function getprojofmultism($sm_arr)
    {
        $proj_arr = null;
        if (!empty($sm_arr)) {
            $smcp_arr = SmProjects::findAll([
                'status' => 1,
                'sm_cp_id' => $sm_arr
            ]);
            $proj_txt = '';
            foreach ($smcp_arr as $smcp_arr_val) {
                if ($proj_txt == '') {
                    $proj_txt = $smcp_arr_val->projects_id;
                } else {
                    $proj_txt .= "," . $smcp_arr_val->projects_id;
                }
                /* $temp_arr = explode(",", $proj_arr_val->projects_id);
                array_push($proj_arr, $temp_arr); */
            }
            if (!empty($proj_txt)) {
                $proj_arr = array_unique(explode(",", $proj_txt));
            }
        }
        return $proj_arr;
    }

    public function checkcpprojaccess($cp_id, $id)
    {
        $access = false;
        $get_sm = $this->getsmofcp($cp_id);
        if (!empty($get_sm)) {
            $get_proj = $this->getprojofmultism($get_sm);
            if (!empty($get_proj)) {
                if (in_array($id, $get_proj)) {
                    $access = true;
                }
            }
        }
        return $access;
    }

    public function checkcpprojaccessbysm($sm_cp_id, $id)
    {
        $access = false;
        $get_sm[0] = $sm_cp_id;
        if (!empty($get_sm)) {
            $get_proj = $this->getprojofmultism($get_sm);
            if (!empty($get_proj)) {
                if (in_array($id, $get_proj)) {
                    $access = true;
                }
            }
        }
        return $access;
    }

    public function checkcpleadaccess($sm_cp_id, $id)
    {
        $access = false;
        $get_members = $this->getaccessmembers($sm_cp_id);
        $get_members[] = $sm_cp_id;
        $get_lead_data = Leadmaster::find()->where(['id' => $id, 'is_deleted' => 0])->one();
        if (!empty($get_lead_data)) {
            $created_by = $get_lead_data->created_by;
            if (in_array($created_by, $get_members)) {
                $access = true;
            }
        }

        return $access;
    }

    public function checkcptagaccess($sm_cp_id, $id, $type = "cp")
    {
        $access = false;
        $get_members = $this->getaccessmembers($sm_cp_id);
        $get_members[] = $sm_cp_id;
        $get_tag_data = Taggingmaster::find()->where(['id' => $id, 'is_deleted' => 0])->one();
        if (!empty($get_tag_data)) {
            if ($type == 'cp') {
                $created_by = $get_tag_data->created_by;
            } else {
                $created_by = $get_tag_data->sm_cp_id;
            }
            if (in_array($created_by, $get_members)) {
                $access = true;
            }
        }

        return $access;
    }

    public function getamenities()
    {
        $amenities_arr = null;
        $amenitiesData = (new \yii\db\Query())
            ->select('am.id,am.name,am.icon')
            ->from('amenities am')
            ->createCommand()
            ->queryAll();
        $amenities = null;
        if (!empty($amenitiesData)) {
            foreach ($amenitiesData as $amenitiesData_key => $amenitiesData_val) {
                $amenities[$amenitiesData_key] = $amenitiesData_val;
                if (!empty($amenitiesData_val['icon'])) {
                    $amenities[$amenitiesData_key]['icon'] = \Yii::$app->params['upload_amenities_path'] . $amenitiesData_val['icon'];
                }
            }
        }
        $amenities_arr['amenities'] = $amenities;
        return $amenities_arr;
    }

    public function getguidelines()
    {
        $guidelines_arr = null;
        $guideData = (new \yii\db\Query())
            ->select('am.id,am.name,am.filename')
            ->from('guidelinesmaster am')
            ->createCommand()
            ->queryAll();
        $guide = null;
        if (!empty($guideData)) {
            foreach ($guideData as $guideData_key => $guideData_val) {
                $guide[$guideData_key] = $guideData_val;
                if (!empty($guideData_val['filename'])) {
                    $guide[$guideData_key]['filename'] = \Yii::$app->params['upload_guidelines_path'] . $guideData_val['filename'];
                }
            }
        }
        $guidelines_arr['guidelines'] = $guide;
        return $guidelines_arr;
    }

    public function getprojectlistapi($get_user, $querydata, $list_type = '')
    {
        $cp_id = $get_user->channelpartner_id;
        $builder_id = $get_user->builder_id;
        $get_sm_cp_id = $get_user->sm_cp_id;

        $cp_location = '';
        if (!empty($cp_id)) {
            $cp_data = Channelpartner::find()->where(['id' => $cp_id])->one();
            if (!empty($cp_data)) {
                $cp_location = $cp_data->location_id;
            }
        }

        $sm_cp_id = $get_user->sm_cp_id;
        $project_arr = null;
        if (empty($list_type)) {
            $pagination = null;
        }
        $project = null;
        $show_project = true;
        /* echo "<pre>";
        print_r($querydata);
        exit; */
        $get_sm = [];
        if (!empty($cp_id)) {
            $get_sm = $this->getsmofcp($cp_id);
            if (empty($get_sm)) {
                $show_project = false;
            }
        }
        if (!empty($builder_id)) {
            $get_sm[] = $get_sm_cp_id;
        }
        /* echo "<pre>";
        print_r($get_sm);
        exit; */



        if ($show_project) {
            $get_proj = [];
            if (!empty($get_sm)) {
                $get_proj = $this->getprojofmultism($get_sm);
            }
            /* echo "<pre>";
            print_r($get_proj);
            exit; */
            //if (!empty($get_proj)) {
            //pending from here
            $get_proj_txt = '-1';
            if (!empty($get_proj)) {
                $get_proj_txt = implode(",", $get_proj);
            }
            if (!empty($querydata)) {

                $proj_name = (!empty($querydata['name']) ? trim($querydata['name']) : '');
                $proj_type = (!empty($querydata['type']) ? trim($querydata['type']) : '');
                if (empty($builder_id)) {
                    $proj_builder_id = (!empty($querydata['builder_id']) ? trim($querydata['builder_id']) : '');
                } else {
                    $proj_builder_id = $builder_id;
                }
                $proj_min_price = (!empty($querydata['min_price']) ? trim($querydata['min_price']) : '');
                $proj_max_price = (!empty($querydata['max_price']) ? trim($querydata['max_price']) : '');
                $proj_config = (!empty($querydata['config']) ? trim($querydata['config']) : '');
                if (empty($builder_id)) {
                    $proj_sm_id = (!empty($querydata['sm_id']) ? trim($querydata['sm_id']) : '');
                    if (!empty($proj_sm_id)) {
                        $sel_sm_arr[0] = $proj_sm_id;
                        $get_proj_sm = $this->getprojofmultism($sel_sm_arr);
                        if (!empty($get_proj_sm)) {
                            $get_proj_txt = implode(",", $get_proj_sm);
                        } else {
                            $get_proj_txt = "-1";
                        }
                    }
                } else {
                    if (empty($get_proj_txt)) {
                        $get_proj_txt = "-1";
                    }
                }

                $proj_property_type = (!empty($querydata['property_type']) ? trim($querydata['property_type']) : '');
                $proj_amenities = (!empty($querydata['amenities']) ? trim($querydata['amenities']) : '');


                /* $proj_location_id = (!empty($querydata['location_id']) ? implode(",", $querydata['location_id']) : []); */
                $proj_location_id = (!empty($querydata['location_id']) ? trim($querydata['location_id']) : '');
            }

            $order_name = (isset($querydata['sort_name']) ? trim($querydata['sort_name']) : 'projects.name');
            $order_type = (isset($querydata['sort_type']) ? trim($querydata['sort_type']) : 'ASC');


            $page_count = (isset($querydata['page_count']) ? trim($querydata['page_count']) : 25);
            $page = (isset($querydata['page']) ? trim($querydata['page']) : 1);
            if ($page == 1) {
                $offset = 0;
            } else {
                $offset = (($page - 1) * $page_count);
            }

            $where_sql = 'projects.id IN(' . $get_proj_txt . ') AND projects.status=1 ';
            if (!empty($proj_name)) {
                $where_sql .= ' AND projects.name like "%' . $proj_name . '%"';
            }
            if (!empty($proj_builder_id)) {
                $where_sql .= ' AND projects.builder_id="' . $proj_builder_id . '"';
            }
            if (!empty($proj_type)) {
                //$where_sql .= ' AND projects.type="' . $proj_type . '"';
                $where_sql .= ' AND FIND_IN_SET("' . (int) $proj_type . '",projects.type)';
            }
            if (!empty($proj_min_price)) {
                $where_sql .= ' AND m.low_price>=' . $proj_min_price . '';
            }
            if (!empty($proj_max_price)) {
                $where_sql .= ' AND m.low_price<=' . $proj_max_price . '';
            }
            if (!empty($proj_config)) {
                $proj_config_arr = explode(",", $proj_config);
                if (count($proj_config_arr) == 1) {
                    $where_sql .= ' AND FIND_IN_SET("' . (int) $proj_config . '",f.flat_types)';
                } else {
                    $where_sql .= ' AND (';
                    $get_count_config = count($proj_config_arr);
                    $icheck = 1;
                    foreach ($proj_config_arr as $proj_config_arr_val) {
                        $where_sql .= ' FIND_IN_SET("' . (int) $proj_config_arr_val . '",f.flat_types)';
                        if ($icheck != $get_count_config) {
                            $where_sql .= ' OR ';
                        }
                        $icheck++;
                    }
                    $where_sql .= '  )';
                }
            }
            if (!empty($proj_property_type)) {
                $proj_property_type_arr = explode(",", $proj_property_type);
                if (count($proj_property_type_arr) == 1) {
                    $where_sql .= ' AND FIND_IN_SET("' . (int) $proj_property_type . '",fp.flat_property_types)';
                } else {
                    $where_sql .= ' AND (';
                    $get_type_count_config = count($proj_property_type_arr);
                    $icheck_type = 1;
                    foreach ($proj_property_type_arr as $proj_property_type_arr_val) {
                        $where_sql .= ' FIND_IN_SET("' . (int) $proj_property_type_arr_val . '",fp.flat_property_types)';
                        if ($icheck_type != $get_type_count_config) {
                            $where_sql .= ' OR ';
                        }
                        $icheck_type++;
                    }
                    $where_sql .= '  )';
                }
            }

            if (!empty($proj_amenities)) {
                $proj_amenities_arr = explode(",", $proj_amenities);
                if (count($proj_amenities_arr) == 1) {
                    $where_sql .= ' AND FIND_IN_SET("' . (int) $proj_amenities . '",projects.amenities)';
                } else {
                    $where_sql .= ' AND (';
                    $get_count_am = count($proj_amenities_arr);
                    $icheck_am = 1;
                    foreach ($proj_amenities_arr as $proj_amenities_arr_val) {
                        $where_sql .= ' FIND_IN_SET("' . (int) $proj_amenities_arr_val . '",projects.amenities)';
                        if ($icheck_am != $get_count_am) {
                            $where_sql .= ' OR ';
                        }
                        $icheck_am++;
                    }
                    $where_sql .= '  )';
                }
            }


            if (!empty($proj_location_id)) {
                $where_sql .= ' AND projects.location_id IN(' . $proj_location_id . ')';
            }
            if (isset($querydata['possession']) && $querydata['possession'] == 'true') {
                $where_sql .= ' AND projects.possession_date<"' . date('Y-m-d') . '"';
            } else if (isset($querydata['possession']) && $querydata['possession'] == 'false') {
                $where_sql .= ' AND projects.possession_date>"' . date('Y-m-d') . '"';
            }


            if (empty($list_type)) {

                if (!empty($cp_location)) {
                    $sort_text = new Expression("FIELD(projects.location_id, " . $cp_location . ") DESC");
                } else {
                    $sort_text = $order_name . ' ' . $order_type;
                }

                $proj_query = (new \yii\db\Query())
                    ->select('projects.id,projects.name,projects.offer,projects.site_address,projects.possession_date,projects.builder_id,projects.logo_name,projects.type,projects.flat_configuration,projects.project_segment,projects.created_on,m.low_price,f.flat_types,fp.flat_property_types,projects.latlong,projects.whatsapp_brief,projects.location_id,loc.name as location,projects.whatsapp_top,projects.whatsapp_middle,projects.whatsapp_bottom,projects.rera_no,projects.amenities,projects.connectivity')
                    ->from('projects')
                    ->leftJoin("(select MIN(base_price) as low_price,projects_id from flat WHERE status=1 AND property_type=1 group by projects_id ) m", 'm.projects_id=projects.id ')
                    /* ->leftJoin("(select sdp.name as primary_banner,sdp.projects_id from snse_dooits_photo sdp where sdp.default=2 group by sdp.projects_id ) sp", 'sp.projects_id=projects.id') */
                    ->leftJoin("(select GROUP_CONCAT(flat_type_id) as flat_types,projects_id from flat WHERE status=1 GROUP by projects_id ) f", 'f.projects_id=projects.id')
                    ->leftJoin("location as loc", 'projects.location_id = loc.id')
                    ->leftJoin("(select GROUP_CONCAT(property_type) as flat_property_types,projects_id from flat WHERE status=1 GROUP by projects_id ) fp", 'fp.projects_id=projects.id')
                    ->where($where_sql)
                    ->orderBy($sort_text);
                $proj_count = $proj_query->count();
                /* echo $proj_count;
                exit; */
                $proj_data = $proj_query->limit($page_count)->offset($offset)->createCommand()
                    /* ->getRawsql();
                    echo $proj_data;
                    exit; */
                    ->queryAll();
            } else {
                $proj_query = (new \yii\db\Query())
                    ->select('projects.id,projects.name,projects.whatsapp_brief')
                    ->from('projects')
                    ->leftJoin("(select MIN(base_price) as low_price,projects_id from flat WHERE status=1 AND property_type=1 group by projects_id ) m", 'm.projects_id=projects.id')
                    ->leftJoin("(select GROUP_CONCAT(flat_type_id) as flat_types,projects_id from flat WHERE status=1 GROUP by projects_id ) f", 'f.projects_id=projects.id')
                    ->leftJoin("(select GROUP_CONCAT(property_type) as flat_property_types,projects_id from flat WHERE status=1 GROUP by projects_id ) fp", 'fp.projects_id=projects.id')
                    ->where($where_sql)
                    ->orderBy($order_name . ' ' . $order_type);

                $proj_data = $proj_query->createCommand()
                    ->queryAll();
            }

            /* echo "<pre>";
                print_r($proj_data);
                exit; */
            if (!empty($proj_data)) {
                //$check_proj_count = 0;      //added for testing
                //$check_multi_count = 1;     //added for testing
                //while ($check_multi_count < 6) {    //added for testing
                foreach ($proj_data as $proj_data_key => $proj_data_val) {
                    //$proj_data_key = $check_proj_count;     //added for testing
                    $project[$proj_data_key] = $proj_data_val;

                    if (empty($list_type)) {

                        //get banner
                        $getbanner = SnseBanner::findOne([
                            'projects_id' => $proj_data_val['id'],
                            'status' => 1
                        ]);
                        if (!empty($getbanner)) {
                            $project[$proj_data_key]['banner'] = \Yii::$app->params['web_path'] . "files/banner/orig/" . $getbanner->name;
                        } else {
                            $project[$proj_data_key]['banner'] = null;
                        }

                        if (!empty($proj_data_val['offer'])) {
                            $project[$proj_data_key]['offer'] = $proj_data_val['offer'];
                        } else {
                            $project[$proj_data_key]['offer'] = null;
                        }

                        /* if (!empty($proj_data_val['primary_banner'])) {
                                $project[$proj_data_key]['banner'] = \Yii::$app->params['upload_file_path'] . $proj_data_val['primary_banner'];
                                } */
                        $builder_data = Builder::find()->select('name')->where(['id' => $proj_data_val['builder_id']])->one();
                        if (!empty($builder_data)) {
                            $project[$proj_data_key]['builder'] = $builder_data->name;
                        } else {
                            $project[$proj_data_key]['builder'] = '';
                        }

                        if (!empty($proj_data_val['type'])) {
                            $proj_type = explode(",", $proj_data_val['type']);
                            $proj_type_txt = '';
                            foreach ($proj_type as $proj_type_val) {
                                if (empty($proj_type_txt)) {
                                    $proj_type_txt = $this->project_type[$proj_type_val];
                                } else {
                                    $proj_type_txt .= "," . $this->project_type[$proj_type_val];
                                }
                            }
                            $project[$proj_data_key]['type'] = $proj_type_txt;
                        }
                        if (!empty($proj_data_val['low_price'])) {
                            $project[$proj_data_key]['price'] = $proj_data_val['low_price'];
                            $project[$proj_data_key]['priceinwords'] = $this->AmountInWords($proj_data_val['low_price']);
                        }

                        if (!empty($proj_data_val['project_segment'])) {
                            $project[$proj_data_key]['project_segment'] = $this->project_segment[$proj_data_val['project_segment']];
                        }

                        $project[$proj_data_key]['bookmark'] = 'false';
                        $getbookmark = SmCpBookmark::findOne([
                            'sm_cp_id' => $sm_cp_id,
                            'projects_id' => $proj_data_val['id'],
                        ]);
                        if (!empty($getbookmark)) {
                            $project[$proj_data_key]['bookmark'] = 'true';
                        }
                    }

                    //get sourcing
                    $sourcingData = (new \yii\db\Query())
                        ->select('sm.sm_cp_id,sm.name,sm.role,sm.contact')
                        ->from('sm_projects sp')
                        ->leftJoin("sm_cp as sm", 'sp.sm_cp_id = sm.sm_cp_id')
                        ->where('FIND_IN_SET("' . (int) $proj_data_val['id'] . '",projects_id) AND sp.status=1 AND sm.status=1 AND sm.is_deleted=0')->groupBy('sp.sm_cp_id')->createCommand()
                        ->queryAll();
                    $sourcing = null;
                    $sourcingbyrole = null;
                    $final_sourcing = null;
                    if (!empty($sourcingData)) {
                        $s_count = 0;
                        foreach ($sourcingData as $sourcingData_val) {
                            $sourcing[$s_count]['sm_cp_id'] = $sourcingData_val['sm_cp_id'];
                            $sourcing[$s_count]['name'] = $sourcingData_val['name'];
                            $sourcing[$s_count]['role'] = $this->role[$sourcingData_val['role']];
                            $sourcing[$s_count]['contact'] = $sourcingData_val['contact'];
                            $sourcingbyrole[$sourcingData_val['role']] = $sourcing[$s_count];
                            $s_count++;
                        }
                        //Show executive first, then manager then Leader
                        if (isset($sourcingbyrole[3])) {
                            $final_sourcing[0] = $sourcingbyrole[3];
                        } else if (isset($sourcingbyrole[2])) {
                            $final_sourcing[0] = $sourcingbyrole[2];
                        } else if (isset($sourcingbyrole[1])) {
                            $final_sourcing[0] = $sourcingbyrole[1];
                        }

                        $project[$proj_data_key]['sourcing'] = $final_sourcing;
                    }

                    //get base price of lowest flat
                    $flatData = (new \yii\db\Query())
                        ->select('flat.base_price,flat.flat_type_id,flat.property_type,flat.carpet_area,flat.base_price')
                        ->from('flat')
                        ->where('flat.projects_id="' . $proj_data_val['id'] . '" AND flat.status=1')
                        ->orderBy('flat.property_type ASC, flat.total_charge ASC')->createCommand()
                        ->queryAll();

                    if (!empty($flatData)) {
                        $flat_type_list_arr = [];
                        foreach ($flatData as $flatData_v) {
                            $flat_type_list_arr[] = (int) $flatData_v['flat_type_id'];
                        }
                        $flat_type_list_arr = array_unique($flat_type_list_arr);
                        $final_flat_type = [];
                        foreach ($flat_type_list_arr as $flat_type_list_arr_val) {
                            if (in_array($flat_type_list_arr_val, array_keys($this->flat_type_id))) {
                                $final_flat_type[$flat_type_list_arr_val] = $this->flat_type_id[$flat_type_list_arr_val];
                            }
                        }
                        $project[$proj_data_key]['flat_type'] = $final_flat_type;
                    }

                    //updating lat long
                    $project[$proj_data_key]['lat'] = null;
                    $project[$proj_data_key]['long'] = null;
                    if (!empty($project[$proj_data_key]['latlong'])) {
                        $getlat_long = explode(",", $project[$proj_data_key]['latlong']);
                        $project[$proj_data_key]['lat'] = !(empty($getlat_long[0])) ? trim($getlat_long[0]) : "";
                        $project[$proj_data_key]['long'] = !empty($getlat_long[1]) ? trim($getlat_long[1]) : "";
                    }

                    /* if (!empty($proj_data_key['whatsapp_brief'])) {
                        $get_whatsapp_brief = trim(preg_replace('/\s+/', ' ', $proj_data_key['whatsapp_brief']));
                        $project[$proj_data_key]['whatsapp_brief'] = $get_whatsapp_brief;
                    } */

                    if (empty($list_type)) {
                        //whatsapp brief start---------
                        $get_whatsapp_brief = "";
                        //$set_br = "\n\n";
                        $set_br = PHP_EOL;
                        $projname = "*" . $project[$proj_data_key]['name'] . "*" . $set_br . $set_br;
                        $whatsapptop =  $project[$proj_data_key]['whatsapp_top'];
                        if (!empty($whatsapptop)) {
                            $whatsapptop = $whatsapptop . $set_br . $set_br;
                        }
                        $flat_txt = '';
                        if (!empty($flatData)) {
                            $flat_txt .= "*Configurations*" . $set_br;

                            foreach ($flatData as $flatData_val) {
                                $get_sp_flat_type_id = !empty($flatData_val['flat_type_id']) ? $flatData_val['flat_type_id'] : "";
                                $get_sp_flat_type_text = !empty($get_sp_flat_type_id) && $flatData_val['property_type'] == 1 ? $this->flat_type_id[$get_sp_flat_type_id] : "";

                                $flat_txt .= $this->flat_property_type[$flatData_val['property_type']] . " " . $get_sp_flat_type_text . " - " . $flatData_val['carpet_area'] . " Carpet, Price -" . $this->AmountInWords($flatData_val['base_price']) . "* Onwards" . $set_br;
                            }
                        }
                        $config = $flat_txt;
                        $rera = "*RERA Number - " .  $project[$proj_data_key]['rera_no'] . "*";


                        //get amenities
                        $amenities_txt = "";
                        $amenity_list = "";
                        if (!empty($project[$proj_data_key]['amenities'])) {
                            $amenitiesData = (new \yii\db\Query())
                                ->select('name')
                                ->from('amenities')
                                ->where("id IN(" . $project[$proj_data_key]['amenities'] . ") AND status=1")->createCommand()
                                ->queryAll();


                            if (!empty($amenitiesData)) {
                                foreach ($amenitiesData as $amenitiesData_val) {
                                    $amenities_txt .= $amenitiesData_val['name'] . $set_br;
                                }
                            }
                            if (!empty($amenities_txt)) {
                                $amenity_list = "*Modern Amenities*" . $set_br . $amenities_txt;
                            }
                        }

                        $whatsappmiddle = $project[$proj_data_key]['whatsapp_middle'];
                        if (!empty($whatsappmiddle)) {
                            $whatsappmiddle = $whatsappmiddle . $set_br;
                        }
                        $connectivity = "*Connectivity*" . $set_br . $project[$proj_data_key]['connectivity'];
                        $whatsappbottom = $project[$proj_data_key]['whatsapp_bottom'];
                        $get_whatsapp_brief = $projname . $whatsapptop . $config . $set_br . $rera . $set_br . $set_br . $amenity_list . $set_br . $connectivity  . $set_br . $whatsappmiddle  . $set_br . $whatsappbottom;
                        //$get_whatsapp_brief = $projname . $whatsapptop;
                        //$get_whatsapp_brief = trim(preg_replace('/\s+/', ' ', $get_whatsapp_brief));
                        $get_whatsapp_brief = trim($get_whatsapp_brief);
                        $project[$proj_data_key]['whatsapp_brief'] = $get_whatsapp_brief;
                        //whatsapp brief end---------
                    }


                    if (empty($list_type)) {
                        unset($project[$proj_data_key]['logo_name'], $project[$proj_data_key]['low_price'], $project[$proj_data_key]['builder_id'], $project[$proj_data_key]['flat_types'], $project[$proj_data_key]['flat_property_types'],  $project[$proj_data_key]['latlong']);
                    }

                    //$check_proj_count++;    //added for testing
                }
                //$check_multi_count++;       //added for testing
                //}       //added for testing
            }

            /* echo "<pre>";
                print_r($project);
                exit; */

            if (empty($list_type)) {
                //pagination code start
                $pgdata['page'] = $page;
                //$pgdata['content_count'] = $proj_count * 5;     //added for testing
                $pgdata['content_count'] = $proj_count;
                $pgdata['page_count'] = $page_count;
                $pagination = $this->getpagination($pgdata);
                //pagination code end
            }

            /* echo "<pre>";
                print_r($project);
                exit; */
            //}
        }

        $project_arr['project'] = $project;
        if (empty($list_type)) {
            $project_arr['pagination'] = $pagination;
        }

        return $project_arr;
    }

    public function getprojectlistbookmarkapi($get_user, $querydata)
    {
        $cp_id = $get_user->channelpartner_id;
        $sm_cp_id = $get_user->sm_cp_id;
        $project_arr = null;
        $pagination = null;
        $project = null;
        /* echo "<pre>";
        print_r($querydata);
        exit; */

        $get_sm = $this->getsmofcp($cp_id);
        if (!empty($get_sm)) {
            $get_proj_sm = $this->getprojofmultism($get_sm);

            $get_proj_book = $this->getbookmarkprojects($sm_cp_id);
            $get_proj = [];
            if (!empty($get_proj_book)) {
                $get_proj = array_intersect($get_proj_book, $get_proj_sm);
            }

            if (!empty($get_proj)) {
                //pending from here
                $get_proj_txt = implode(",", $get_proj);
                if (!empty($querydata)) {
                    $proj_name = (!empty($querydata['name']) ? trim($querydata['name']) : '');
                    $proj_type = (!empty($querydata['type']) ? trim($querydata['type']) : '');
                    $proj_builder_id = (!empty($querydata['builder_id']) ? trim($querydata['builder_id']) : '');
                    $proj_min_price = (!empty($querydata['min_price']) ? trim($querydata['min_price']) : '');
                    $proj_max_price = (!empty($querydata['max_price']) ? trim($querydata['max_price']) : '');
                    $proj_config = (!empty($querydata['config']) ? trim($querydata['config']) : '');
                    /* $proj_location_id = (!empty($querydata['location_id']) ? implode(",", $querydata['location_id']) : []); */
                    $proj_location_id = (!empty($querydata['location_id']) ? trim($querydata['location_id']) : '');
                }

                $order_name = (isset($querydata['sort_name']) ? trim($querydata['sort_name']) : 'projects.name');
                $order_type = (isset($querydata['sort_type']) ? trim($querydata['sort_type']) : 'ASC');


                $page_count = (isset($querydata['page_count']) ? trim($querydata['page_count']) : 25);
                $page = (isset($querydata['page']) ? trim($querydata['page']) : 1);
                if ($page == 1) {
                    $offset = 0;
                } else {
                    $offset = (($page - 1) * $page_count);
                }

                $where_sql = 'projects.id IN(' . $get_proj_txt . ') AND projects.status=1 ';
                if (!empty($proj_name)) {
                    $where_sql .= ' AND projects.name like "%' . $proj_name . '%"';
                }
                if (!empty($proj_type)) {
                    $where_sql .= ' AND projects.type="' . $proj_type . '"';
                }
                if (!empty($proj_builder_id)) {
                    $where_sql .= ' AND projects.builder_id="' . $proj_builder_id . '"';
                }
                if (!empty($proj_min_price)) {
                    $where_sql .= ' AND m.low_price>=' . $proj_min_price . '';
                }
                if (!empty($proj_max_price)) {
                    $where_sql .= ' AND m.low_price<=' . $proj_max_price . '';
                }
                if (!empty($proj_config)) {
                    $where_sql .= ' AND FIND_IN_SET("' . (int) $proj_config . '",f.flat_types)';
                }
                if (!empty($proj_location_id)) {
                    $where_sql .= ' AND projects.location_id IN(' . $proj_location_id . ')';
                }
                if (isset($querydata['possession']) && $querydata['possession'] == 'true') {
                    $where_sql .= ' AND projects.possession_date<"' . date('Y-m-d') . '"';
                } else if (isset($querydata['possession']) && $querydata['possession'] == 'false') {
                    $where_sql .= ' AND projects.possession_date>"' . date('Y-m-d') . '"';
                }



                $proj_query = (new \yii\db\Query())
                    ->select('projects.id,projects.name,projects.offer,projects.site_address,projects.possession_date,projects.builder_id,projects.logo_name,projects.type,projects.flat_configuration,projects.project_segment,projects.created_on,m.low_price,f.flat_types,fp.flat_property_types,projects.latlong,projects.whatsapp_brief,projects.location_id,loc.name as location,projects.whatsapp_top,projects.whatsapp_middle,projects.whatsapp_bottom,projects.rera_no,projects.amenities,projects.connectivity')
                    ->from('projects')
                    ->leftJoin("(select MIN(base_price) as low_price,projects_id from flat WHERE status=1 AND property_type=1 group by projects_id ) m", 'm.projects_id=projects.id')
                    /* ->leftJoin("(select sdp.name as primary_banner,sdp.projects_id from snse_dooits_photo sdp where sdp.default=2 group by sdp.projects_id ) sp", 'sp.projects_id=projects.id') */
                    ->leftJoin("(select GROUP_CONCAT(flat_type_id) as flat_types,projects_id from flat WHERE status=1 GROUP by projects_id ) f", 'f.projects_id=projects.id')
                    ->leftJoin("location as loc", 'projects.location_id = loc.id')
                    ->leftJoin("(select GROUP_CONCAT(property_type) as flat_property_types,projects_id from flat WHERE status=1 GROUP by projects_id ) fp", 'fp.projects_id=projects.id')
                    ->where($where_sql)
                    ->orderBy($order_name . ' ' . $order_type);
                $proj_count = $proj_query->count();
                /* echo $proj_count;
                exit; */
                $proj_data = $proj_query->limit($page_count)->offset($offset)->createCommand()
                    /* ->getRawsql();
                echo $proj_data;
                exit; */
                    ->queryAll();

                if (!empty($proj_data)) {
                    foreach ($proj_data as $proj_data_key => $proj_data_val) {
                        $project[$proj_data_key] = $proj_data_val;

                        if (!empty($proj_data_val['offer'])) {
                            $project[$proj_data_key]['offer'] = $proj_data_val['offer'];
                        } else {
                            $project[$proj_data_key]['offer'] = null;
                        }

                        //get banner
                        $getbanner = SnseBanner::findOne([
                            'projects_id' => $proj_data_val['id'],
                            'status' => 1
                        ]);
                        if (!empty($getbanner)) {
                            $project[$proj_data_key]['banner'] = \Yii::$app->params['web_path'] . "files/banner/orig/" . $getbanner->name;
                        } else {
                            $project[$proj_data_key]['banner'] = null;
                        }


                        /* if (!empty($proj_data_val['primary_banner'])) {
                            $project[$proj_data_key]['banner'] = \Yii::$app->params['upload_file_path'] . $proj_data_val['primary_banner'];
                        } */
                        $builder_data = Builder::find()->select('name')->where(['id' => $proj_data_val['builder_id']])->one();
                        if (!empty($builder_data)) {
                            $project[$proj_data_key]['builder'] = $builder_data->name;
                        } else {
                            $project[$proj_data_key]['builder'] = '';
                        }

                        if (!empty($proj_data_val['type'])) {
                            $proj_type = explode(",", $proj_data_val['type']);
                            $proj_type_txt = '';
                            foreach ($proj_type as $proj_type_val) {
                                if (empty($proj_type_txt)) {
                                    $proj_type_txt = $this->project_type[$proj_type_val];
                                } else {
                                    $proj_type_txt .= "," . $this->project_type[$proj_type_val];
                                }
                            }
                            $project[$proj_data_key]['type'] = $proj_type_txt;
                        }
                        if (!empty($proj_data_val['low_price'])) {
                            $project[$proj_data_key]['price'] = $proj_data_val['low_price'];
                            $project[$proj_data_key]['priceinwords'] = $this->AmountInWords($proj_data_val['low_price']);
                        }
                        if (!empty($proj_data_val['project_segment'])) {
                            $project[$proj_data_key]['project_segment'] = $this->project_segment[$proj_data_val['project_segment']];
                        }


                        //get sourcing
                        $sourcingData = (new \yii\db\Query())
                            ->select('sm.sm_cp_id,sm.name,sm.role,sm.contact')
                            ->from('sm_projects sp')
                            ->leftJoin("sm_cp as sm", 'sp.sm_cp_id = sm.sm_cp_id')
                            ->where('FIND_IN_SET("' . (int) $proj_data_val['id'] . '",projects_id) AND sp.status=1 AND sm.status=1 AND sm.is_deleted=0')->groupBy('sp.sm_cp_id')->createCommand()
                            ->queryAll();
                        $sourcing = null;
                        if (!empty($sourcingData)) {
                            $s_count = 0;
                            foreach ($sourcingData as $sourcingData_val) {
                                $sourcing[$s_count]['sm_cp_id'] = $sourcingData_val['sm_cp_id'];
                                $sourcing[$s_count]['name'] = $sourcingData_val['name'];
                                $sourcing[$s_count]['role'] = $this->role[$sourcingData_val['role']];
                                $sourcing[$s_count]['contact'] = $sourcingData_val['contact'];
                                $s_count++;
                            }
                            $project[$proj_data_key]['sourcing'] = $sourcing;
                        }

                        //get base price of lowest flat
                        $flatData = (new \yii\db\Query())
                            ->select('flat.base_price,flat.flat_type_id,flat.property_type,flat.carpet_area,flat.base_price')
                            ->from('flat')
                            ->where('flat.projects_id="' . $proj_data_val['id'] . '" AND flat.status=1')
                            ->orderBy('flat.property_type ASC, flat.total_charge ASC')->createCommand()
                            ->queryAll();

                        if (!empty($flatData)) {
                            $flat_type_list_arr = [];
                            foreach ($flatData as $flatData_v) {
                                $flat_type_list_arr[] = (int) $flatData_v['flat_type_id'];
                            }
                            $flat_type_list_arr = array_unique($flat_type_list_arr);
                            $final_flat_type = [];
                            foreach ($flat_type_list_arr as $flat_type_list_arr_val) {
                                if (in_array($flat_type_list_arr_val, array_keys($this->flat_type_id))) {
                                    $final_flat_type[$flat_type_list_arr_val] = $this->flat_type_id[$flat_type_list_arr_val];
                                }
                            }
                            $project[$proj_data_key]['flat_type'] = $final_flat_type;
                        }


                        //updating lat long
                        $project[$proj_data_key]['lat'] = null;
                        $project[$proj_data_key]['long'] = null;
                        if (!empty($project[$proj_data_key]['latlong'])) {
                            $getlat_long = explode(",", $project[$proj_data_key]['latlong']);
                            $project[$proj_data_key]['lat'] = trim($getlat_long[0]);
                            $project[$proj_data_key]['long'] = trim($getlat_long[1]);
                        }

                        /* if (!empty($proj_data_key['whatsapp_brief'])) {
                            $get_whatsapp_brief = trim(preg_replace('/\s+/', ' ', $proj_data_key['whatsapp_brief']));
                            $project[$proj_data_key]['whatsapp_brief'] = $get_whatsapp_brief;
                        } */



                        //whatsapp brief start---------
                        $get_whatsapp_brief = "";
                        //$set_br = "\n\n";
                        $set_br = PHP_EOL;
                        $projname = "*" . $project[$proj_data_key]['name'] . "*" . $set_br . $set_br;
                        $whatsapptop =  $project[$proj_data_key]['whatsapp_top'];
                        if (!empty($whatsapptop)) {
                            $whatsapptop = $whatsapptop . $set_br . $set_br;
                        }
                        $flat_txt = '';
                        if (!empty($flatData)) {
                            $flat_txt .= "*Configurations*" . $set_br;

                            foreach ($flatData as $flatData_val) {
                                $get_sp_flat_type_id = !empty($flatData_val['flat_type_id']) ? $flatData_val['flat_type_id'] : "";
                                $get_sp_flat_type_text = !empty($get_sp_flat_type_id) && $flatData_val['property_type'] == 1 ? $this->flat_type_id[$get_sp_flat_type_id] : "";

                                $flat_txt .= $this->flat_property_type[$flatData_val['property_type']] . " " . $get_sp_flat_type_text . " - " . $flatData_val['carpet_area'] . " Carpet, Price -" . $this->AmountInWords($flatData_val['base_price']) . "* Onwards" . $set_br;
                            }
                        }
                        $config = $flat_txt;
                        $rera = "*RERA Number - " .  $project[$proj_data_key]['rera_no'] . "*";


                        //get amenities
                        $amenities_txt = "";
                        $amenity_list = "";
                        if (!empty($project[$proj_data_key]['amenities'])) {
                            $amenitiesData = (new \yii\db\Query())
                                ->select('name')
                                ->from('amenities')
                                ->where("id IN(" . $project[$proj_data_key]['amenities'] . ") AND status=1")->createCommand()
                                ->queryAll();


                            if (!empty($amenitiesData)) {
                                foreach ($amenitiesData as $amenitiesData_val) {
                                    $amenities_txt .= $amenitiesData_val['name'] . $set_br;
                                }
                            }
                            if (!empty($amenities_txt)) {
                                $amenity_list = "*Modern Amenities*" . $set_br . $amenities_txt;
                            }
                        }

                        $whatsappmiddle = $project[$proj_data_key]['whatsapp_middle'];
                        if (!empty($whatsappmiddle)) {
                            $whatsappmiddle = $whatsappmiddle . $set_br;
                        }
                        $connectivity = "*Connectivity*" . $set_br . $project[$proj_data_key]['connectivity'];
                        $whatsappbottom = $project[$proj_data_key]['whatsapp_bottom'];
                        $get_whatsapp_brief = $projname . $whatsapptop . $config . $set_br . $rera . $set_br . $set_br . $amenity_list . $set_br . $connectivity  . $set_br . $whatsappmiddle  . $set_br . $whatsappbottom;
                        //$get_whatsapp_brief = $projname . $whatsapptop;
                        //$get_whatsapp_brief = trim(preg_replace('/\s+/', ' ', $get_whatsapp_brief));
                        $get_whatsapp_brief = trim($get_whatsapp_brief);
                        $project[$proj_data_key]['whatsapp_brief'] = $get_whatsapp_brief;
                        //whatsapp brief end---------




                        $project[$proj_data_key]['bookmark'] = 'true';

                        unset($project[$proj_data_key]['logo_name'], $project[$proj_data_key]['low_price'], $project[$proj_data_key]['builder_id'], $project[$proj_data_key]['flat_types']);
                    }
                }

                //pagination code start
                $pgdata['page'] = $page;
                $pgdata['content_count'] = $proj_count;
                $pgdata['page_count'] = $page_count;
                $pagination = $this->getpagination($pgdata);
                //pagination code end

                /* echo "<pre>";
                print_r($project);
                exit; */
            }
        }


        $project_arr['project'] = $project;
        $project_arr['pagination'] = $pagination;

        return $project_arr;
    }

    public function getpagination($data_arr)
    {
        $pagination = null;
        $page = intval($data_arr['page']);
        $content_count = intval($data_arr['content_count']);
        $page_count = intval($data_arr['page_count']);

        $total_pages = floor($content_count / $page_count);
        if (($content_count % $page_count) != 0) {
            $total_pages = $total_pages + 1;
        }
        if ($total_pages > 1) {

            $pagination['current_page'] = $page;
            $pagination['total_count'] = $content_count;

            //page link
            $current_page_link = Yii::$app->request->hostInfo . Yii::$app->request->url;
            $txtcheck   = 'page=';
            if ($page < $total_pages) {
                $next_page = $page + 1;
                /* if (str_contains($current_page_link, $txtcheck)) {
                    $next_page = str_replace("page=" . $page, "page=" . $page + 1, $current_page_link);
                } else {
                    $next_page = $current_page_link . "&page=" . $page + 1;
                } */
                $pagination['next_page'] = $next_page;
            }
            if ($page - 1) {
                $previous_page = $page - 1;
                /* if (str_contains($current_page_link, $txtcheck)) {
                    $previous_page = str_replace("page=" . $page, "page=" . $page - 1, $current_page_link);
                } */
                $pagination['previous_page'] = $previous_page;
            }
            $pagination['total_page'] = $total_pages;
        }
        return $pagination;
    }



    public function getprojectapi($proj_id, $sm_cp_id)
    {
        $project_arr = null;
        $project = null;
        $proj_data = Projects::find()->select('id,name,builder_id,offer,logo_name,type,location_id,site_address,sale_address,project_description,signification,connectivity,website_address,rera_no,approved_by,no_of_tower,possession_date,flat_configuration,structure,pdf_upload,project_status,project_segment,launch_date,google_map,google_link,status,created_on,modified_on,amenities,latlong,whatsapp_brief,tc')->where(['id' => $proj_id, 'status' => 1])->one();
        if (!empty($proj_data)) {

            $location_arr = Location::findAll([
                'status' => 1
            ]);
            foreach ($location_arr as $location_arr_val) {
                $locations[$location_arr_val->id] = $location_arr_val->name;
            }
            $project = $proj_data->toArray();

            if (!empty($project['location_id'])) {
                $get_loc = $project['location_id'];
                $get_loc_name = $locations[$get_loc];

                $project['location_id'] = $get_loc_name;
            } else {
                $project['location_id'] = '';
            }

            $project_offer = $project['offer'];
            if (!empty($project_offer)) {
                $project['offer'] = $project_offer;
            } else {
                $project['offer'] = null;
            }

            $builder_data = Builder::find()->select('name')->where(['id' => $project['builder_id']])->one();
            if (!empty($builder_data)) {
                $project['builder'] = $builder_data->name;
            } else {
                $project['builder'] = '';
            }

            //get banner
            $getbanner = SnseBanner::findAll([
                'projects_id' => $proj_id,
                'status' => 1
            ]);
            if (!empty($getbanner)) {
                foreach ($getbanner as $getbanner_val) {
                    $project['banner'][] = \Yii::$app->params['web_path'] . "files/banner/orig/" . $getbanner_val->name;
                }
            } else {
                $project['banner'] = null;
            }

            /*  if (!empty($project['logo_name'])) {
                $project['banner'] = \Yii::$app->params['upload_file_path'] . $project['logo_name'];
            } */
            if (!empty($project['type'])) {
                $proj_type = explode(",", $project['type']);
                $proj_type_txt = '';
                foreach ($proj_type as $proj_type_val) {
                    if (empty($proj_type_txt)) {
                        $proj_type_txt = $this->project_type[$proj_type_val];
                    } else {
                        $proj_type_txt .= "," . $this->project_type[$proj_type_val];
                    }
                }
                $project['type'] = $proj_type_txt;
            }
            /* echo "<pre>";
            print_r($project);
            exit; */
            $project['flat_details'] = null;
            //get base price of lowest flat
            $flatData = (new \yii\db\Query())
                ->select('flat.base_price,flat.flat_type_id,flat.carpet_area,flat.total_charge,flat.property_type')
                ->from('flat')
                ->where('flat.projects_id="' . $proj_id . '" AND flat.status=1')
                ->orderBy('flat.property_type ASC, flat.total_charge ASC')->createCommand()
                ->queryAll();

            if (!empty($flatData)) {

                $flat_details_txt = '<table style="border: 1px solid black;"><tr style="border: 1px solid black;width: 100% !important;"><th style="border: 1px solid black;width: 10% !important;">Property Type</th><th style="border: 1px solid black;width: 15% !important;">Config</th><th style="border: 1px solid black;width: 15% !important;">Carpet Area</th><th style="border: 1px solid black;width: 30% !important;">Base Price</th><th style="border: 1px solid black;width: 30% !important;">Final Price</th></tr>';
                foreach ($flatData as $flatData_v) {
                    $get_sp_flat_type_id = !empty($flatData_v['flat_type_id']) ? $flatData_v['flat_type_id'] : "";
                    $get_sp_flat_type_text = !empty($get_sp_flat_type_id) && $flatData_v['property_type'] == 1 ? $this->flat_type_id[$get_sp_flat_type_id] : '';
                    $flat_details_txt .= '<tr style="border: 1px solid black;"><td style="border: 1px solid black;">' . $this->flat_property_type[$flatData_v['property_type']] . '</td><td style="border: 1px solid black;">' . $get_sp_flat_type_text . '</td><td style="border: 1px solid black;">' . $flatData_v['carpet_area'] . '</td><td style="border: 1px solid black;"> ' . $this->AmountInWords($flatData_v['base_price']) . '</td><td style="border: 1px solid black;"> ' . $this->AmountInWords($flatData_v['total_charge']) . '</td></tr>';
                }
                $flat_details_txt .= '</table>';
                $project['flat_details'] = $flat_details_txt;
                $project['price'] = $flatData[0]['base_price'];
                $project['priceinwords'] = $this->AmountInWords($project['price']);

                $flat_type_list_arr = [];
                foreach ($flatData as $flatData_v) {
                    $flat_type_list_arr[] = (int) $flatData_v['flat_type_id'];
                }
                $flat_type_list_arr = array_unique($flat_type_list_arr);
                //$project['flat_type_id'] = $flat_type_list_arr;
                $final_flat_type = [];
                $fcount = 0;
                foreach ($flat_type_list_arr as $flat_type_list_arr_val) {
                    /* if (in_array($flat_type_list_arr_val, array_keys($this->flat_type_id))) {
                        $final_flat_type[$flat_type_list_arr_val] = $this->flat_type_id[$flat_type_list_arr_val];
                    } */
                    //$final_flat_type[] = $flat_type_list_arr_val;
                    $final_flat_type[$fcount]["id"] = $flat_type_list_arr_val;
                    $final_flat_type[$fcount]["configuration"] = $this->flat_type_id[$flat_type_list_arr_val];
                    $fcount++;
                }
                $project['flat_type_id'] = $final_flat_type;
                //$project['flat_type'] = $final_flat_type;
            }

            $project['connectivity'] = nl2br($project['connectivity']);

            //commercial details
            $project['commercial_details'] = null;
            //get base price of lowest flat
            $officeData = (new \yii\db\Query())
                ->select('flat.base_price,flat.flat_type_id,flat.carpet_area,flat.total_charge,flat.property_type')
                ->from('flat')
                ->where('flat.projects_id="' . $proj_id . '" AND flat.status=1 AND flat.property_type !=1')
                ->orderBy('flat.property_type ASC, flat.total_charge ASC')->createCommand()
                ->queryAll();

            if (!empty($officeData)) {

                $office_details_txt = '<table style="border: 1px solid black;"><tr style="border: 1px solid black;"><th style="border: 1px solid black;width: 20%;">Property Type</th><th style="border: 1px solid black;width: 20%;">Carpet Area</th><th style="border: 1px solid black;width: 30%;">Base Price</th><th style="border: 1px solid black;width: 30%;">Final Price</th></tr>';
                foreach ($officeData as $officeData_v) {
                    $office_details_txt .= '<tr style="border: 1px solid black;"><td style="border: 1px solid black;">' . $this->flat_property_type[$officeData_v['property_type']] . '</td><td style="border: 1px solid black;">' . $officeData_v['carpet_area'] . '</td><td style="border: 1px solid black;"> ' . $this->AmountInWords($officeData_v['base_price']) . '</td><td style="border: 1px solid black;"> ' . $this->AmountInWords($officeData_v['total_charge']) . '</td></tr>';
                }
                $office_details_txt .= '</table>';
                $project['commercial_details'] = $office_details_txt;
            }

            if (!empty($project['pdf_upload'])) {
                $project['pdf'] = \Yii::$app->params['upload_file_path'] . $project['pdf_upload'];
            }
            /* if (!empty($project['project_status'])) {
                $project['project_status'] = $this->project_status[$project['project_status']];
            } */
            if (!empty($project['project_segment'])) {
                $project['project_segment'] = $this->project_segment[$project['project_segment']];
            }




            //get bookmark
            $getbookmark = SmCpBookmark::findOne([
                'sm_cp_id' => $sm_cp_id,
                'projects_id' => $proj_id,
            ]);
            if (!empty($getbookmark)) {
                $project['bookmark'] = true;
            } else {
                $project['bookmark'] = false;
            }

            $proj_amenities = $project['amenities'];

            //updating lat long
            $project['lat'] = null;
            $project['long'] = null;
            if (!empty($project['latlong'])) {
                $getlat_long = explode(",", $project['latlong']);
                $project['lat'] = trim($getlat_long[0]);
                $project['long'] = trim($getlat_long[1]);
            }

            /* if (!empty($project['whatsapp_brief'])) {
                $get_whatsapp_brief = trim(preg_replace('/\s+/', ' ', $project['whatsapp_brief']));
                $project['whatsapp_brief'] = $get_whatsapp_brief;
            } */
            $project['whatsapp_brief'] = null;


            unset($project['amenities'], $project['builder_id'], $project['logo_name'], $project['latlong']);

            //get collateral
            $collateralData = (new \yii\db\Query())
                ->select('sphoto.docs_name,sphoto.name,sphoto.photo_category')
                ->from('snse_dooits_photo as sphoto')
                ->where('sphoto.projects_id="' . $proj_id . '" AND sphoto.status=1')->createCommand()
                ->queryAll();

            $collateral = null;
            if (!empty($collateralData)) {
                $col_count = 0;

                foreach ($collateralData as $collateralData_val) {
                    if ($collateralData_val['docs_name'] != 6) {
                        $collateral[$col_count]['docs_name'] = $collateralData_val['docs_name'];
                        $get_file_name = $collateralData_val['name'];
                        $get_file_name = preg_replace('/\s+/', '', $get_file_name);
                        $collateral[$col_count]['save_name'] = $get_file_name;
                        $collateral[$col_count]['docs_link'] = \Yii::$app->params['upload_file_path'] . rawurlencode($collateralData_val['name']);
                        $col_count++;
                    }
                }
                //showing gallery data in collateral for download
                foreach ($collateralData as $collateralData_val) {
                    if ($collateralData_val['docs_name'] == 6) {
                        $collateral[$col_count]['docs_name'] = $collateralData_val['docs_name'];
                        $collateral[$col_count]['docs_link'] = \Yii::$app->params['upload_file_path'] . rawurlencode($collateralData_val['name']);
                        $col_count++;
                    }
                }
            }
            //get amenities
            $amenities = null;
            if (!empty($proj_amenities)) {
                $amenitiesData = (new \yii\db\Query())
                    ->select('name,icon')
                    ->from('amenities')
                    ->where('id IN(' . $proj_amenities . ') AND status=1 ')->createCommand()
                    ->queryAll();

                if (!empty($amenitiesData)) {
                    $amn_count = 0;
                    foreach ($amenitiesData as $amenitiesData_val) {
                        $amenities[$amn_count]['name'] = $amenitiesData_val['name'];
                        $amenities[$amn_count]['icon'] = (!empty($amenitiesData_val['icon'])) ? \Yii::$app->params['upload_amenities_path'] . $amenitiesData_val['icon'] : '';
                        $amn_count++;
                    }
                }
            }
            //get gallery
            $galleryData = (new \yii\db\Query())
                ->select('sphoto.docs_name,sphoto.name')
                ->from('snse_dooits_photo as sphoto')
                ->where('sphoto.projects_id="' . $proj_id . '" AND sphoto.photo_category=6 AND sphoto.status=1 ')->createCommand()
                ->queryAll();
            $gallery = null;
            if (!empty($galleryData)) {
                $gal_count = 0;
                foreach ($galleryData as $galleryData_val) {
                    $gallery[$gal_count]['docs_name'] = $galleryData_val['docs_name'];
                    $gallery[$gal_count]['docs_link'] = \Yii::$app->params['upload_file_path'] . rawurlencode($galleryData_val['name']);
                    $gal_count++;
                }
            }
            //get sourcing
            $sourcingData = (new \yii\db\Query())
                ->select('sm.sm_cp_id,sm.name,sm.role,sm.contact')
                ->from('sm_projects sp')
                ->leftJoin("sm_cp as sm", 'sp.sm_cp_id = sm.sm_cp_id')
                ->where('FIND_IN_SET("' . (int) $proj_id . '",projects_id) AND sp.status=1 AND sm.status=1 AND sm.is_deleted=0')->groupBy('sp.sm_cp_id')->createCommand()
                ->queryAll();
            $sourcing = null;
            $sourcingbyrole = null;
            $final_sourcing = null;
            if (!empty($sourcingData)) {
                $s_count = 0;
                foreach ($sourcingData as $sourcingData_val) {
                    $sourcing[$s_count]['sm_cp_id'] = $sourcingData_val['sm_cp_id'];
                    $sourcing[$s_count]['name'] = $sourcingData_val['name'];
                    $sourcing[$s_count]['role'] = $this->role[$sourcingData_val['role']];
                    $sourcing[$s_count]['contact'] = $sourcingData_val['contact'];
                    $sourcingbyrole[$sourcingData_val['role']] = $sourcing[$s_count];
                    $s_count++;
                }

                //Show executive first, then manager then Leader
                if (isset($sourcingbyrole[3])) {
                    $final_sourcing[0] = $sourcingbyrole[3];
                } else if (isset($sourcingbyrole[2])) {
                    $final_sourcing[0] = $sourcingbyrole[2];
                } else if (isset($sourcingbyrole[1])) {
                    $final_sourcing[0] = $sourcingbyrole[1];
                }
            }
        }
        $project_arr['project'] = $project;
        $project_arr['collateral'] = $collateral;
        $project_arr['amenities'] = $amenities;
        $project_arr['gallery'] = $gallery;
        $project_arr['sourcing'] = $final_sourcing;


        return $project_arr;
    }

    public function getleadapi($l_id, $lead_data, $show_feed = '')
    {
        $lead_arr = null;
        $lead = null;
        if (empty($lead_data)) {
            $lead_data = Leadmaster::find()->select('id,lead_id,name,contact,email,flat_type_id,budget,customer_type,followup_date,status,tagging,created_by,created_on,modified_by,modified_on')->where(['id' => $l_id, 'is_deleted' => 0])->one();
            $lead = $lead_data->toArray();
        } else {
            $lead = $lead_data->toArray();
            unset($lead['cp_id'], $lead['created_from']);
        }
        if (!empty($lead_data)) {
            $lead['id'] = (string) $lead['id'];
            $lead['flat_type_text'] = null;
            if (!empty($lead['flat_type_id'])) {
                $lead['flat_type_id'] = (string) $lead['flat_type_id'];
                $lead['flat_type_text'] = $this->flat_type_id[$lead['flat_type_id']];
            } else {
                $lead['flat_type_id'] = null;
            }
            $lead['budgetinwords'] = null;
            if (!empty($lead['budget'])) {
                $lead['budget'] = (string) $lead['budget'];
                $lead['budgetinwords'] = $this->AmountInWords($lead['budget']);
            } else {
                $lead['budget'] = null;
            }

            if (!empty($lead['customer_type'])) {
                $lead['customer_type'] = $this->customer_type[$lead['customer_type']];
            } else {
                $lead['customer_type'] = null;
            }
            if (!empty($lead['status'])) {
                $lead['status'] = $this->lead_status[$lead['status']];
            }
            /*  if (!empty($lead['tagging'])) {
                $lead['tagging'] = 'true';
            } else {
                $lead['tagging'] = 'false';
            } */
            //$lead['tag_count'] = "0";
            /* if ($lead['tagging'] == 'true') {
                $tag_query = (new \yii\db\Query())
                    ->select('id')
                    ->from('taggingmaster')
                    ->where("taggingmaster.lead_id='" . $l_id . "'");
                $tag_count = $tag_query->count();
                $lead['tag_count'] = $tag_count;
            } */

            //get tag details if any
            $tagData = (new \yii\db\Query())
                ->select('t.id,t.appointment_date,p.name')
                ->from('taggingmaster t')
                ->leftJoin("projects as p", 't.project_id = p.id')
                ->where("t.lead_id='" . $l_id . "' AND t.is_deleted=0")->createCommand()
                ->queryAll();
            $tag_arr = null;
            $t_count = 0;
            if (!empty($tagData)) {
                foreach ($tagData as $tagData_val) {
                    $tag_arr[$t_count]['id'] = $tagData_val['id'];
                    $tag_arr[$t_count]['tagging_date'] = $tagData_val['appointment_date'];
                    $tag_arr[$t_count]['project'] = $tagData_val['name'];
                    $t_count++;
                }
            }

            $lead['tag_count'] = $t_count;
            $lead['tagging'] = 'False';
            $lead['tag_data'] = $tag_arr;
            if (!empty($t_count)) {
                $lead['tagging'] = 'True';
            }



            if (!empty($lead['created_by'])) {
                $created_by_model = SmCp::find()->where(['sm_cp_id' => $lead['created_by'], 'is_deleted' => 0])->one();
                $lead['created_by'] = $created_by_model->name;
            } else {
                $lead['created_by'] = null;
            }
            if (!empty($lead['modified_by'])) {
                $modified_by_model = SmCp::find()->where(['sm_cp_id' => $lead['modified_by']])->one();
                $lead['modified_by'] = $modified_by_model->name;
            } else {
                $lead['modified_by'] = null;
            }

            $lead_arr['lead'] = $lead;
            if (!empty($show_feed)) {
                //get lead feedback
                $feedData = (new \yii\db\Query())
                    ->select('fd.id,fd.feedback,fd.created_on,sm.sm_cp_id,sm.name,sm.role')
                    ->from('lead_feedback fd')
                    ->leftJoin("sm_cp as sm", 'fd.created_by = sm.sm_cp_id')
                    ->where('fd.lead_id="' . $l_id . '"')
                    ->orderBy('fd.id DESC')
                    ->limit(5)
                    ->createCommand()
                    ->queryAll();
                $feedback = null;
                if (!empty($feedData)) {
                    $f_count = 0;
                    foreach ($feedData as $feedData_val) {
                        //$feedback[$f_count]['id'] = $feedData_val['id'];
                        $feedback[$f_count]['feedback'] = $feedData_val['feedback'];
                        $feedback[$f_count]['created_on'] = $feedData_val['created_on'];
                        //$feedback[$f_count]['sm_cp_id'] = $feedData_val['sm_cp_id'];
                        $feedback[$f_count]['created_by'] = $feedData_val['name'];
                        //$feedback[$f_count]['role'] = $this->role[$feedData_val['role']];
                        $f_count++;
                    }
                }
                $lead_arr['lead']['feedback'] = $feedback;
            }

            $lead_arr['flat_type'] = $this->flat_type_id;
            $lead_arr['customer_type'] = $this->customer_type;
            $lead_arr['status'] = $this->lead_status;
            $lead_arr['tagging'] = $this->tagging_done;
        }
        return $lead_arr;
    }

    public function getleadshortapi($l_id, $lead_data, $show_feed = '')
    {
        $lead_arr = null;
        $lead = null;
        if (empty($lead_data)) {
            $lead_data = Leadmaster::find()->select('id,lead_id,name,contact,email,flat_type_id,budget,customer_type,followup_date,status,tagging,created_by,created_on,modified_by,modified_on')->where(['id' => $l_id, 'is_deleted' => 0])->one();
            $lead = $lead_data->toArray();
        } else {
            $lead = $lead_data->toArray();
            unset($lead['cp_id'], $lead['created_from']);
        }
        if (!empty($lead_data)) {
            $lead['id'] = (string) $lead['id'];
            $lead['flat_type_text'] = null;
            if (!empty($lead['flat_type_id'])) {
                $lead['flat_type_id'] = (string) $lead['flat_type_id'];
                $lead['flat_type_text'] = $this->flat_type_id[$lead['flat_type_id']];
            } else {
                $lead['flat_type_id'] = null;
            }
            $lead['budgetinwords'] = null;
            if (!empty($lead['budget'])) {
                $lead['budget'] = (string) $lead['budget'];
                $lead['budgetinwords'] = $this->AmountInWords($lead['budget']);
            } else {
                $lead['budget'] = null;
            }

            if (!empty($lead['customer_type'])) {
                $lead['customer_type'] = $this->customer_type[$lead['customer_type']];
            } else {
                $lead['customer_type'] = null;
            }
            if (!empty($lead['status'])) {
                $lead['status'] = $this->lead_status[$lead['status']];
            }
            /* if (!empty($lead['tagging'])) {
                $lead['tagging'] = 'true';
            } else {
                $lead['tagging'] = 'false';
            }
            $lead['tag_count'] = "0";
            if ($lead['tagging'] == 'true') {
                $tag_query = (new \yii\db\Query())
                    ->select('id')
                    ->from('taggingmaster')
                    ->where("taggingmaster.lead_id='" . $l_id . "'");
                $tag_count = $tag_query->count();
                $lead['tag_count'] = $tag_count;
            } */

            //get tag details if any
            $tagData = (new \yii\db\Query())
                ->select('t.id,t.appointment_date,p.name')
                ->from('taggingmaster t')
                ->leftJoin("projects as p", 't.project_id = p.id')
                ->where("t.lead_id='" . $l_id . "' AND t.is_deleted=0")->createCommand()
                ->queryAll();
            $tag_arr = null;
            $t_count = 0;
            if (!empty($tagData)) {
                foreach ($tagData as $tagData_val) {
                    $tag_arr[$t_count]['id'] = $tagData_val['id'];
                    $tag_arr[$t_count]['tagging_date'] = $tagData_val['appointment_date'];
                    $tag_arr[$t_count]['project'] = $tagData_val['name'];
                    $t_count++;
                }
            }

            $lead['tag_count'] = $t_count;
            $lead['tagging'] = 'False';
            //$lead['tag_data'] = $tag_arr;
            if (!empty($t_count)) {
                $lead['tagging'] = 'True';
            }




            if (!empty($lead['created_by'])) {
                $created_by_model = SmCp::find()->where(['sm_cp_id' => $lead['created_by'], 'is_deleted' => 0])->one();
                $lead['created_by'] = $created_by_model->name;
            } else {
                $lead['created_by'] = null;
            }
            if (!empty($lead['modified_by'])) {
                $modified_by_model = SmCp::find()->where(['sm_cp_id' => $lead['modified_by']])->one();
                $lead['modified_by'] = $modified_by_model->name;
            } else {
                $lead['created_by'] = null;
            }

            $lead_arr['lead'] = $lead;
            if (!empty($show_feed)) {
                //get lead feedback
                $feedData = (new \yii\db\Query())
                    ->select('fd.id,fd.feedback,fd.created_on,sm.sm_cp_id,sm.name,sm.role')
                    ->from('lead_feedback fd')
                    ->leftJoin("sm_cp as sm", 'fd.created_by = sm.sm_cp_id')
                    ->where('fd.lead_id="' . $l_id . '"')
                    ->orderBy('fd.id DESC')
                    ->limit(5)
                    ->createCommand()
                    ->queryAll();
                $feedback = null;
                if (!empty($feedData)) {
                    $f_count = 0;
                    foreach ($feedData as $feedData_val) {
                        //$feedback[$f_count]['id'] = $feedData_val['id'];
                        $feedback[$f_count]['feedback'] = $feedData_val['feedback'];
                        $feedback[$f_count]['created_on'] = $feedData_val['created_on'];
                        //$feedback[$f_count]['sm_cp_id'] = $feedData_val['sm_cp_id'];
                        $feedback[$f_count]['created_by'] = $feedData_val['name'];
                        //$feedback[$f_count]['role'] = $this->role[$feedData_val['role']];
                        $f_count++;
                    }
                }
                $lead_arr['lead']['feedback'] = $feedback;
            }

            /* $lead_arr['flat_type'] = $this->flat_type_id;
            $lead_arr['customer_type'] = $this->customer_type;
            $lead_arr['status'] = $this->lead_status;
            $lead_arr['tagging'] = $this->tagging_done; */
        }
        return $lead_arr;
    }

    public function gettagapi($tag_id, $tag_data, $show_feed = '')
    {
        $tag_arr = null;
        $tag = null;
        if (empty($tag_data)) {
            $tag_data = Taggingmaster::find()->select('id,lead_id,tagging_id,tag_name,tag_phone,tag_email,flat_type_id,sm_cp_id,project_id,budget,customer_type,appointment_date,appointment_time,status,created_by,created_on,modified_by,modified_on,visit_notvisit_clash_date,lead_convert_date,lead_dead_date,lead_registered_date,retag_limit,tag_code')->where(['id' => $tag_id, 'is_deleted' => 0])->one();
            $tag = $tag_data->toArray();
        } else {
            $tag = $tag_data->toArray();
            unset($tag['is_deleted'], $tag['deleted_on'], $tag['deleted_by'], $tag['created_from'], $tag['cp_id'], $tag['is_accepted']);
        }

        if (!empty($tag_data)) {

            $lead_data = Leadmaster::find()->select('id,lead_id,name')->where(['id' => $tag['lead_id'], 'is_deleted' => 0])->one();
            if (!empty($lead_data)) {
                $tag['lead_id'] = $lead_data->lead_id;
            }
            $tag['id'] = (string) $tag['id'];
            if (!empty($tag['tag_name'])) {
                $tag['name'] = $tag['tag_name'];
                unset($tag['tag_name']);
            }
            if (!empty($tag['tag_phone'])) {
                $tag['contact'] = $tag['tag_phone'];
                unset($tag['tag_phone']);
            }
            if (!empty($tag['tag_email'])) {
                $tag['email'] = $tag['tag_email'];
                unset($tag['tag_email']);
            } else {
                $tag['email'] = null;
            }
            $tag['flat_type_text'] = null;
            if (!empty($tag['flat_type_id'])) {
                $tag['flat_type_id'] = (string) $tag['flat_type_id'];
                $tag['flat_type_text'] = $this->flat_type_id[$tag['flat_type_id']];
            } else {
                $tag['flat_type_id'] = null;
            }
            $tag['budgetinwords'] = null;
            if (!empty($tag['budget'])) {
                $tag['budget'] = (string) $tag['budget'];
                $tag['budgetinwords'] = $this->AmountInWords($tag['budget']);
            } else {
                $tag['budget'] = null;
            }



            $tag_limit_set = isset($tag['retag_limit']) ? intval($tag['retag_limit']) : 0;
            $tag_available = intval(\Yii::$app->params['RETAG_MAX']) - $tag_limit_set;
            $tag['retag_attempt_left'] = (string) $tag_available;


            if (!empty($tag['customer_type'])) {
                $tag['customer_type'] = $this->customer_type[$tag['customer_type']];
            } else {
                $tag['customer_type'] = null;
            }
            if (!empty($tag['status'])) {
                $tag['statusText'] = $this->tag_status[$tag['status']];

                if ($tag['status'] == 1) {
                    $tag['visited_on'] = $tag['visit_notvisit_clash_date'];
                } else if ($tag['status'] == 3) {
                    $tag['clashed_on'] = $tag['visit_notvisit_clash_date'];
                } else if ($tag['status'] == 7) {
                    $tag['rejected_on'] = $tag['visit_notvisit_clash_date'];
                } else if ($tag['status'] == 4) {
                    $tag['booked_on'] = $tag['lead_convert_date'];
                } else if ($tag['status'] == 5) {
                    $tag['lead_dead_on'] = $tag['lead_dead_date'];
                } else if ($tag['status'] == 6) {
                    $tag['registered_on'] = $tag['lead_registered_date'];
                }
                /* if ($tag['statusText'] == 'Visited') {
                    $tag['visited_on'] = $tag['visit_notvisit_clash_date'];
                } else if ($tag['statusText'] == 'Clashed') {
                    $tag['clash_on'] = $tag['visit_notvisit_clash_date'];
                } else if ($tag['statusText'] == 'Lead Converted') {
                    $tag['lead_convert_on'] = $tag['lead_convert_date'];
                } else if ($tag['statusText'] == 'Lead Dead') {
                    $tag['lead_dead_on'] = $tag['lead_dead_date'];
                } else if ($tag['statusText'] == 'Lead Registered') {
                    $tag['lead_registered_on'] = $tag['lead_registered_date'];
                } */
            } else {
                $tag['statusText'] = 'In Progress';
            }
            unset($tag['visit_notvisit_clash_date'], $tag['lead_convert_date'], $tag['lead_dead_date'], $tag['lead_registered_date']);

            if (!empty($tag['project_id'])) {
                $project_model = Projects::find()->where(['id' => $tag['project_id']])->one();
                $tag['project_id'] = $project_model->name;
            }

            if (!empty($tag['sm_cp_id'])) {
                $sourcing_model = SmCp::find()->where(['sm_cp_id' => $tag['sm_cp_id'], 'is_deleted' => 0])->one();
                $tag['sourcing_id'] = $sourcing_model->name;
                $get_sm_contact = $sourcing_model->contact;
                unset($tag['sm_cp_id']);
            }



            if (!empty($tag['created_by'])) {
                $created_by_model = SmCp::find()->where(['sm_cp_id' => $tag['created_by'], 'is_deleted' => 0])->one();
                $tag['created_by'] = $created_by_model->name;
            } else {
                $tag['created_by'] = null;
            }

            if (!empty($tag['modified_by'])) {
                $modified_by_model = SmCp::find()->where(['sm_cp_id' => $tag['modified_by']])->one();
                $tag['modified_by'] = !empty($modified_by_model->name) ? $modified_by_model->name : null;
            } else {
                $tag['modified_by'] = null;
            }
            /* var_dump($tag);
            exit; */



            $tag['tag_code_content'] = null;
            if (!empty($tag['tag_code'])) {


                $get_cp_name = !empty($created_by_model) ? $created_by_model->name : "";
                $get_cp_contact = !empty($created_by_model) ? $created_by_model->contact : "";

                $tag_code_content = "Hello Sir," . PHP_EOL . "Your appointment has been scheduled at " . $project_model->name . "." . PHP_EOL . "Please Showcase appointment code *" . $tag['tag_code'] . "* at reception once you arrive." . PHP_EOL . PHP_EOL .  "In case of any help required to reach the project, you can contact *" . $get_cp_name . "* on *" . $get_cp_contact . "*." . PHP_EOL . PHP_EOL . "Regards,";

                /* $tag_code_content = "Hello Sir," . PHP_EOL . " Your appointment has been scheduled at " . $project_model->name . "" . PHP_EOL . " Please Showcase appointment code *" . $tag['tag_code'] . "* at reception once you arrive." . PHP_EOL . PHP_EOL . "*ADITYARAJ SALES OFFICE ADDRESS:* " . PHP_EOL . $project_model->sale_address . "" . PHP_EOL . PHP_EOL . " In case of any help required to reach the project, you can contact *" . $get_cp_name . "* on *" . $get_cp_contact . "*" . PHP_EOL . PHP_EOL . " Regards,"; */
                //$tag_code_content = trim(preg_replace('/\s+/', ' ', $tag_code_content));
                $tag['tag_code_content'] = $tag_code_content;
            }

            $tag_arr['tagging'] = $tag;
            if (!empty($show_feed)) {
                //get lead feedback
                $feedData = (new \yii\db\Query())
                    ->select('fd.id,fd.feedback,fd.created_on,sm.sm_cp_id,sm.name,sm.role')
                    ->from('tagging_feedback fd')
                    ->leftJoin("sm_cp as sm", 'fd.created_by = sm.sm_cp_id')
                    ->where('fd.tagging_id="' . $tag_id . '"')
                    ->orderBy('fd.id DESC')
                    ->limit(5)  //show last 5 feedback
                    ->createCommand()
                    ->queryAll();
                $feedback = null;
                if (!empty($feedData)) {
                    $f_count = 0;
                    foreach ($feedData as $feedData_val) {
                        //$feedback[$f_count]['id'] = $feedData_val['id'];
                        $feedback[$f_count]['feedback'] = $feedData_val['feedback'];
                        $feedback[$f_count]['created_on'] = $feedData_val['created_on'];
                        //$feedback[$f_count]['sm_cp_id'] = $feedData_val['sm_cp_id'];
                        $feedback[$f_count]['created_by'] = $feedData_val['name'];
                        //$feedback[$f_count]['role'] = $this->role[$feedData_val['role']];
                        $f_count++;
                    }
                }
                $tag_arr['tagging']['feedback'] = $feedback;
            }

            if (!empty($show_feed)) {
                $tag_arr['flat_type'] = $this->flat_type_id;
                $tag_arr['customer_type'] = $this->customer_type;
                $tag_arr['status'] = $this->tag_status;
            }
        }
        return $tag_arr;
    }

    public function gettagshortapi($tag_id, $tag_data, $show_feed = '')
    {
        $tag_arr = null;
        $tag = null;
        if (empty($tag_data)) {
            $tag_data = Taggingmaster::find()->select('id,lead_id,tagging_id,tag_name,tag_phone,tag_email,flat_type_id,sm_cp_id,project_id,budget,customer_type,appointment_date,appointment_time,status,created_by,created_on,modified_by,modified_on,visit_notvisit_clash_date,lead_convert_date,lead_dead_date,lead_registered_date,retag_limit')->where(['id' => $tag_id, 'is_deleted' => 0])->one();
            $tag = $tag_data->toArray();
        } else {
            $tag = $tag_data->toArray();
            unset($tag['is_deleted'], $tag['deleted_on'], $tag['deleted_by'], $tag['created_from'], $tag['cp_id'], $tag['is_accepted']);
        }

        if (!empty($tag_data)) {

            $lead_data = Leadmaster::find()->select('id,lead_id,name')->where(['id' => $tag['lead_id'], 'is_deleted' => 0])->one();
            if (!empty($lead_data)) {
                $tag['lead_id'] = $lead_data->lead_id;
            }
            $tag['id'] = (string) $tag['id'];
            if (!empty($tag['tag_name'])) {
                $tag['name'] = $tag['tag_name'];
                unset($tag['tag_name']);
            }
            if (!empty($tag['tag_phone'])) {
                $tag['contact'] = $tag['tag_phone'];
                unset($tag['tag_phone']);
            }
            if (!empty($tag['tag_email'])) {
                $tag['email'] = $tag['tag_email'];
                unset($tag['tag_email']);
            } else {
                $tag['email'] = null;
            }
            $tag['flat_type_text'] = null;
            if (!empty($tag['flat_type_id'])) {
                $tag['flat_type_id'] = (string) $tag['flat_type_id'];
                $tag['flat_type_text'] = $this->flat_type_id[$tag['flat_type_id']];
            } else {
                $tag['flat_type_id'] = null;
            }
            $tag['budgetinwords'] = null;
            if (!empty($tag['budget'])) {
                $tag['budget'] = (string) $tag['budget'];
                $tag['budgetinwords'] = $this->AmountInWords($tag['budget']);
            } else {
                $tag['budget'] = null;
            }


            if (!empty($tag['customer_type'])) {
                $tag['customer_type'] = $this->customer_type[$tag['customer_type']];
            } else {
                $tag['customer_type'] = null;
            }
            if (!empty($tag['status'])) {
                $tag['statusText'] = $this->tag_status[$tag['status']];
                if ($tag['status'] == 1) {
                    $tag['visited_on'] = $tag['visit_notvisit_clash_date'];
                } else if ($tag['status'] == 3) {
                    $tag['clashed_on'] = $tag['visit_notvisit_clash_date'];
                } else if ($tag['status'] == 7) {
                    $tag['rejected_on'] = $tag['visit_notvisit_clash_date'];
                } else if ($tag['status'] == 4) {
                    $tag['booked_on'] = $tag['lead_convert_date'];
                } else if ($tag['status'] == 5) {
                    $tag['lead_dead_on'] = $tag['lead_dead_date'];
                } else if ($tag['status'] == 6) {
                    $tag['registered_on'] = $tag['lead_registered_date'];
                }
                /* if ($tag['statusText'] == 'Visited') {
                    $tag['visited_on'] = $tag['visit_notvisit_clash_date'];
                } else if ($tag['statusText'] == 'Clashed') {
                    $tag['clash_on'] = $tag['visit_notvisit_clash_date'];
                } else if ($tag['statusText'] == 'Lead Converted') {
                    $tag['lead_convert_on'] = $tag['lead_convert_date'];
                } else if ($tag['statusText'] == 'Lead Dead') {
                    $tag['lead_dead_on'] = $tag['lead_dead_date'];
                } else if ($tag['statusText'] == 'Lead Registered') {
                    $tag['lead_registered_on'] = $tag['lead_registered_date'];
                } */
            } else {
                $tag['statusText'] = 'In Progress';
            }
            unset($tag['visit_notvisit_clash_date'], $tag['lead_convert_date'], $tag['lead_dead_date'], $tag['lead_registered_date']);

            if (!empty($tag['project_id'])) {
                $project_model = Projects::find()->where(['id' => $tag['project_id']])->one();
                $tag['project_id'] = $project_model->name;
            }
            if (!empty($tag['sm_cp_id'])) {
                $sourcing_model = SmCp::find()->where(['sm_cp_id' => $tag['sm_cp_id'], 'is_deleted' => 0])->one();
                $tag['sourcing_id'] = $sourcing_model->name;
                unset($tag['sm_cp_id']);
            }

            if (!empty($tag['created_by'])) {
                $created_by_model = SmCp::find()->where(['sm_cp_id' => $tag['created_by'], 'is_deleted' => 0])->one();
                $tag['created_by'] = $created_by_model->name;
            } else {
                $tag['created_by'] = null;
            }
            if (!empty($tag['modified_by'])) {
                $modified_by_model = SmCp::find()->where(['sm_cp_id' => $tag['modified_by']])->one();
                $tag['modified_by'] = $modified_by_model->name;
            } else {
                $tag['modified_by'] = null;
            }

            $tag_arr['tagging'] = $tag;
            if (!empty($show_feed)) {
                //get lead feedback
                $feedData = (new \yii\db\Query())
                    ->select('fd.id,fd.feedback,fd.created_on,sm.sm_cp_id,sm.name,sm.role')
                    ->from('tagging_feedback fd')
                    ->leftJoin("sm_cp as sm", 'fd.created_by = sm.sm_cp_id')
                    ->where('fd.tagging_id="' . $tag_id . '"')
                    ->orderBy('fd.id DESC')
                    ->limit(5)  //show last 5 feedback
                    ->createCommand()
                    ->queryAll();
                $feedback = null;
                if (!empty($feedData)) {
                    $f_count = 0;
                    foreach ($feedData as $feedData_val) {
                        //$feedback[$f_count]['id'] = $feedData_val['id'];
                        $feedback[$f_count]['feedback'] = $feedData_val['feedback'];
                        $feedback[$f_count]['created_on'] = $feedData_val['created_on'];
                        //$feedback[$f_count]['sm_cp_id'] = $feedData_val['sm_cp_id'];
                        $feedback[$f_count]['created_by'] = $feedData_val['name'];
                        //$feedback[$f_count]['role'] = $this->role[$feedData_val['role']];
                        $f_count++;
                    }
                }
                $tag_arr['tagging']['feedback'] = $feedback;
            }



            /* if (!empty($show_feed)) {
                $tag_arr['flat_type'] = $this->flat_type_id;
                $tag_arr['customer_type'] = $this->customer_type;
                $tag_arr['status'] = $this->tag_status;
            } */
        }

        $tag_limit_set = intval($tag_arr['tagging']['retag_limit']);
        $tag_available = intval(\Yii::$app->params['RETAG_MAX']) - $tag_limit_set;
        $tag_arr['tagging']['retag_attempt_left'] = (string) $tag_available;

        return $tag_arr;
    }

    public function getticketlistapi($get_user, $querydata)
    {
        $sm_cp_id = $get_user->sm_cp_id;
        $ticket_arr = null;

        $ticket = null;
        /* echo "<pre>";
        print_r($querydata);
        exit; */

        if (!empty($querydata)) {
            $ticket_contact = (!empty($querydata['contact']) ? trim($querydata['contact']) : '');
            $ticket_ticketid = (!empty($querydata['ticketid']) ? trim($querydata['ticketid']) : '');

            $ticket_start_created_on_date = (!empty($querydata['start_created_on_date']) ? trim($querydata['start_created_on_date']) : '');
            $ticket_end_created_on_date = (!empty($querydata['end_created_on_date']) ? trim($querydata['end_created_on_date']) : '');

            $ticket_status = (!empty($querydata['status']) ? trim($querydata['status']) : '');
        }

        $order_name = (isset($querydata['sort_name']) ? trim($querydata['sort_name']) : 'ticket.id');
        $order_type = (isset($querydata['sort_type']) ? trim($querydata['sort_type']) : 'DESC');


        $page_count = (isset($querydata['page_count']) ? trim($querydata['page_count']) : 25);
        $page = (isset($querydata['page']) ? trim($querydata['page']) : 1);
        if ($page == 1) {
            $offset = 0;
        } else {
            $offset = (($page - 1) * $page_count);
        }

        $where_sql = '1 ';

        if (!empty($ticket_ticketid)) {
            $where_sql .= ' AND ticket.ticketid="' . $ticket_ticketid . '"';
        }


        if (!empty($ticket_start_created_on_date)) {
            $where_sql .= ' AND DATE(ticket.created_on)>="' . $ticket_start_created_on_date . '"';
        }
        if (!empty($ticket_end_created_on_date)) {
            $where_sql .= ' AND DATE(ticket.created_on)<="' . $ticket_end_created_on_date . '"';
        }

        if (!empty($ticket_contact)) {
            $where_sql .= ' AND ticket.contact="' . $ticket_contact . '"';
        }

        if (!empty($ticket_status)) {
            $where_sql .= ' AND ticket.status="' . $ticket_status . '"';
        }



        $ticket_query = (new \yii\db\Query())
            ->select('contact,issue_type,message,created_on,modified_on,status,ticketid,feedback')
            ->from('ticket')
            ->where($where_sql)
            ->orderBy($order_name . ' ' . $order_type);
        $ticket_count = $ticket_query->count();
        /* echo $proj_count;
                exit; */
        $ticket_data = $ticket_query->limit($page_count)->offset($offset)->createCommand()
            /* ->getRawsql();
                echo $proj_data;
                exit; */
            ->queryAll();



        if (!empty($ticket_data)) {
            foreach ($ticket_data as $ticket_data_key => $ticket_data_val) {
                $ticket[$ticket_data_key] = $ticket_data_val;
                $ticket[$ticket_data_key]['status'] = $this->ticket_status[$ticket_data_val['status']];
                if (!empty($ticket_data_val['issue_type'])) {
                    $ticket[$ticket_data_key]['issue_type'] = $this->ticket_issue_type[$ticket_data_val['issue_type']];
                } else {
                    $ticket[$ticket_data_key]['issue_type'] = null;
                }
            }
        }


        //pagination code start
        $pgdata['page'] = $page;
        $pgdata['content_count'] = $ticket_count;
        $pgdata['page_count'] = $page_count;
        $pagination = $this->getpagination($pgdata);
        //pagination code end


        $ticket_arr['ticket'] = $ticket;
        $ticket_arr['pagination'] = $pagination;

        return $ticket_arr;
    }

    public function getticketapi($ticket_id, $ticket_data)
    {
        $ticket_arr = null;
        $ticket = null;
        if (empty($ticket_data)) {
            $ticket_data = Ticket::find()->select('id,contact,issue_type,message,created_on,modified_on,status,ticketid,feedback')->where(['id' => $ticket_id])->one();
            $ticket = $ticket_data->toArray();
        } else {
            $ticket = $ticket_data->toArray();
        }

        if (!empty($ticket_data)) {

            if (!empty($ticket['issue_type'])) {
                $ticket['issue_type'] = $this->ticket_issue_type[$ticket['issue_type']];
            }

            if (!empty($ticket['status'])) {
                $ticket['status'] = $this->ticket_status[$ticket['status']];
            }
            unset($ticket['created_by'], $ticket['ip_address'], $ticket['modified_by']);


            /* if (!empty($tag['modified_by'])) {
                $modified_by_model = SmCp::find()->where(['sm_cp_id' => $tag['modified_by']])->one();
                $tag['modified_by'] = $modified_by_model->name;
            } */

            $ticket_arr['ticket'] = $ticket;
        }
        return $ticket_arr;
    }

    public function getfaqlistapi($get_user, $querydata, $faqtype = 1)
    {
        $sm_cp_id = $get_user->sm_cp_id;
        $faq_arr = null;

        $faq = null;
        /* echo "<pre>";
        print_r($querydata);
        exit; */

        if (!empty($querydata)) {
            $faq_search = (!empty($querydata['search']) ? trim($querydata['search']) : '');
        }

        $order_name = (isset($querydata['sort_name']) ? trim($querydata['sort_name']) : 'faqmaster.id');
        $order_type = (isset($querydata['sort_type']) ? trim($querydata['sort_type']) : 'DESC');


        $page_count = (isset($querydata['page_count']) ? trim($querydata['page_count']) : 25);
        $page = (isset($querydata['page']) ? trim($querydata['page']) : 1);
        if ($page == 1) {
            $offset = 0;
        } else {
            $offset = (($page - 1) * $page_count);
        }

        $where_sql = 'faqmaster.status=1 ';
        if ($faqtype == 1) {
            $where_sql .= ' AND faqmaster.type IN(1,3)';
        } else {
            $where_sql .= ' AND faqmaster.type IN(2,3)';
        }

        if (!empty($faq_search)) {
            $where_sql .= ' AND ((faqmaster.question LIKE "%' . $faq_search . '%") OR (faqmaster.answer LIKE "%' . $faq_search . '%"))';
        }

        $faq_query = (new \yii\db\Query())
            ->select('question,id,answer,created_on,modified_on,id')
            ->from('faqmaster')
            ->where($where_sql)
            ->orderBy($order_name . ' ' . $order_type);
        $faq_count = $faq_query->count();
        /* echo $proj_count;
                exit; */
        $faq_data = $faq_query->limit($page_count)->offset($offset)->createCommand()
            /* ->getRawsql();
                echo $proj_data;
                exit; */
            ->queryAll();



        if (!empty($faq_data)) {
            foreach ($faq_data as $faq_data_key => $faq_data_val) {
                $faq[$faq_data_key] = $faq_data_val;
            }
        }


        //pagination code start
        $pgdata['page'] = $page;
        $pgdata['content_count'] = $faq_count;
        $pgdata['page_count'] = $page_count;
        $pagination = $this->getpagination($pgdata);
        //pagination code end


        $faq_arr['faq'] = $faq;
        $faq_arr['pagination'] = $pagination;

        return $faq_arr;
    }

    public function getfaqapi($faq_id, $faq_data)
    {
        $faq_arr = null;
        $faq = null;
        if (empty($faq_data)) {
            $faq_data = Faqmaster::find()->select('id,question,answer,created_on,modified_on,id')->where(['id' => $faq_id])->one();
            $faq = $faq_data->toArray();
        } else {
            $faq = $faq_data->toArray();
        }

        if (!empty($faq_data)) {

            unset($faq['created_by'], $faq['modified_by'], $faq['type'], $faq['status']);
            $faq_arr['faq'] = $faq;
        }
        return $faq_arr;
    }



    public function getleadstatsapi($sm_cp_id)
    {
        $get_members = $this->getaccessmembers($sm_cp_id);
        $get_members[] = $sm_cp_id;
        $statData_arr = null;


        $get_members_txt = implode(",", $get_members);
        $where_sql = " leadmaster.created_by IN(" . $get_members_txt . ") AND leadmaster.is_deleted=0 ";
        $get_date = date('Y-m-d');


        $statData = Yii::$app->db->createCommand("SELECT SUM(IF(1, 1, 0)) AS total, SUM(IF((leadmaster.followup_date>='" . $get_date . "'), 1, 0)) AS followup,SUM(IF((leadmaster.followup_date='" . $get_date . "' ), 1, 0)) AS today,SUM(IF((leadmaster.followup_date<'" . $get_date . "'), 1, 0)) AS missed,SUM(IF((DATE(leadmaster.created_on)='" . $get_date . "' ), 1, 0)) AS fresh FROM leadmaster where " . $where_sql)->queryAll();

        if (!empty($statData)) {
            $statData_arr['stats'] = $statData[0];
        }
        return $statData_arr;
    }

    public function getleadlistapi($get_user, $querydata, $list_type = '')
    {
        $sm_cp_id = $get_user->sm_cp_id;
        $lead_arr = null;
        if (empty($list_type)) {
            $pagination = null;
        }
        $lead = null;
        /* echo "<pre>";
        print_r($querydata);
        exit; */

        $get_members = $this->getaccessmembers($sm_cp_id);
        $get_members[] = $sm_cp_id;


        $get_members_txt = implode(",", $get_members);
        if (!empty($querydata)) {
            $lead_name = (!empty($querydata['name']) ? trim($querydata['name']) : '');
            $lead_lead_id = (!empty($querydata['lead_id']) ? trim($querydata['lead_id']) : '');
            $lead_start_followup_date = (!empty($querydata['start_followup_date']) ? trim($querydata['start_followup_date']) : '');
            $lead_end_followup_date = (!empty($querydata['end_followup_date']) ? trim($querydata['end_followup_date']) : '');
            $lead_start_created_on_date = (!empty($querydata['start_created_on_date']) ? trim($querydata['start_created_on_date']) : '');
            $lead_end_created_on_date = (!empty($querydata['end_created_on_date']) ? trim($querydata['end_created_on_date']) : '');
            $lead_customer_type = (!empty($querydata['customer_type']) ? trim($querydata['customer_type']) : '');

            $lead_start_budget = (!empty($querydata['min_price']) ? trim($querydata['min_price']) : '');
            $lead_end_budget = (!empty($querydata['max_price']) ? trim($querydata['max_price']) : '');
            $lead_flat_type_id = (!empty($querydata['config']) ? trim($querydata['config']) : '');

            $lead_contact = (!empty($querydata['contact']) ? trim($querydata['contact']) : '');
            $lead_created_by = (!empty($querydata['created_by']) ? trim($querydata['created_by']) : '');

            $lead_status = (!empty($querydata['status']) ? trim($querydata['status']) : '');
            $lead_type = (!empty($querydata['type']) ? trim($querydata['type']) : '');
        }

        $order_name = (isset($querydata['sort_name']) ? trim($querydata['sort_name']) : 'leadmaster.id');
        $order_type = (isset($querydata['sort_type']) ? trim($querydata['sort_type']) : 'DESC');


        $page_count = (isset($querydata['page_count']) ? trim($querydata['page_count']) : 25);
        $page = (isset($querydata['page']) ? trim($querydata['page']) : 1);
        if ($page == 1) {
            $offset = 0;
        } else {
            $offset = (($page - 1) * $page_count);
        }

        $where_sql = 'leadmaster.created_by IN(' . $get_members_txt . ') AND leadmaster.is_deleted=0 ';
        if (!empty($lead_name)) {
            $where_sql .= ' AND leadmaster.name like "%' . $lead_name . '%"';
        }
        if (!empty($lead_lead_id)) {
            $where_sql .= ' AND leadmaster.lead_id like "%' . $lead_lead_id . '%"';
        }
        if (!empty($lead_start_followup_date)) {
            $where_sql .= ' AND leadmaster.followup_date>="' . $lead_start_followup_date . '"';
        }
        if (!empty($lead_end_followup_date)) {
            $where_sql .= ' AND leadmaster.followup_date<="' . $lead_end_followup_date . '"';
        }

        //added on 1-7-24
        if (!empty($lead_start_budget)) {
            $where_sql .= ' AND leadmaster.budget>="' . $lead_start_budget . '"';
        }
        if (!empty($lead_end_budget)) {
            $where_sql .= ' AND leadmaster.budget<="' . $lead_end_budget . '"';
        }
        if (!empty($lead_flat_type_id)) {
            $where_sql .= ' AND leadmaster.flat_type_id IN(' . $lead_flat_type_id . ')';
        }


        if (!empty($lead_start_created_on_date)) {
            $where_sql .= ' AND DATE(leadmaster.created_on)>="' . $lead_start_created_on_date . '"';
        }
        if (!empty($lead_end_created_on_date)) {
            $where_sql .= ' AND DATE(leadmaster.created_on)<="' . $lead_end_created_on_date . '"';
        }
        if (!empty($lead_customer_type)) {
            $where_sql .= ' AND leadmaster.customer_type IN(' . $lead_customer_type . ')';
        }
        if (!empty($lead_contact)) {
            $where_sql .=
                ' AND leadmaster.contact like "%' . $lead_contact . '%"';
        }
        if (!empty($lead_created_by)) {
            $where_sql .= ' AND leadmaster.created_by="' . $lead_created_by . '"';
        }
        if (isset($querydata['tagged']) && $querydata['tagged'] == 'true') {
            $where_sql .= ' AND tag.tag_count is not null';
        } else if (isset($querydata['tagged']) && $querydata['tagged'] == 'false') {
            $where_sql .= ' AND tag.tag_count is null';
        }

        if (!empty($lead_status)) {
            $where_sql .= ' AND leadmaster.status="' . $lead_status . '"';
        }

        if (!empty($lead_type)) {
            if ($lead_type == 1) {
                //followup - leads with followup today and later
                $where_sql .= ' AND leadmaster.followup_date>="' . date('Y-m-d') . '"  ';
            } else if ($lead_type == 2) {
                //today - leads with followup as today
                $where_sql .= ' AND leadmaster.followup_date="' . date('Y-m-d') . '" ';
            } else if ($lead_type == 3) {
                //missed - leads with followup less than today
                $where_sql .= ' AND leadmaster.followup_date<"' . date('Y-m-d') . '" ';
            } else if ($lead_type == 4) {
                //fresh - leads with created_on as today
                $where_sql .= ' AND DATE(leadmaster.created_on)="' . date('Y-m-d') . '" ';
            }
        }



        if (empty($list_type)) {
            $lead_query = (new \yii\db\Query())
                ->select('leadmaster.id,leadmaster.name,leadmaster.lead_id,leadmaster.email,leadmaster.flat_type_id,leadmaster.contact,leadmaster.budget,leadmaster.customer_type,leadmaster.followup_date,leadmaster.status,leadmaster.tagging,tag.tag_count,leadmaster.created_on,leadmaster.modified_on,creator.name as createdby,modifier.name as modifiedby')
                ->from('leadmaster')
                ->leftJoin("(select count(t.id) as tag_count,t.lead_id from taggingmaster t group by t.lead_id ) tag", 'tag.lead_id=leadmaster.id ')
                ->leftJoin("sm_cp as creator", 'leadmaster.created_by=creator.sm_cp_id AND creator.is_deleted=0')
                ->leftJoin("sm_cp as modifier", 'leadmaster.modified_by=modifier.sm_cp_id ')
                ->where($where_sql)
                ->orderBy($order_name . ' ' . $order_type);
            $lead_count = $lead_query->count();
            /* echo $proj_count;
                exit; */
            $lead_data = $lead_query->limit($page_count)->offset($offset)->createCommand()
                /* ->getRawsql();
                echo $proj_data;
                exit; */
                ->queryAll();
        } else {
            $lead_query = (new \yii\db\Query())
                ->select('leadmaster.id,leadmaster.contact,leadmaster.name,leadmaster.lead_id')
                ->from('leadmaster')
                ->leftJoin("(select count(t.id) as tag_count,t.lead_id from taggingmaster t group by t.lead_id ) tag", 'tag.lead_id=leadmaster.id')
                ->where($where_sql)
                ->orderBy($order_name . ' ' . $order_type);

            $lead_data = $lead_query->createCommand()
                ->queryAll();
        }


        if (!empty($lead_data)) {
            foreach ($lead_data as $lead_data_key => $lead_data_val) {
                $lead[$lead_data_key] = $lead_data_val;

                if (empty($list_type)) {

                    $lead[$lead_data_key]['flat_type_text'] = null;
                    if (!empty($lead_data_val['flat_type_id'])) {
                        $lead[$lead_data_key]['flat_type_text'] = $this->flat_type_id[$lead_data_val['flat_type_id']];
                    } else {
                        $lead[$lead_data_key]['flat_type_id'] = null;
                    }

                    $lead[$lead_data_key]['budgetinwords'] = null;
                    if (!empty($lead_data_val['budget'])) {
                        $lead[$lead_data_key]['budget'] = (string) $lead_data_val['budget'];
                        $lead[$lead_data_key]['budgetinwords'] = $this->AmountInWords($lead_data_val['budget']);
                    } else {
                        $lead[$lead_data_key]['budget'] = null;
                    }

                    if (!empty($lead_data_val['customer_type'])) {
                        $lead[$lead_data_key]['customer_type'] = $this->customer_type[$lead_data_val['customer_type']];
                    } else {
                        $lead[$lead_data_key]['customer_type'] = null;
                    }

                    $lead[$lead_data_key]['status'] = $this->lead_status[$lead_data_val['status']];
                    //$lead[$lead_data_key]['tagging'] = $this->tagging_done[$lead_data_val['tagging']];
                    if (!empty($lead_data_val['tag_count'])) {
                        $lead[$lead_data_key]['tag_count'] = $lead_data_val['tag_count'];
                        $lead[$lead_data_key]['tagging'] = 'True';
                    } else {
                        $lead[$lead_data_key]['tagging'] = 'False';
                        $lead[$lead_data_key]['tag_count'] = null;
                        //unset($lead[$lead_data_key]['tag_count']);
                    }

                    //get lead feedback
                    $feedData = (new \yii\db\Query())
                        ->select('fd.id,fd.feedback,fd.created_on,sm.sm_cp_id,sm.name,sm.role')
                        ->from('lead_feedback fd')
                        ->leftJoin("sm_cp as sm", 'fd.created_by = sm.sm_cp_id AND sm.is_deleted=0')
                        ->where('fd.lead_id="' . $lead_data_val['id'] . '"')
                        ->orderBy('fd.id DESC')
                        ->limit(5)
                        ->createCommand()
                        ->queryAll();
                    $feedback = null;
                    if (!empty($feedData)) {
                        $f_count = 0;
                        foreach ($feedData as $feedData_val) {
                            //$feedback[$f_count]['id'] = $feedData_val['id'];
                            $feedback[$f_count]['feedback'] = $feedData_val['feedback'];
                            $feedback[$f_count]['created_on'] = $feedData_val['created_on'];
                            //$feedback[$f_count]['sm_cp_id'] = $feedData_val['sm_cp_id'];
                            $feedback[$f_count]['created_by'] = $feedData_val['name'];
                            //$feedback[$f_count]['role'] = $this->role[$feedData_val['role']];
                            $f_count++;
                        }
                    }
                    $lead[$lead_data_key]['feedback'] = $feedback;

                    $lead[$lead_data_key]['created_by'] = $lead_data_val['createdby'];
                    $lead[$lead_data_key]['modified_by'] = $lead_data_val['modifiedby'];
                    unset($lead[$lead_data_key]['createdby'], $lead[$lead_data_key]['modifiedby']);
                }
            }
        }

        if (empty($list_type)) {
            //pagination code start
            $pgdata['page'] = $page;
            $pgdata['content_count'] = $lead_count;
            $pgdata['page_count'] = $page_count;
            $pagination = $this->getpagination($pgdata);
            //pagination code end
        }

        $lead_arr['lead'] = $lead;
        if (empty($list_type)) {
            $lead_arr['pagination'] = $pagination;
        }

        return $lead_arr;
    }

    public function gettaglistapi($get_user, $querydata, $list_type = '')
    {
        $sm_cp_id = $get_user->sm_cp_id;
        $get_cp_id = $get_user->channelpartner_id;

        $staff_type = $get_user->staff_type;

        $get_builder_id = $get_user->builder_id;
        $tag_arr = null;
        if (empty($list_type)) {
            $pagination = null;
        }
        $tag = null;
        /* echo "<pre>";
        print_r($querydata);
        exit; */
        $get_members_txt = '';
        if ($staff_type == 1) {
            $get_members = $this->getaccessmembers($sm_cp_id);
            $get_members[] = $sm_cp_id;

            $get_members_txt = implode(",", $get_members);
        }
        $tag_status = "";
        if (!empty($querydata)) {
            $tag_project_id = (!empty($querydata['project_id']) ? $querydata['project_id'] : '');
            $tag_builder_id = (!empty($querydata['builder_id']) ? $querydata['builder_id'] : '');
            $tag_name = (!empty($querydata['name']) ? trim($querydata['name']) : '');
            $tag_contact = (!empty($querydata['contact']) ? trim($querydata['contact']) : '');
            $tag_tag_code = (!empty($querydata['tag_code']) ? trim($querydata['tag_code']) : '');
            $tag_start_appointment_date = (!empty($querydata['start_appointment_date']) ? trim($querydata['start_appointment_date']) : '');
            $tag_end_appointment_date = (!empty($querydata['end_appointment_date']) ? trim($querydata['end_appointment_date']) : '');
            $tag_start_created_on_date = (!empty($querydata['start_created_on_date']) ? trim($querydata['start_created_on_date']) : '');
            $tag_end_created_on_date = (!empty($querydata['end_created_on_date']) ? trim($querydata['end_created_on_date']) : '');
            $tag_customer_type = (!empty($querydata['customer_type']) ? trim($querydata['customer_type']) : '');
            $tag_archive = (!empty($querydata['archive']) ? trim($querydata['archive']) : '');

            $tag_start_budget = (!empty($querydata['min_price']) ? trim($querydata['min_price']) : '');
            $tag_end_budget = (!empty($querydata['max_price']) ? trim($querydata['max_price']) : '');
            $tag_flat_type_id = (!empty($querydata['config']) ? trim($querydata['config']) : '');
            $tag_sm_cp_id = (!empty($querydata['sm_cp_id']) ? trim($querydata['sm_cp_id']) : '');

            $tag_status = (isset($querydata['status']) ? trim($querydata['status']) : '');
        }

        if (!empty($get_builder_id)) {
            $tag_builder_id = $get_builder_id;
            $tag_cp_id = (!empty($querydata['cp_id']) ? $querydata['cp_id'] : '');
        }

        $order_name = (isset($querydata['sort_name']) ? trim($querydata['sort_name']) : 'taggingmaster.id');
        $order_type = (isset($querydata['sort_type']) ? trim($querydata['sort_type']) : 'DESC');


        $page_count = (isset($querydata['page_count']) ? trim($querydata['page_count']) : 25);
        $page = (isset($querydata['page']) ? trim($querydata['page']) : 1);
        if ($page == 1) {
            $offset = 0;
        } else {
            $offset = (($page - 1) * $page_count);
        }
        if (!empty($get_builder_id)) {
            if (!empty($get_members_txt)) {
                $where_sql = 'taggingmaster.sm_cp_id IN(' . $get_members_txt . ') AND taggingmaster.is_deleted=0 ';
            } else {
                $where_sql = 'taggingmaster.is_deleted=0 ';
            }
        } else {
            $where_sql = 'taggingmaster.created_by IN(' . $get_members_txt . ') AND taggingmaster.is_deleted=0 ';
        }

        if (!empty($tag_name)) {
            $where_sql .= ' AND taggingmaster.tag_name like "%' . $tag_name . '%"';
        }
        if (!empty($tag_contact)) {
            $where_sql .= ' AND taggingmaster.tag_phone like "%' . $tag_contact . '%"';
        }
        if (!empty($tag_tag_code)) {
            $where_sql .= ' AND taggingmaster.tag_code like "%' . $tag_tag_code . '%"';
        }
        if (!empty($tag_start_appointment_date)) {
            $where_sql .= ' AND taggingmaster.appointment_date>="' . $tag_start_appointment_date . '"';
        }
        if (!empty($tag_end_appointment_date)) {
            $where_sql .= ' AND taggingmaster.appointment_date<="' . $tag_end_appointment_date . '"';
        }

        //added on 1-7-24
        if (!empty($tag_start_budget)) {
            $where_sql .= ' AND taggingmaster.budget>="' . $tag_start_budget . '"';
        }
        if (!empty($tag_end_budget)) {
            $where_sql .= ' AND taggingmaster.budget<="' . $tag_end_budget . '"';
        }
        if (!empty($tag_flat_type_id)) {
            $where_sql .= ' AND taggingmaster.flat_type_id IN(' . $tag_flat_type_id . ')';
        }
        if (!empty($tag_sm_cp_id)) {
            $where_sql .= ' AND taggingmaster.sm_cp_id IN(' . $tag_sm_cp_id . ')';
        }

        //archive query
        /* $prev_mon_date = date("Y-m-d", strtotime("-1 month"));
        if (!empty($tag_archive)) {
            $where_sql .= ' AND (taggingmaster.appointment_date <"' . $prev_mon_date . '" AND taggingmaster.status=2)';
        } else {
            $where_sql .= ' AND taggingmaster.id NOT IN( SELECT id from taggingmaster where appointment_date < "' . $prev_mon_date . '" AND status=2)';
        } */

        if (!empty($tag_start_created_on_date)) {
            $where_sql .= ' AND DATE(taggingmaster.created_on)>="' . $tag_start_created_on_date . '"';
        }
        if (!empty($tag_end_created_on_date)) {
            $where_sql .= ' AND DATE(taggingmaster.created_on)<="' . $tag_end_created_on_date . '"';
        }
        if (!empty($tag_customer_type)) {
            $where_sql .= ' AND taggingmaster.customer_type="' . $tag_customer_type . '"';
        }



        if (!empty($tag_project_id)) {
            $where_sql .= ' AND taggingmaster.project_id IN(' . $tag_project_id . ')';
        } else {
            if ($staff_type == 2) {
                $get_sm[0] = $sm_cp_id;
                $get_proj = $this->getprojofmultism($get_sm);
                if (!empty($get_proj)) {
                    $get_proj_txt = implode(",", $get_proj);
                    $where_sql .= ' AND taggingmaster.project_id IN(' . $get_proj_txt . ')';
                }
            }
        }
        if (!empty($tag_builder_id)) {
            $where_sql .= ' AND projects.builder_id IN(' . $tag_builder_id . ')';
        }

        if (!empty($tag_cp_id)) {
            $where_sql .= ' AND taggingmaster.cp_id IN(' . $tag_cp_id . ') ';
        }

        if ($tag_status != "") {
            $where_sql .= ' AND taggingmaster.status IN(' . $tag_status . ')';
        }

        if (empty($list_type)) {
            $tag_query = (new \yii\db\Query())
                ->select('taggingmaster.id,taggingmaster.tag_code,taggingmaster.retag_limit,taggingmaster.tag_name,taggingmaster.tag_phone,taggingmaster.tagging_id,taggingmaster.lead_id,taggingmaster.tag_email,taggingmaster.flat_type_id,taggingmaster.budget,taggingmaster.customer_type,taggingmaster.appointment_date,taggingmaster.appointment_time,taggingmaster.status,taggingmaster.created_on,taggingmaster.created_by,taggingmaster.modified_on,taggingmaster.modified_by,taggingmaster.visit_notvisit_clash_date,taggingmaster.lead_convert_date,taggingmaster.lead_dead_date,taggingmaster.lead_registered_date,sm_cp.name as sourcing_id,leadmaster.lead_id,creator.name as createdby,creator.sm_cp_id as creatorid,modifier.name as modifiedby,taggingmaster.sm_cp_id,taggingmaster.project_id,cp.company_name as cp_name')
                ->from('taggingmaster')
                ->leftJoin("projects", 'taggingmaster.project_id=projects.id')
                ->leftJoin("sm_cp", 'taggingmaster.sm_cp_id=sm_cp.sm_cp_id AND sm_cp.is_deleted=0')
                ->leftJoin("channelpartner as cp", 'taggingmaster.cp_id=cp.id')
                ->leftJoin("leadmaster", 'taggingmaster.lead_id=leadmaster.id AND leadmaster.is_deleted=0')
                ->leftJoin("sm_cp as creator", 'taggingmaster.created_by=creator.sm_cp_id AND creator.is_deleted=0')
                ->leftJoin("sm_cp as modifier", 'taggingmaster.modified_by=modifier.sm_cp_id')
                ->where($where_sql)
                ->orderBy($order_name . ' ' . $order_type);
            $tag_count = $tag_query->count();
            /* echo $proj_count;
                exit; */
            $tag_data = $tag_query->limit($page_count)->offset($offset)->createCommand()
                /* ->getRawsql();
                echo $proj_data;
                exit; */
                ->queryAll();
        } else {
            $tag_query = (new \yii\db\Query())
                ->select('taggingmaster.id,taggingmaster.tag_phone,taggingmaster.tag_name,taggingmaster.tagging_id,taggingmaster.retag_limit')
                ->from('taggingmaster')
                ->where($where_sql)
                ->orderBy($order_name . ' ' . $order_type);

            $tag_data = $tag_query->createCommand()
                ->queryAll();
        }


        if (!empty($tag_data)) {
            foreach ($tag_data as $tag_data_key => $tag_data_val) {
                $tag[$tag_data_key] = $tag_data_val;

                $tag_limit_set = intval($tag_data_val['retag_limit']);
                $tag_available = intval(\Yii::$app->params['RETAG_MAX']) - $tag_limit_set;
                $tag[$tag_data_key]['retag_attempt_left'] = (string) $tag_available;

                if (empty($list_type)) {
                    $tag[$tag_data_key]['name'] = $tag_data_val['tag_name'];
                    $tag[$tag_data_key]['contact'] = $tag_data_val['tag_phone'];
                    $tag[$tag_data_key]['email'] = $tag_data_val['tag_email'];
                    $tag[$tag_data_key]['flat_type_text'] = null;
                    if (!empty($tag_data_val['flat_type_id'])) {
                        $tag[$tag_data_key]['flat_type_text'] = $this->flat_type_id[$tag_data_val['flat_type_id']];
                    } else {
                        $tag[$tag_data_key]['flat_type_id'] = null;
                    }

                    $tag[$tag_data_key]['budgetinwords'] = null;
                    if (!empty($tag_data_val['budget'])) {
                        $tag[$tag_data_key]['budget'] = (string) $tag_data_val['budget'];
                        $tag[$tag_data_key]['budgetinwords'] = $this->AmountInWords($tag_data_val['budget']);
                    } else {
                        $tag[$tag_data_key]['budget'] = null;
                    }

                    if (!empty($tag_data_val['customer_type'])) {
                        $tag[$tag_data_key]['customer_type'] = $this->customer_type[$tag_data_val['customer_type']];
                    } else {
                        $tag[$tag_data_key]['customer_type'] = null;
                    }
                    $tag[$tag_data_key]['status'] = $tag_data_val['status'];
                    $tag[$tag_data_key]['statusText'] = $this->tag_status[$tag_data_val['status']];
                    if ($tag_data_val['status'] == 1) {
                        $tag[$tag_data_key]['visited_on'] = $tag_data_val['visit_notvisit_clash_date'];
                    } else if ($tag_data_val['status'] == 3) {
                        $tag[$tag_data_key]['clashed_on'] = $tag_data_val['visit_notvisit_clash_date'];
                    } else if ($tag_data_val['status'] == 7) {
                        $tag[$tag_data_key]['rejected_on'] = $tag_data_val['visit_notvisit_clash_date'];
                    } else if ($tag_data_val['status'] == 4) {
                        $tag[$tag_data_key]['booked_on'] = $tag_data_val['lead_convert_date'];
                    } else if ($tag_data_val['status'] == 5) {
                        $tag[$tag_data_key]['lead_dead_on'] = $tag_data_val['lead_dead_date'];
                    } else if ($tag_data_val['status'] == 6) {
                        $tag[$tag_data_key]['registered_on'] = $tag_data_val['lead_registered_date'];
                    }

                    $tag[$tag_data_key]['created_by'] = !empty($tag_data_val['createdby']) ? $tag_data_val['createdby'] : null;
                    $tag[$tag_data_key]['modified_by'] = !empty($tag_data_val['modifiedby']) ? $tag_data_val['modifiedby'] : null;

                    $tag[$tag_data_key]['tag_code_content'] = null;
                    $project_model = Projects::find()->where(['id' => $tag_data_val['project_id']])->one();
                    $code_project_name = !empty($project_model) ? $project_model->name : "";
                    $code_google_link = !empty($project_model) ? $project_model->sale_address : "";
                    $tag[$tag_data_key]['project_id'] = $code_project_name;
                    if (!empty($tag_data_val['tag_code'])) {
                        $sourcing_model = SmCp::find()->where(['sm_cp_id' => $tag_data_val['creatorid'], 'is_deleted' => 0])->one();
                        $get_cp_name = !empty($sourcing_model) ? $sourcing_model->name : "";
                        $get_cp_contact = !empty($sourcing_model) ? $sourcing_model->contact : "";

                        $tag_code_content = "";

                        $tag_code_content = "Hello Sir," . PHP_EOL . "Your appointment has been scheduled at " . $code_project_name . "." . PHP_EOL . "Please Showcase appointment code *" . $tag_data_val['tag_code'] . "* at reception once you arrive." . PHP_EOL . PHP_EOL .  "In case of any help required to reach the project, you can contact *" . $get_cp_name . "* on *" . $get_cp_contact . "*." . PHP_EOL . PHP_EOL . "Regards,";

                        /* $tag_code_content = "Hello Sir," . PHP_EOL . "Your appointment has been scheduled at " . $code_project_name . "." . PHP_EOL . "Please Showcase appointment code *" . $tag_data_val['tag_code'] . "* at reception once you arrive." . PHP_EOL . PHP_EOL . "*ADITYARAJ SALES OFFICE ADDRESS:*" . "" . PHP_EOL . $code_google_link . "" . PHP_EOL . PHP_EOL . "In case of any help required to reach the project, you can contact *" . $get_cp_name . "* on *" . $get_cp_contact . "*." . PHP_EOL . PHP_EOL . "Regards,"; */
                        //$tag_code_content = trim(preg_replace('/\s+/', ' ', $tag_code_content));
                        $tag[$tag_data_key]['tag_code_content'] = $tag_code_content;
                    }



                    //get lead feedback
                    $feedData = (new \yii\db\Query())
                        ->select('fd.id,fd.feedback,fd.created_on,sm.sm_cp_id,sm.name,sm.role')
                        ->from('tagging_feedback fd')
                        ->leftJoin("sm_cp as sm", 'fd.created_by = sm.sm_cp_id AND sm.is_deleted=0')
                        ->where('fd.tagging_id="' . $tag_data_val['id'] . '"')
                        ->orderBy('fd.id DESC')
                        ->limit(5)  //show last 5 feedback
                        ->createCommand()
                        ->queryAll();
                    $feedback = null;
                    if (!empty($feedData)) {
                        $f_count = 0;
                        foreach ($feedData as $feedData_val) {
                            //$feedback[$f_count]['id'] = $feedData_val['id'];
                            $feedback[$f_count]['feedback'] = $feedData_val['feedback'];
                            $feedback[$f_count]['created_on'] = $feedData_val['created_on'];
                            //$feedback[$f_count]['sm_cp_id'] = $feedData_val['sm_cp_id'];
                            $feedback[$f_count]['created_by'] = $feedData_val['name'];
                            //$feedback[$f_count]['role'] = $this->role[$feedData_val['role']];
                            $f_count++;
                        }
                    }
                    $tag[$tag_data_key]['feedback'] = $feedback;
                    unset($tag[$tag_data_key]['tag_name'], $tag[$tag_data_key]['tag_phone'], $tag[$tag_data_key]['tag_email'], $tag[$tag_data_key]['visit_notvisit_clash_date'], $tag[$tag_data_key]['lead_convert_date'], $tag[$tag_data_key]['lead_dead_date'], $tag[$tag_data_key]['lead_registered_date'], $tag[$tag_data_key]['created_by'], $tag[$tag_data_key]['modified_by']);
                } else {
                    $tag[$tag_data_key]['name'] = $tag_data_val['tag_name'];
                    $tag[$tag_data_key]['contact'] = $tag_data_val['tag_phone'];
                    unset($tag[$tag_data_key]['tag_name'], $tag[$tag_data_key]['tag_phone']);
                }
            }
        }

        if (empty($list_type)) {
            //pagination code start
            $pgdata['page'] = $page;
            $pgdata['content_count'] = $tag_count;
            $pgdata['page_count'] = $page_count;
            $pagination = $this->getpagination($pgdata);
            //pagination code end
        }

        $tag_arr['tag'] = $tag;
        if (empty($list_type)) {
            $tag_arr['pagination'] = $pagination;
        }

        return $tag_arr;
    }

    public function gettagstatsapi($sm_cp_id, $get_type = 'cp')
    {
        $get_members = $this->getaccessmembers($sm_cp_id);
        $get_members[] = $sm_cp_id;
        $statData_arr = null;


        $get_members_txt = implode(",", $get_members);
        if ($get_type == 'cp') {
            $where_sql = " taggingmaster.created_by IN(" . $get_members_txt . ") AND taggingmaster.is_deleted=0 ";
        } else {
            $where_sql = " taggingmaster.sm_cp_id IN(" . $get_members_txt . ") AND taggingmaster.is_deleted=0 ";
        }

        $prev_mon_date = date("Y-m-d", strtotime("-1 month"));

        $where_sql .= ' AND taggingmaster.id NOT IN( SELECT id from taggingmaster where appointment_date < "' . $prev_mon_date . '" AND status=2)';

        /* $get_date = date('Y-m-d');
        $statData = [];
        $total_where_sql = $where_sql;
        $total_query = (new \yii\db\Query())
            ->select('taggingmaster.id')
            ->from('taggingmaster')
            ->where($total_where_sql);
        $total_count = $total_query->count();
        $statData['total'] = $total_count;

        $appointment_where_sql = $where_sql . " AND taggingmaster.status=0";
        $appointment_query = (new \yii\db\Query())
            ->select('taggingmaster.id')
            ->from('taggingmaster')
            ->where($appointment_where_sql);
        $appointment_count = $appointment_query->count();
        $statData['appointment'] = $appointment_count; */

        $statData = Yii::$app->db->createCommand("SELECT SUM(IF((taggingmaster.id!=''), 1, 0)) AS total, SUM(IF((taggingmaster.status=0), 1, 0)) AS appointment,SUM(IF((taggingmaster.status=1 OR taggingmaster.status=3), 1, 0)) AS visited,SUM(IF((taggingmaster.status=2), 1, 0)) AS notvisited,SUM(IF((taggingmaster.status=7), 1, 0)) AS physical_visit,SUM(IF((taggingmaster.status=6 OR taggingmaster.status=4), 1, 0)) AS booked FROM taggingmaster where " . $where_sql)->queryAll();

        if (!empty($statData)) {
            $statData_arr['stats'] = $statData[0];
        }
        return $statData_arr;
    }

    public function gettagstatsmonthlyapi($get_user, $querydata)
    {
        $sm_cp_id = $get_user->sm_cp_id;
        $get_cp_id = $get_user->channelpartner_id;
        $tag_arr = null;

        $tag = null;
        /* echo "<pre>";
        print_r($querydata);
        exit; */

        $get_members = $this->getaccessmembers($sm_cp_id);
        $get_members[] = $sm_cp_id;


        $get_members_txt = implode(",", $get_members);
        $tag_year = date('Y');
        if (!empty($querydata)) {

            $tag_year = (!empty($querydata['year']) ? trim($querydata['year']) : date('Y'));
        }

        if (!empty($get_cp_id)) {
            $where_sql = 'taggingmaster.created_by IN(' . $get_members_txt . ') AND taggingmaster.is_deleted=0 ';
        } else {
            $where_sql = 'taggingmaster.sm_cp_id IN(' . $get_members_txt . ') AND taggingmaster.is_deleted=0 ';
        }
        if (!empty($tag_year)) {
            $where_sql .= ' AND YEAR(taggingmaster.created_on)="' . $tag_year . '"';
        }

        /* $prev_mon_date = date("Y-m-d", strtotime("-1 month"));
        $where_sql .= ' AND taggingmaster.id NOT IN( SELECT id from taggingmaster where appointment_date < "' . $prev_mon_date . '" AND status=2)'; */



        $tag_query = (new \yii\db\Query())
            ->select('YEAR(created_on) AS y, MONTH(created_on) AS m, COUNT(id) as val')
            ->from('taggingmaster')
            ->where($where_sql)
            ->groupBy('y,m')
            ->orderBy('y DESC');
        $tag_data = $tag_query->createCommand()->queryAll();

        if (!empty($tag_data)) {
            foreach ($tag_data as $tag_data_key => $tag_data_val) {
                $tag[$tag_data_key]['name'] = $this->month[$tag_data_val['m']];
                $tag[$tag_data_key]['count'] = $tag_data_val['val'];

                $get_date = $tag_data_val['y'] . '-' . $tag_data_val['m'] . '-' . '01';
                $date = new DateTime($get_date);
                $date->modify('last day of this month');
                $get_last_day = $date->format('Y-m-d');

                $tag[$tag_data_key]['start_created_on_date'] = $get_date;
                $tag[$tag_data_key]['end_created_on_date'] = $get_last_day;
            }
        }

        $tag_arr['stats']['monthwise'] = $tag;

        return $tag_arr;
    }

    public function getmarketlistapi($get_user, $querydata)
    {
        $cp_id = $get_user->channelpartner_id;
        $builder_id = $get_user->builder_id;
        $sm_cp_id = $get_user->sm_cp_id;
        $market_arr = null;

        $pagination = null;
        $market = null;

        $get_proj = array();
        if (!empty($cp_id)) {
            $get_sm = $this->getsmofcp($cp_id);
            if (!empty($get_sm)) {
                $get_proj = $this->getprojofmultism($get_sm);
            }
        }
        /* if (!empty($get_proj)) {

            $get_proj_txt = implode(",", $get_proj);
        } */
        $market_start_campaign_date = '';
        $market_end_campaign_date = '';
        if (!empty($querydata)) {

            $market_name = (!empty($querydata['name']) ? trim($querydata['name']) : '');
            $market_project_id = (!empty($querydata['project_id']) ? implode(",", $querydata['project_id']) : []);
            /* $market_start_campaign_date = (!empty($querydata['start_campaign_date']) ? trim($querydata['start_campaign_date']) : '');
            $market_end_campaign_date = (!empty($querydata['end_campaign_date']) ? trim($querydata['end_campaign_date']) : '');
            $market_start_created_on_date = (!empty($querydata['start_created_on_date']) ? trim($querydata['start_created_on_date']) : '');
            $market_end_created_on_date = (!empty($querydata['end_created_on_date']) ? trim($querydata['end_created_on_date']) : ''); */
        }

        $order_name = (isset($querydata['sort_name']) ? 'marketing_schedule.' . trim($querydata['sort_name']) : 'marketing_schedule.id');
        $order_type = (isset($querydata['sort_type']) ? trim($querydata['sort_type']) : 'DESC');


        $page_count = (isset($querydata['page_count']) ? trim($querydata['page_count']) : 25);
        $page = (isset($querydata['page']) ? trim($querydata['page']) : 1);
        if ($page == 1) {
            $offset = 0;
        } else {
            $offset = (($page - 1) * $page_count);
        }

        /* $where_sql = 'marketing_schedule.project_id IN(' . $get_proj_txt . ') AND marketing_schedule.status=1 AND marketing_campaign.status=1'; */
        $where_sql = 'marketing_schedule.status=1 AND marketing_campaign.status=1';
        if (!empty($market_name)) {
            $where_sql .= ' AND marketing_schedule.name like "%' . $market_name . '%"';
        }
        if (!empty($market_project_id)) {
            $where_sql .= ' AND marketing_campaign.project_id IN(' . $market_project_id . ')';
        }

        if (!empty($builder_id)) {
            $where_sql .= ' AND projects.builder_id IN(' . $builder_id . ')';
        }

        /* if (!empty($market_start_campaign_date)) {
            $where_sql .= ' AND marketing_schedule.start_date>="' . $market_start_campaign_date . '"';
        }
        if (!empty($market_end_campaign_date)) {
            $where_sql .= ' AND marketing_schedule.start_date<="' . $market_end_campaign_date . '"';
        }

        if (!empty($market_start_created_on_date)) {
            $where_sql .= ' AND DATE(marketing_schedule.created_on)>="' . $market_start_created_on_date . '"';
        }
        if (!empty($market_end_created_on_date)) {
            $where_sql .= ' AND DATE(marketing_schedule.created_on)<="' . $market_end_created_on_date . '"';
        } */

        $where_sql .= ' AND DATE("' . date('Y-m-d') . '") BETWEEN marketing_campaign.start_date AND marketing_campaign.end_date';




        $market_query = (new \yii\db\Query())
            ->select(
                'marketing_schedule.id,marketing_schedule.campaign_id,projects.name as projectname,marketing_campaign.project_id,marketing_campaign.start_date,marketing_campaign.end_date,marketing_schedule.created_on,marketing_schedule.website,marketing_schedule.name as title,marketing_schedule.brief as schedule_brief,marketing_campaign.feedback as campaign_feedback'
            )
            ->from('marketing_schedule')
            ->leftJoin("marketing_campaign", 'marketing_schedule.campaign_id=marketing_campaign.id')
            ->leftJoin("projects", 'marketing_campaign.project_id=projects.id')
            //->leftJoin("sm_cp as creator", 'marketing.created_by=creator.sm_cp_id')
            //->leftJoin("sm_cp as modifier", 'marketing.modified_by=modifier.sm_cp_id')
            ->where($where_sql)
            ->orderBy($order_name . ' ' . $order_type);
        $market_count = $market_query->count();
        /* echo $proj_count;
                exit; */
        $market_data = $market_query->limit($page_count)->offset($offset)->createCommand()
            /* ->getRawsql();
                echo $market_data;
                exit; */
            ->queryAll();

        if (!empty($market_data)) {
            foreach ($market_data as $market_data_key => $market_data_val) {
                $market[$market_data_key] = $market_data_val;
                $databrief = '';
                if (!empty($market_data_val['schedule_brief'])) {
                    $databrief = $market_data_val['schedule_brief'];
                }
                if (empty($databrief)) {
                    if (!empty($market_data_val['campaign_feedback'])) {
                        $databrief = $market_data_val['campaign_feedback'];
                    }
                }


                $sm_connected = 'false';
                if (!empty($get_proj)) {
                    if (in_array($market_data_val['project_id'], $get_proj)) {
                        $sm_connected = 'true';
                    }
                }
                $market[$market_data_key]['sm_connected'] = $sm_connected;



                if (!empty($databrief)) {
                    $get_camp_brief = trim(preg_replace('/\s+/', ' ', $databrief));
                    $market[$market_data_key]['brief'] = $get_camp_brief;
                } else {
                    $market[$market_data_key]['brief'] = null;
                }

                $get_campaign_content_arr = null;
                $get_campaign_content_data = MarketingCampaignContent::find()->select('content')->where(['schedule_id' => $market_data_val['id']])->asArray()->all();
                if (!empty($get_campaign_content_data)) {
                    $c_count = 0;
                    foreach ($get_campaign_content_data as $get_campaign_content_data_val) {
                        $get_campaign_content_arr[$c_count]['link'] = \Yii::$app->params['web_path'] . 'files/marketing/' . $get_campaign_content_data_val['content'];
                        $c_count++;
                    }
                    $market[$market_data_key]['content'] = $get_campaign_content_arr;
                }

                //get sourcing
                $sourcingData = (new \yii\db\Query())
                    ->select('sm.sm_cp_id,sm.name,sm.role,sm.contact')
                    ->from('sm_projects sp')
                    ->leftJoin("sm_cp as sm", 'sp.sm_cp_id = sm.sm_cp_id AND sm.is_deleted=0')
                    ->where('FIND_IN_SET("' . (int) $market_data_val['project_id'] . '",projects_id) AND sp.status=1 AND sm.role is not null')->groupBy('sp.sm_cp_id')->createCommand()
                    ->queryAll();
                $sourcing = null;
                $sourcingbyrole = null;
                $final_sourcing = null;
                /* var_dump($sourcingData);
                exit; */
                if (!empty($sourcingData)) {
                    $s_count = 0;
                    foreach ($sourcingData as $sourcingData_val) {
                        $sourcing[$s_count]['sm_cp_id'] = $sourcingData_val['sm_cp_id'];
                        $sourcing[$s_count]['name'] = $sourcingData_val['name'];
                        $sourcing[$s_count]['role'] = $this->role[$sourcingData_val['role']];
                        $sourcing[$s_count]['contact'] = $sourcingData_val['contact'];
                        $sourcingbyrole[$sourcingData_val['role']] = $sourcing[$s_count];
                        $s_count++;
                    }
                    //Show executive first, then manager then Leader
                    if (isset($sourcingbyrole[3])) {
                        $final_sourcing[0] = $sourcingbyrole[3];
                    } else if (isset($sourcingbyrole[2])) {
                        $final_sourcing[0] = $sourcingbyrole[2];
                    } else if (isset($sourcingbyrole[1])) {
                        $final_sourcing[0] = $sourcingbyrole[1];
                    }
                }
                $market[$market_data_key]['sourcing'] = $final_sourcing;

                unset($market[$market_data_key]['campaign_id'], $market[$market_data_key]['schedule_brief'], $market[$market_data_key]['campaign_feedback']);
            }
        }


        //pagination code start
        $pgdata['page'] = $page;
        $pgdata['content_count'] = $market_count;
        $pgdata['page_count'] = $page_count;
        $pagination = $this->getpagination($pgdata);
        //pagination code end


        /* echo "<pre>";
                print_r($project);
                exit; */



        $market_arr['marketing'] = $market;
        $market_arr['pagination'] = $pagination;


        return $market_arr;
    }

    public function getcpnetwork($get_user, $querydata, $showstatus = 1, $list_type = '')
    {
        $get_sm_cp_id = $get_user->sm_cp_id;
        $get_builder_id = $get_user->builder_id;

        $network_arr = null;
        if (empty($list_type)) {
            $pagination = null;
        }
        $network = null;
        $show_network = true;
        /* echo "<pre>";
        print_r($querydata);
        exit; */
        if (empty($get_builder_id)) {
            $show_network = false;
        }

        if ($show_network) {


            if (!empty($querydata)) {

                $cp_company_name = (!empty($querydata['company_name']) ? trim($querydata['company_name']) : '');
                $cp_rera = (!empty($querydata['rera_no']) ? trim($querydata['rera_no']) : '');
                $cp_contact = (!empty($querydata['contact']) ? trim($querydata['contact']) : '');
                $cp_status = (!empty($querydata['status']) ? trim($querydata['status']) : '');
            }

            $order_name = (isset($querydata['sort_name']) ? trim($querydata['sort_name']) : 'cp.company_name');
            $order_type = (isset($querydata['sort_type']) ? trim($querydata['sort_type']) : 'ASC');


            $page_count = (isset($querydata['page_count']) ? trim($querydata['page_count']) : 25);
            $page = (isset($querydata['page']) ? trim($querydata['page']) : 1);
            if ($page == 1) {
                $offset = 0;
            } else {
                $offset = (($page - 1) * $page_count);
            }

            if (empty($cp_status)) {
                $where_sql = 'sm_cp_network.status="' . $showstatus . '" ';
            } else {
                $where_sql = 'sm_cp_network.status="' . $cp_status . '" ';
            }

            $where_sql .= 'AND sm_cp_network.sm_cp_id="' . $get_sm_cp_id . '" AND cp.status=1 ';
            if (!empty($cp_company_name)) {
                $where_sql .= ' AND cp.company_name like "%' . $cp_company_name . '%"';
            }
            if (!empty($cp_contact)) {
                $where_sql .= ' AND cp.contact like "%' . $cp_contact . '%"';
            }
            if (!empty($cp_rera)) {
                $where_sql .= ' AND cp.rera_number="' . $cp_rera . '"';
            }



            if (empty($list_type)) {


                $sort_text = $order_name . ' ' . $order_type;


                $network_query = (new \yii\db\Query())
                    ->select('sm_cp_network.network_id,sm_cp_network.request_sent,sm_cp_network.joined_date,sm_cp_network.channelpartner_id,cp.company_name,cp.contact,cp.name,cp.rera_number as rera_no')
                    ->from('sm_cp_network')
                    ->leftJoin("channelpartner as cp", 'sm_cp_network.channelpartner_id = cp.id')
                    ->where($where_sql)
                    ->orderBy($sort_text);
                $network_count = $network_query->count();
                /* echo $proj_count;
                exit; */
                $network_data = $network_query->limit($page_count)->offset($offset)->createCommand()
                    /* ->getRawsql();
                    echo $proj_data;
                    exit; */
                    ->queryAll();
            } else {
                $network_query = (new \yii\db\Query())
                    ->select('cp.id,cp.company_name,cp.contact,cp.name')
                    ->from('sm_cp_network')
                    ->leftJoin("channelpartner as cp", 'sm_cp_network.channelpartner_id = cp.id')
                    ->where($where_sql)
                    ->orderBy($order_name . ' ' . $order_type);

                $network_data = $network_query->createCommand()
                    ->queryAll();
            }

            /* echo "<pre>";
                print_r($proj_data);
                exit; */
            if (!empty($network_data)) {
                //$check_proj_count = 0;      //added for testing
                //$check_multi_count = 1;     //added for testing
                //while ($check_multi_count < 6) {    //added for testing
                foreach ($network_data as $network_data_key => $network_data_val) {
                    //$proj_data_key = $check_proj_count;     //added for testing
                    $network[$network_data_key] = $network_data_val;

                    if ($showstatus == 3) {
                        unset($network[$network_data_key]['joined_date']);
                    } else if ($showstatus == 1) {
                        unset($network[$network_data_key]['request_sent']);
                    }

                    /*  if (empty($list_type)) {
                        unset($project[$proj_data_key]['logo_name'], $project[$proj_data_key]['low_price'], $project[$proj_data_key]['builder_id'], $project[$proj_data_key]['flat_types'], $project[$proj_data_key]['flat_property_types'],  $project[$proj_data_key]['latlong']);
                    } */

                    //$check_proj_count++;    //added for testing
                }
                //$check_multi_count++;       //added for testing
                //}       //added for testing
            }

            /* echo "<pre>";
                print_r($project);
                exit; */

            if (empty($list_type)) {
                //pagination code start
                $pgdata['page'] = $page;
                //$pgdata['content_count'] = $proj_count * 5;     //added for testing
                $pgdata['content_count'] = $network_count;
                $pgdata['page_count'] = $page_count;
                $pagination = $this->getpagination($pgdata);
                //pagination code end
            }

            /* echo "<pre>";
                print_r($project);
                exit; */
            //}
        }

        $network_arr['network'] = $network;
        if (empty($list_type)) {
            $network_arr['pagination'] = $pagination;
        }

        return $network_arr;
    }

    public function checkmembercount($cp_id)
    {
        $check_query = (new \yii\db\Query())
            ->select('sm_cp.sm_cp_id')
            ->from('sm_cp')
            ->where("sm_cp.channelpartner_id='" . $cp_id . "' AND sm_cp.status=1");

        $user_count = $check_query->count();
        return $user_count;
    }


    function AmountInWords($get_amount)
    {
        $show_aount = '';
        if ($get_amount >= 1000000 && $get_amount < 10000000) {
            $get_digit = substr($get_amount, 0, 2);
            $get_inner_digit = intval(substr($get_amount, 2, 2));
            if ($get_inner_digit > 0) {
                $show_aount = $get_digit . "." . $get_inner_digit . " L";
            } else {
                $show_aount = $get_digit . " L";
            }
        } else if ($get_amount >= 10000000 && $get_amount < 100000000) {
            $get_digit = substr($get_amount, 0, 1);
            $get_inner_digit = intval(substr($get_amount, 1, 2));
            if ($get_inner_digit < 10 && $get_inner_digit > 0) {
                $get_inner_digit = "0" . $get_inner_digit;
            }
            if ($get_inner_digit > 0) {
                $show_aount = $get_digit . "." . $get_inner_digit . " Cr";
            } else {
                $show_aount = $get_digit . " Cr";
            }
        } else if ($get_amount >= 100000000 && $get_amount < 1000000000) {
            $get_digit = substr($get_amount, 0, 2);
            $get_inner_digit = intval(substr($get_amount, 2, 2));
            if ($get_inner_digit > 0) {
                $show_aount = $get_digit . "." . $get_inner_digit . " Cr";
            } else {
                $show_aount = $get_digit . " Cr";
            }
        } else {
            $get_digit = substr($get_amount, 0, 3);
            $get_inner_digit = intval(substr($get_amount, 2, 2));
            if ($get_inner_digit > 0) {
                $show_aount = $get_digit . "." . $get_inner_digit . " Cr";
            } else {
                $show_aount = $get_digit . " Cr";
            }
        }
        return $show_aount;
    }

    // Create a function for converting the amount in words
    function AmountInWordsfull($amount)
    {
        $num = $amount;
        $amt_hundred = null;
        $count_length = strlen($num);
        $x = 0;
        $string = array();
        $change_words = array(
            0 => '',
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
            4 => 'Four',
            5 => 'Five',
            6 => 'Six',
            7 => 'Seven',
            8 => 'Eight',
            9 => 'Nine',
            10 => 'Ten',
            11 => 'Eleven',
            12 => 'Twelve',
            13 => 'Thirteen',
            14 => 'Fourteen',
            15 => 'Fifteen',
            16 => 'Sixteen',
            17 => 'Seventeen',
            18 => 'Eighteen',
            19 => 'Nineteen',
            20 => 'Twenty',
            30 => 'Thirty',
            40 => 'Forty',
            50 => 'Fifty',
            60 => 'Sixty',
            70 => 'Seventy',
            80 => 'Eighty',
            90 => 'Ninety'
        );
        $here_digits = array('', 'Hundred', 'Thousand', 'Lakh', 'Crore');
        while ($x < $count_length) {
            $get_divider = ($x == 2) ? 10 : 100;
            $amount = floor($num % $get_divider);
            $num = floor($num / $get_divider);
            $x += $get_divider == 10 ? 1 : 2;
            if ($amount) {
                $add_plural = (($counter = count($string)) && $amount > 9) ? 's' : null;
                $amt_hundred = ($counter == 1 && $string[0]) ? ' and ' : null;
                $string[] = ($amount < 21) ? $change_words[$amount] . ' ' . $here_digits[$counter] . $add_plural . ' ' . $amt_hundred : $change_words[floor($amount / 10) * 10] . ' ' . $change_words[$amount % 10] . ' ' . $here_digits[$counter] . $add_plural . ' ' . $amt_hundred;
            } else $string[] = null;
        }
        $implode_to_Rupees = implode('', array_reverse($string));
        return ($implode_to_Rupees ? trim($implode_to_Rupees) : '');
    }
}
