<?php
require_once __DIR__.'/include/autoload.php';
require_once __DIR__.'/include/Property.Class.php';
require_once __DIR__.'/include/MYB.Class.php';
require_once __DIR__.'/include/Page.Class.php';
require_once __DIR__.'/include/Vtiger.Class.php';

header('Content-type: application/json');

$Page = new Page();

$param = array_to_obj($param);
$controller = $param->controller;
$action     = $param->action;
$id         = $param->id;

$date_start     = request_ifset('date_start');
$date_end       = request_ifset('date_end');
$filter         = request_ifset('filter');
$value          = request_ifset('value');

$MYB = new MYBrokerage();



switch($controller){


    

    case 'user': {
        switch($action){        
            case 'search':
                echo $MYB->Search_Users($id);
            break;
            case 'data':
                echo $MYB->GetUser($id);
            break;
            case 'edit':
                
                $prep = new stdClass();
                
                
                $prep->id                         = $id;

                if(!empty(request_ifset('new_pswd')) && (request_ifset('new_pswd') == request_ifset('new_pswd_verify'))){
                	$prep->pswd                       = better_crypt(request_ifset('new_pswd'));
                }
                $prep->cell                       = request_ifset('cell');
                $prep->quote                      = request_ifset_removern('quote');
                $prep->fb                         = request_ifset('fb');
                $prep->linkedin                   = request_ifset('linkedin');
                $prep->hobbies_content            = request_ifset_removern('hobbies_content');
                $prep->carriera_content           = request_ifset_removern('carriera_content');
                $prep->mipiace_content            = request_ifset_removern('mipiace_content');
                $prep->awards_content             = request_ifset_removern('awards_content');
                $prep->corsi_content              = request_ifset_removern('corsi_content');
                $prep->telegram_id                = request_ifset('telegram_id');
                $prep->daily_target               = request_ifset('daily_target');
                $prep->leads_notify               = request_ifset('leads_notify');
                
                if(is_backoffice()){
                    $prep->org_unit_id                  = request_ifset('org_unit_id');
                    $prep->team_id                    = request_ifset('team_id');
                    $prep->status                     = request_ifset('status');
                    $prep->name                       = request_ifset('name');
                    $prep->email                      = request_ifset('email');
                    $prep->job_title                  = request_ifset('job_title');
                    $prep->role                       = request_ifset('role');
                    $prep->crm_id                     = request_ifset('crm_id');
                    $prep->data_contratto             = request_ifset('data_contratto');
                    $prep->piano                      = request_ifset('piano');
                    $prep->team_leader_id             = request_ifset('team_leader_id');
                    $prep->maximizer_uid              = request_ifset('maximizer_uid');
                    $prep->wa_access_token            = request_ifset('wa_access_token');
                    $prep->wac_subscription            = request_ifset('wac_subscription');

                    //$prep->company_id                 = request_ifset('company_id');                    
                }
               
               
                
                
                $values = PrepSQLValues($prep);
                echo $MYB->InsertOrUpdate($values, "users");
                
            break;
            
            case 'delete':
                if(is_backoffice()){
                    echo $MYB->Delete($id, 'users');
                }
            break;
            
            case 'disable':
                if(is_backoffice()){

                    echo $MYB->SoftDelete($id, 'users');
               }
            break;
            
        }
    break;
    }

   
    case 'UI': {
        switch($action){        
            
            case 'fieldUpdate':
                
                
                $module = $id;
                $fieldname = request_ifset('name');
                $value = request_ifset('value');
                $primarykey = request_ifset('pk');


                switch($module){
                    case 'contacts': {

                        $Contact = $MYB->GetContact($primarykey, true, 'obj');

                           
                            $prep = new stdClass();
                            $prep->id = $primarykey;
                            $prep->{$fieldname} = $value;
                            
                            $values = PrepSQLValues($prep);
                            $result =  $MYB->InsertOrUpdate($values, 'contacts');

                            $AuditLog = $MYB->NewAuditLog(
                                $module, // module
                                $primarykey, // id
                                2, // 1 = create, 2 = update, 3 = delete
                                $fieldname, // field (optional)
                                $Contact->{$fieldname}, // postvalue (optional)
                                $value // postvalue (optional)
                            );
                    }
                    break;
                    case 'potentials': {

                        $Potential = $MYB->GetPotential($primarykey, 'obj');

                           
                            $prep = new stdClass();
                            $prep->id = $primarykey;
                            $prep->{$fieldname} = $value;
                            
                            $values = PrepSQLValues($prep);
                        
                            $result =  $MYB->InsertOrUpdate($values, 'crm_potentials');

                            $AuditLog = $MYB->NewAuditLog(
                                $module, // module
                                $primarykey, // id
                                2, // 1 = create, 2 = update, 3 = delete
                                $fieldname, // field (optional)
                                $Potential->{$fieldname}, // postvalue (optional)
                                $value // postvalue (optional)
                            );
                    }
                    break;
                    case 'scoutings': {

                        $Potential = $MYB->GetPotential($primarykey, 'obj');

                           
                            $prep = new stdClass();
                            $prep->id = $primarykey;
                            $prep->{$fieldname} = $value;
                            
                            $values = PrepSQLValues($prep);
                        
                            $result =  $MYB->InsertOrUpdate($values, 'potentials');

                            $AuditLog = $MYB->NewAuditLog(
                                $module, // module
                                $primarykey, // id
                                2, // 1 = create, 2 = update, 3 = delete
                                $fieldname, // field (optional)
                                $Potential->{$fieldname}, // postvalue (optional)
                                $value // postvalue (optional)
                            );
                    }
                    break;

                }
                if(is_numeric($result) && $result !== 0) echo $result;
                else  http_response_code(403);
                
            break;
            
        }
    break;
    }


    case 'wascript':{
    
        
    switch($action){    

            
            case 'data':
            
                if(request_ifset('buyerlead_id') || request_ifset('potential_id')){
          
                    if(request_ifset('buyerlead_id')){
                        $ScriptInfo[0] =  $MYB->GetWAScript($id, false, 'obj');
                        $ScriptInfo[0]->content = replace_placeholder($ScriptInfo[0]->content, request_ifset('buyerlead_id'));
                        echo json_encode($ScriptInfo);
                    }

                    if(request_ifset('potential_id')) {
                        $ScriptInfo[0] =  $MYB->GetWAScript($id, false, 'obj');
                        $ScriptInfo[0]->content = replace_placeholder($ScriptInfo[0]->content, false, false, request_ifset('potential_id'));
                        echo json_encode($ScriptInfo);

                    }

                } else {
                    echo $MYB->GetWAScript($id);

                }
        
            break;
            case 'save':
                
                $prep = new stdClass();

                if($id !== 'new') {
                    $prep->id                   = $id;
                } else {
                    $prep->user_id                  = $User->id;
                }
                $prep->company_id               = COMPANY_ID;
                $prep->name                     = request_ifset('name');
                $prep->content                  = request_ifset('content');
                $prep->status = 1;
                $prep->type                     = request_ifset('type');

                if($_FILES['file']['tmp_name']) {
                    $MediaFilename = GenRandomString(20);
                    $UploadMedia =  upload_file($_FILES['file'], __DIR__."/files_generated/".FCID."/MediaUploads/", $MediaFilename);
                    $prep->media = $UploadMedia['basename'];
                }
                $values = PrepSQLValues($prep);
                $WAScript_ID =  $MYB->InsertOrUpdate($values, "wa_scripts");     
                echo $WAScript_ID;
                
                if(request_ifset('related_to_entity') && request_ifset('related_to_entity_id')){
                    $prepRelated = new stdClass();
                    $prepRelated->id = request_ifset('related_to_entity_id');
                    $prepRelated->script_id = $WAScript_ID;
                    $valuesRelated = PrepSQLValues($prepRelated);
                    $MYB->InsertOrUpdate($valuesRelated, request_ifset('related_to_entity'));     

                }
            

            break;
            case 'mediaDelete':
                
                $ScriptInfo = $MYB->GetWAScript($id, 'obj');
                if($User->id == $ScriptInfo->user_id || is_backoffice()){
                    $prep = new stdClass();
                    $prep->id                   = $id;
                    $prep->media                = NULL;
                    $values = PrepSQLValues($prep);
                    echo $result =  $MYB->InsertOrUpdate($values, 'wa_scripts');
                }
            break;
    
            case 'delete':
                
                $ScriptInfo = $MYB->GetWAScript($id, 'obj');
                if($User->id == $ScriptInfo->user_id || is_backoffice()){
                    echo $MYB->Delete($id, "wa_scripts");
                }
            break;
        }
        break;
    }


 

    case 'proposals':{
    
        
        switch($action){        
                
              
                case 'delete':
                    
                    if(is_admin()){
                        echo $MYB->Delete($id, "proposals");
                    }
                break;
            }
            break;
        }


    case 'potentials':{

        switch($action){        



                case 'save':
                
                    $prep = new stdClass();
                    if(request_ifset('status')) $prep->status = request_ifset('status');
                        else $prep->status                   = '1';
                    
                    if(request_ifset('assigned_to')) $prep->assigned_to = request_ifset('assigned_to');
                        else $prep->assigned_to              = $User->id;
                    
                    $tel = request_ifset('tel');
                    $name = request_ifset('name');

                    if(request_ifset('contact_id')) { 
                        $contact_id = request_ifset('contact_id');
                    } else {
                        $contact_id = $MYB->NewContact($name, $tel, false, false, request_ifset('source_id'));
                    }


                    $prep->contact_id               = $contact_id;
                    $prep->opportunity_name         = request_ifset('opportunity_name');
                    $prep->opportunity_type         = request_ifset('opportunity_type');
                    $prep->zone_id                  = request_ifset('zone_id');
                    $prep->source_id                = request_ifset('source_id');
                    $prep->source_url               = request_ifset('source_url');
                    $prep->price                    = request_ifset('price');
                    $prep->description              = request_ifset('description');
                    $prep->company_id               = COMPANY_ID;

                    $values = $MYB->PrepSQLValues($prep);
                    echo $MYB->InsertOrUpdate($values, "crm_potentials");
                
                break;

                case 'checkByMobile':{
                    
                    $data = new stdClass();
                    $data->data = $MYB->CheckFreePotential($id, $User->id, request_ifset('bypass_mine'));
                    
                    
                    echo json_encode($data);
                }
                break;

                case 'delete':
                
                        if(!is_backoffice()){

                            $PotentialInfo = $MYB->GetPotential($id, 'obj');
                            if($PotentialInfo->assigned_to !== $User->id) die('OPERAZIONE NEGATA');
                        } 
                        echo $MYB->SoftDelete($id, "crm_potentials");
                        
                break;

                case 'getList':{
                    $draw = $_REQUEST['draw'];
                    $row = $_REQUEST['start'];
                    $rowperpage = $_REQUEST['length']; // Rows display per page
                    $columnIndex = $_REQUEST['order'][0]['column']; // Column index
                    $columnName = $_REQUEST['columns'][$columnIndex]['data']; // Column name
                    $columnSortOrder = $_REQUEST['order'][0]['dir']; // asc or desc
                    $searchValue = my_escape($_REQUEST['search']['value']); // Search value

                    if($row && $rowperpage)
                        $limit = "{$row},{$rowperpage}";


                    $where = false;
    
                    foreach($_POST['columns'] as $col ){
    
                        $search_value='';
                        if(!empty($col['search']['value'])){
                            $search_value = str_replace('((((', '', $col['search']['value']);
                            $search_value = str_replace('))))', '', $search_value);
    
                            $operator = 'LIKE';
                            $search_value = "'%{$search_value}%'";
                            $field = $col['data'];
                            switch($col['data']){
                                case 'date':
                                    $field = 'ts';
                                break;
                                
                                
                            }
    
                            $where.= "{$field} {$operator} {$search_value}";
                        }
                    }
    
                    if($searchValue) {
                        //$where = " AND (CONCAT(r.id, ' ', name, ' ', r.contact, ' ', r.email, ' ', r.id_immobile, ' ', r.status, ' ', r.note, ' ', imm.address, ' ', imm.city, ' ', imm.consulente) LIKE '%{$searchValue}%')";    
                    }
    
                    
                    $response = $MYB->GetPotentials($User->id, $where, $limit, 'ssp');
                    $response["draw"] = intval($draw);
    
                    $response = json_encode($response);
                    echo $response;     
                    break;
                }


                case 'getListv2':{ //potentials
                    $draw = $_REQUEST['draw'];
                    $row = $_REQUEST['start'];
                    $rowperpage = $_REQUEST['length']; // Rows display per page
                    $columnIndex = $_REQUEST['order'][0]['column']; // Column index
                    $columnSortOrder = $_REQUEST['order'][0]['dir']; // asc or desc
                    $searchValue = my_escape($_REQUEST['search']['value']); // Search value
                    $filterOutStatusZero = TRUE;
                    $cid = request_ifset('cid');

                    if(!empty($row) && !empty($rowperpage)) {
                        $limit = "{$row},{$rowperpage}";
                    } 


                    $where = "1=1";
    
                    foreach($_POST['search'] as $search ){
    
                        $search_value='';

                        if($search['name'] == 'status'){
                            $filterOutStatusZero = FALSE;
                        } 

                        
                        if(!empty($search['value']) OR $search['value'] == 0){
                            switch($search['name']){
                                case 'id':

                                    $field = $search['name'];
                                    $operator = 'LIKE';
                                    $search['value'] = str_replace("POT", "", $search['value']);
                                    $search_value = "'%{$search['value']}%'";
    
                                break;
                                case 'status':

                                    $field = $search['name'];
                                    $operator = '=';
                                    $search_value = "'{$search['value']}'";

                                break;
                                case 'createdtime_daterange':
                                case 'modifiedtime_daterange':

                                    $dates = DateRange_to_Dates($search['value']);
                                    $date_start = $dates[0];
                                    $date_end = $dates[1];

                                    $field_explode = explode('_', $search['name']);
                                    $field = $field_explode[0];
                                    $operator = 'BETWEEN';
                                    $search_value = "'{$date_start} 00:00:00' AND '{$date_end} 23:59:59'";
                                    
                                break;

                                case 'tags':

                                    $tags_filter[] = $search['value'];

                                break;
                                default:

                                    $field = $search['name'];
                                    $operator = 'LIKE';
                                    $search_value = "'%{$search['value']}%'";

                                break;

                            }

                             if($field && $operator && $search_value){
                                $where.= " AND {$field} {$operator} {$search_value}";
                             }
                        }
  
                    }

                    if($tags_filter){
                        $tags_filter_csv = array_to_csv($tags_filter);
                        $where.= " AND FIND_IN_SET(id, (SELECT GROUP_CONCAT(entity_id) FROM tags_relations WHERE entity = 'potentials' AND tag_id IN ($tags_filter_csv)))";

                    }

                
    
                    if($searchValue) {
                        //$where = " AND (CONCAT(r.id, ' ', name, ' ', r.contact, ' ', r.email, ' ', r.id_immobile, ' ', r.status, ' ', r.note, ' ', imm.address, ' ', imm.city, ' ', imm.consulente) LIKE '%{$searchValue}%')";    
                    }
    
                    if($filterOutStatusZero){
                        $where.= " AND status != 0";
                    }
                    if($cid) {
                        $where.= " AND contact_id = '{$cid}'";
                    }
    

                    $response = $MYB->GetPotentials($User->id, $where, $limit, 'ssp');
                    $response["draw"] = intval($draw);
    
                    $response = json_encode($response);
                    echo $response;     
                    break;
                }
            }
            break;
        }
        case 'scoutings':{

            switch($action){        
    
    
    
                    case 'save':
                    
                        $prep = new stdClass();
                        $prep->cens_date                = request_ifset('cens_date');
                        $prep->agent_id                 = $User->id;
                        $prep->status                   = request_ifset('status');
                        $prep->scouting_type            = request_ifset('scouting_type');
                        $prep->zone_id                  = request_ifset('zone_id');
                        $prep->info_source_id           = request_ifset('info_source_id');
                        $prep->link                 = request_ifset('link');
                        $prep->pot_price            = request_ifset('pot_price');
                        $prep->scouting_address            = request_ifset('scouting_address');
                        $prep->scouting_number            = request_ifset('scouting_number');
                        $prep->scouting_int            = request_ifset('scouting_int');
                        $prep->scouting_owner_name            = request_ifset('scouting_owner_name');
                        $prep->scouting_cf          = request_ifset('scouting_cf');
                        $prep->notes            = request_ifset('notes');
    
                        $values = $MYB->PrepSQLValues($prep);
                        echo $MYB->InsertOrUpdate($values, "potentials");
                    
                    break;

                    case 'delete':
                    
                            echo $MYB->Delete($id, "potentials");
                        
                    break;

    
                    case 'getList':{ //scoutings
                        $draw = $_REQUEST['draw'];
                        $row = $_REQUEST['start'];
                        $rowperpage = $_REQUEST['length']; // Rows display per page
                        $columnIndex = $_REQUEST['order'][0]['column']; // Column index
                        $columnSortOrder = $_REQUEST['order'][0]['dir']; // asc or desc
                        $searchValue = my_escape($_REQUEST['search']['value']); // Search value
                        $filterOutStatusZero = TRUE;
                        $cid = request_ifset('cid');
    
                        if(!empty($row) && !empty($rowperpage)) {
                            $limit = "{$row},{$rowperpage}";
                        } 
    
    
                        $where = "1=1";
        
                        foreach($_POST['search'] as $search ){
        
                            $search_value='';
    
                            if($search['name'] == 'status'){
                                $filterOutStatusZero = FALSE;
                            } 
    
                            
                            if(!empty($search['value']) OR $search['value'] == 0){
                                switch($search['name']){
                                    case 'id':
    
                                        $field = $search['name'];
                                        $operator = 'LIKE';
                                        $search['value'] = str_replace("SCO", "", $search['value']);
                                        $search_value = "'%{$search['value']}%'";
        
                                    break;
                                    case 'status':
    
                                        $field = $search['name'];
                                        $operator = '=';
                                        $search_value = "'{$search['value']}'";
    
                                    break;
                                    case 'createdtime_daterange':
                                    case 'modifiedtime_daterange':
    
                                        $dates = DateRange_to_Dates($search['value']);
                                        $date_start = $dates[0];
                                        $date_end = $dates[1];
    
                                        $field_explode = explode('_', $search['name']);
                                        $field = $field_explode[0];
                                        $operator = 'BETWEEN';
                                        $search_value = "'{$date_start} 00:00:00' AND '{$date_end} 23:59:59'";
                                        
                                    break;
    
                                    case 'tags':
    
                                        $tags_filter[] = $search['value'];
    
                                    break;
                                    default:
    
                                        $field = $search['name'];
                                        $operator = 'LIKE';
                                        $search_value = "'%{$search['value']}%'";
    
                                    break;
    
                                }
    
                                 if($field && $operator && $search_value){
                                    $where.= " AND {$field} {$operator} {$search_value}";
                                 }
                            }
      
                        }
    
                        if($tags_filter){
                            $tags_filter_csv = array_to_csv($tags_filter);
                            $where.= " AND FIND_IN_SET(id, (SELECT GROUP_CONCAT(entity_id) FROM tags_relations WHERE entity = 'potentials' AND tag_id IN ($tags_filter_csv)))";
    
                        }
    
                    
        
                        if($searchValue) {
                            //$where = " AND (CONCAT(r.id, ' ', name, ' ', r.contact, ' ', r.email, ' ', r.id_immobile, ' ', r.status, ' ', r.note, ' ', imm.address, ' ', imm.city, ' ', imm.consulente) LIKE '%{$searchValue}%')";    
                        }
        
                        if($filterOutStatusZero){
                            $where.= " AND status != 0";
                        }
                        if($cid) {
                            $where.= " AND contact_id = '{$cid}'";
                        }
        
    
                        $response = $MYB->GetScoutings($User->id, $where, $limit, 'ssp');
                        $response["draw"] = intval($draw);
        
                        $response = json_encode($response);
                        echo $response;     
                        break;
                    }
                }
                break;
            }
        case 'contacts':{

            switch($action){        
    
    
    
                    case 'save':
                    

                   
                        $mobile = request_ifset('mobile');
                        $phone = request_ifset('phone');
                        $fullname = request_ifset('fullname');
                        $email = request_ifset('email');
                        $lead_source = request_ifset('source_id');

                        $contact_id = $MYB->NewContact($fullname, $mobile, $phone, $email, $lead_source);

                        if($contact_id) {
                            $prep = new stdClass();
                            $prep->contact_id = $contact_id;
                            $prep->user_id = $User->id;
 
                            $values = $MYB->PrepSQLValues($prep);
                            $MYB->InsertOrUpdate($values, "contacts_direct_ownership");


                            foreach($_REQUEST['primary_tags'] as $primary_tags){


                                $prep_prim_tag = new stdClass();
                                $prep_prim_tag->tag_id = $primary_tags;
                                $prep_prim_tag->entity_id = $contact_id;
                                $prep_prim_tag->user_id = $User->id;
                                $prep_prim_tag->entity = 'contacts';

     
                                $primary_tags_values = $MYB->PrepSQLValues($prep_prim_tag);
                                $MYB->InsertOrUpdate($primary_tags_values, "tags_relations");

                            }
                            

                            echo $contact_id;
                        }
                        
                    
                    break;
    
                    case 'delete':
                    
                            echo $MYB->Delete($id, "contacts");
                        
                    break;
    
                    case 'getList':{ //contacts
                        $draw = $_REQUEST['draw'];
                        $row = $_REQUEST['start'];
                        $rowperpage = $_REQUEST['length']; // Rows display per page
                        $columnIndex = $_REQUEST['order'][0]['column']; // Column index
                        $columnSortOrder = $_REQUEST['order'][0]['dir']; // asc or desc
                        $searchValue = my_escape($_REQUEST['search']['value']); // Search value
                        $filterOutStatusZero = TRUE;
    
                        if($row && $rowperpage)
                            $limit = "{$row},{$rowperpage}";
    
    
                        $where = "1=1";
        
                        foreach($_POST['search'] as $search ){
        
                            $search_value='';
    
                            if($search['name'] == 'status'){
                                $filterOutStatusZero = FALSE;
                            } 
    
                            
                            if(!empty($search['value']) OR $search['value'] == 0){
                                switch($search['name']){
                                    case 'id':

                                        $field = $search['name'];
                                        $operator = 'LIKE';
                                        $search['value'] = str_replace("CON", "", $search['value']);
                                        $search_value = "'%{$search['value']}%'";
        
                                    break;
                                    case 'status':
    
                                        $field = $search['name'];
                                        $operator = '=';
                                        $search_value = "'{$search['value']}'";
    
                                    break;
                                    case 'createdtime_daterange':
                                    case 'modifiedtime_daterange':
    
                                        $dates = DateRange_to_Dates($search['value']);
                                        $date_start = $dates[0];
                                        $date_end = $dates[1];
    
                                        $field_explode = explode('_', $search['name']);
                                        $field = $field_explode[0];
                                        $operator = 'BETWEEN';
                                        $search_value = "'{$date_start}' AND '{$date_end}'";
                                        
                                    break;
    
                                    case 'tags':
    
                                        $tags_filter[] = $search['value'];
    
                                    break;

                                    case 'primary_tags':
    
                                        $primary_tags_filter[] = $search['value'];
    
                                    break;
                                    case 'tags':
    
                                        $tags_filter[] = $search['value'];
    
                                    break;
                                    case 'consulente':
    
                                        $forced_user_id = $search['value'];
                                        $where .= " AND (FIND_IN_SET('{$forced_user_id}', authorized_users_richieste) OR FIND_IN_SET('{$forced_user_id}', authorized_users_potentials) OR FIND_IN_SET('{$forced_user_id}', authorized_users_ownership) OR FIND_IN_SET('{$forced_user_id}', authorized_users_assigned))";

                                    break;
                                    default:
    
                                        $field = $search['name'];
                                        $operator = 'LIKE';
                                        $search_value = "'%{$search['value']}%'";
    
                                    break;
    
                                }
    
                                 if($field && $operator && $search_value){
                                    $where.= " AND {$field} {$operator} {$search_value}";
                                 }
                            }
      
                        }
    
                        if($primary_tags_filter){
                            $primary_tags_filter_csv = array_to_csv($primary_tags_filter);
                            $where.= " AND FIND_IN_SET(id, (SELECT GROUP_CONCAT(entity_id) FROM tags_relations WHERE entity = 'contacts' AND tag_id IN ($primary_tags_filter_csv)))";
    
                        }

                        if($tags_filter){
                            $tags_filter_csv = array_to_csv($tags_filter);
                            $where.= " AND FIND_IN_SET(id, (SELECT GROUP_CONCAT(entity_id) FROM tags_relations WHERE entity = 'contacts' AND tag_id IN ($tags_filter_csv)))";
    
                        }
    
    
                    
        
                        if($searchValue) {
                            //$where = " AND (CONCAT(r.id, ' ', name, ' ', r.contact, ' ', r.email, ' ', r.id_immobile, ' ', r.status, ' ', r.note, ' ', imm.address, ' ', imm.city, ' ', imm.consulente) LIKE '%{$searchValue}%')";    
                        }
        
                        if($filterOutStatusZero){
                           // $where.= " AND status != 0";
                        }

                        if(!$user_id_filter) $user_id_filter = $User->id;
    
                        $response = $MYB->GetContacts_SSP($user_id_filter, $where, $limit, 'ssp');
                        $response["draw"] = intval($draw);
        
                        $response = json_encode($response);
                        echo $response;     
                        break;
                    }
                }
                break;
        }

        case 'broadcasts':{

            switch($action){        
    
    
    
                    case 'save':
                    

                        $prep = new stdClass();
                        $prep->name = request_ifset('name');
                        $prep->entity = request_ifset('entity');
                        $prep->tag_id = request_ifset('tag_id');
                        $prep->platform = request_ifset('platform');
                        $prep->user_id = $User->id;
                        $prep->status = 1;
                        $prep->company_id = COMPANY_ID;


                        $values = $MYB->PrepSQLValues($prep);
                        echo $MYB->InsertOrUpdate($values, "broadcasts");
                        
                    
                    break;

                    case 'update':
                    

                        $prep = new stdClass();
                        $prep->id = $id;
                        $prep->status = request_ifset('status');

                        switch($prep->status){
                            case '4':
                                echo $MYB->DeleteWhere("broadcast_id = '{$id}' AND status = 0", "broadcasts_queue");
                            break;
                        }

                        $values = $MYB->PrepSQLValues($prep);
                        echo $MYB->InsertOrUpdate($values, "broadcasts");
                        
                    
                    break;
    
    
                    case 'delete':
                    
                            echo $MYB->Delete($id, "broadcasts");
                        
                    break;
    
                    case 'getList':{ //contacts
                        $draw = $_REQUEST['draw'];
                        $row = $_REQUEST['start'];
                        $rowperpage = $_REQUEST['length']; // Rows display per page
                        $columnIndex = $_REQUEST['order'][0]['column']; // Column index
                        $columnSortOrder = $_REQUEST['order'][0]['dir']; // asc or desc
                        $searchValue = my_escape($_REQUEST['search']['value']); // Search value
                        $filterOutStatusZero = TRUE;
    
                        if($row && $rowperpage)
                            $limit = "{$row},{$rowperpage}";
    
    
                        $where = "1=1";
        
                        foreach($_POST['search'] as $search ){
        
                            $search_value='';
    
                            if($search['name'] == 'status'){
                                $filterOutStatusZero = FALSE;
                            } 
    
                            
                            if(!empty($search['value']) OR $search['value'] == 0){
                                switch($search['name']){
                                    case 'id':

                                        $field = $search['name'];
                                        $operator = 'LIKE';
                                        $search['value'] = str_replace("CON", "", $search['value']);
                                        $search_value = "'%{$search['value']}%'";
        
                                    break;
                                    case 'createdtime_daterange':
                                    case 'modifiedtime_daterange':
    
                                        $dates = DateRange_to_Dates($search['value']);
                                        $date_start = $dates[0];
                                        $date_end = $dates[1];
    
                                        $field_explode = explode('_', $search['name']);
                                        $field = $field_explode[0];
                                        $operator = 'BETWEEN';
                                        $search_value = "'{$date_start}' AND '{$date_end}'";
                                        
                                    break;
    
                                    case 'tag_id':
    
                                        $tags_filter[] = $search['value'];
    
                                    break;

                                 
                          
                                    default:
    
                                        $field = $search['name'];
                                        $operator = 'LIKE';
                                        $search_value = "'%{$search['value']}%'";
    
                                    break;
    
                                }
    
                                 if($field && $operator && $search_value){
                                    $where.= " AND {$field} {$operator} {$search_value}";
                                 }
                            }
      
                        }
    
                     
                        if($tags_filter){
                            $tags_filter_csv = array_to_csv($tags_filter);
                            $where.= " AND FIND_IN_SET(id, (SELECT GROUP_CONCAT(entity_id) FROM tags_relations WHERE entity = 'contacts' AND tag_id IN ($tags_filter_csv)))";
    
                        }
    
    
                    
        
                        if($searchValue) {
                            //$where = " AND (CONCAT(r.id, ' ', name, ' ', r.contact, ' ', r.email, ' ', r.id_immobile, ' ', r.status, ' ', r.note, ' ', imm.address, ' ', imm.city, ' ', imm.consulente) LIKE '%{$searchValue}%')";    
                        }
        
                        if($filterOutStatusZero){
                           // $where.= " AND status != 0";
                        }
    
                        $response = $MYB->GetBroadcasts($User->id, $where, $limit, 'ssp');
                        $response["draw"] = intval($draw);
        
                        $response = json_encode($response);
                        echo $response;     
                        break;
                    }
                }
                break;
        }

        case 'property':{
        
            switch($action){        

                case 'getInfo':
                    

                    echo $MYB->GetPropertyByRif($id, 'json');
                    
                
                break;
    
                case 'update':
                    

    
                    $prep = new stdClass();
                    $prep->listings_rif_id                 = $id;
                    $prep->docs_report = request_ifset('docs_report');
    
                  
                    $values = $MYB->PrepSQLValues($prep);
                    echo $MYB->InsertOrUpdate($values, "impruv");
                
                break;
    
                case 'saveShowingsFeed':
                    

    
                    $prep = new stdClass();
                    $prep->property_id                 = $id;
                    $prep->company_id           = COMPANY_ID;
                    $prep->startDate       = request_ifset('startDate');
                    $prep->endDate            = request_ifset('endDate');
    
                  
                    $values = $MYB->PrepSQLValues($prep);
                    echo $MYB->InsertOrUpdate($values, "showings_availability");
                
                break;
        
                case 'getShowingsFeed':
                    

    
                   $Showings =  $MYB->Get("id, startDate as start, endDate as end", "showings_availability", "property_id = '{$id}' AND company_id = ".COMPANY_ID, "id", 500, false, 'obj');
                   foreach($Showings as $Showing){

                       //$Showing->dow = "[2]"; 

                   }

                   echo json_encode($Showings);
                

                break;
                case 'deleteShowingsFeed':
                    
                        $eventID = request_ifset('eventId');
                    echo $MYB->DeleteWhere("property_id = '{$id}' and id = '{$eventID}' AND company_id = ".COMPANY_ID, 'showings_availability');

                 break;
            }
            break;
        }
    
    case 'PricesHistory':{
        
        switch($action){        

            case 'save':
                
                $rif_id     = $id;
                $PropertyData = $MYB->GetPropertyByRif($rif_id, 'obj');

                $prep = new stdClass();
                $prep->date                 = request_ifset('date');
                $prep->rif_id           = $PropertyData->rif_id;
                $prep->previous_price       = request_ifset('previous_price');
                $prep->new_price            = request_ifset('new_price');
                $prep->company_id           = COMPANY_ID;

              
                $values = $MYB->PrepSQLValues($prep);
                echo $MYB->InsertOrUpdate($values, "listing_ribassi");
            
            break;
    
            case 'delete':
            
                    echo $MYB->Delete($id, "listing_ribassi");
                
            break;
        }
        break;
    }

    case 'Activity':{
        
        switch($action){        

            case 'new':
                
                $prep = new stdClass();
                $prep->activity_date                 = request_ifset('date');
                $prep->entity           = request_ifset('entity');
                $prep->entity_id       = request_ifset('entity_id');
                $prep->type            = request_ifset('type');
                $prep->user_id         = $User->id;
                $prep->status = 1;
                $prep->company_id           = COMPANY_ID;

                $values = $MYB->PrepSQLValues($prep);
                $Activity_ID =  $MYB->InsertOrUpdate($values, "activities");
                echo $Activity_ID;

                if(request_ifset('activity_comment')) {
                    $prep_comm = new stdClass();
                    $prep_comm->entity           = request_ifset('entity');
                    $prep_comm->entity_id       = request_ifset('entity_id');
                    $prep_comm->created_by = $User->id;
                    $prep_comm->content = request_ifset('activity_comment');
                    $prep_comm->activity_id = $Activity_ID;
                    $prep_comm->company_id = COMPANY_ID;
                    $prep_comm->status = 1;

                    $values_comm = $MYB->PrepSQLValues($prep_comm);
                    $MYB->InsertOrUpdate($values_comm, "comments");

                }
            
            break;
    
            case 'delete':
            
                echo $MYB->SoftDelete($id, 'activities', 'status', 0);
                
            break;
        }
        break;
    }

    case 'RenewalsHistory':{
        
        switch($action){        

            case 'save':
                
                $rif_id     = $id;
                $PropertyData = $MYB->GetPropertyByRif($rif_id, 'obj');

                $prep = new stdClass();
                $prep->date                 = request_ifset('date');
                $prep->rif_id           = $PropertyData->rif_id;
                $prep->company_id           = COMPANY_ID;

              
                $values = $MYB->PrepSQLValues($prep);
                echo $MYB->InsertOrUpdate($values, "listing_renowals");
            
            break;
    
            case 'delete':
            
                    echo $MYB->Delete($id, "listing_renowals");
                
            break;
        }
        break;
    }

    case 'ListingStats':{

    
        switch($action){        



                case 'save':
                
                    $prep = new stdClass();
                    $prep->report_date          = request_ifset('report_date');
                    $prep->rif_id               = request_ifset('rif_id');
                    $prep->source               = request_ifset('source');
                    $prep->data1                = request_ifset('data1');
                    $prep->data2                = request_ifset('data2');
                    $prep->data3                = request_ifset('data3');
                    $prep->data4                = request_ifset('data4');
                    $prep->data5                = request_ifset('data5');

                    $values = $MYB->PrepSQLValues($prep);
                    echo $MYB->InsertOrUpdate($values, "listing_stats");
                
                break;
        
                case 'delete':
                
                        echo $MYB->Delete($id, "listing_stats");
                    
                break;
            }
            break;
        }



    case 'assistantAI': {

        

            switch($action){        
    
                case 'generate':{

                   // echo GenerateOpenAI("cos'è chatgpt?", 50);

                   
                    
                    $webhook_resp = curlize("https://hook.eu1.make.com/59yhiax2o00jknbpl3n15sb3iwhlwsc5", 
                                false, 
                                false, 
                                $_POST
                            );

                    
                $response = json_encode(nl2br($webhook_resp));
                echo $response;     
                                    
                }
            }
        break;
    }     
    
    case 'AttendanceRegister':{

    
        switch($action){        

                case 'save':
                
                    $prep = new stdClass();
                    $prep->date                     =       request_ifset('date');
                    $prep->n_pres                   =       request_ifset('n_pres');
                    $prep->user_id                  =       request_ifset('consulente');
           

                    $values = $MYB->PrepSQLValues($prep);
                    echo $MYB->InsertOrUpdate($values, "attendance_register");
                
                break;
        
                case 'delete':
                
                        echo $MYB->Delete($id, "attendance_register");
                    
                break;
            }
            break;
        }
    case 'smsscript':{
    
        
        switch($action){        
                
                case 'data':
                
                    if(request_ifset('buyerlead_id')){
                                    echo $MYB->GetSMSScript($id, request_ifset('buyerlead_id'));
    
                    } else {
                    
                                    echo $MYB->GetSMSScript($id);
    
                    }
            
                break;
        
                case 'delete':
                    
                    $ScriptInfo = $MYB->GetSMSScript($id, 'obj');
                    if($User->id == $ScriptInfo->user_id || is_backoffice()){
                        echo $MYB->Delete($id, "sms_scripts");
                    }
                break;
            }
            break;
        }

    case 'DocGenerator':{

if ( ! headers_sent() ) {
    header_remove();
}

        switch($action){        
            
            case 'fogliovisita':
                echo $MYB->DocGenerator('fogliovisita.docx', $id);
            break;
            case 'PBXReport':
                echo $MYB->DocGenerator('ReportCentralino.xlsx', $id);
            break;
            case 'SellerReport':
                echo $MYB->DocGenerator('SellerReport.docx', $id);
            break;
	        case 'ReferralAgreement':
                echo $MYB->DocGenerator('ReferralAgreement.docx', $id);
            break;
    
	}
	die();
        break;
    }

    case 'comments':{


        switch($action){        
            
            case 'new':
            
                $prep = new stdClass();
                
                $prep->entity                  = request_ifset('related_to');
                $prep->entity_id              = request_ifset('entity_id');
                $prep->created_by              = $User->id;
                $prep->content                      = request_ifset('content');
                $prep->status = 1;
                $prep->company_id = COMPANY_ID;
                $values = PrepSQLValues($prep);
                echo $MYB->InsertOrUpdate($values, "comments");
                
            break;

            case 'get':
            
                echo $MYB->GetComments($id, request_ifset('entity'));
                
            break;

            case 'delete':
                echo $MYB->SoftDelete($id, 'comments', 'status', 0);
            break;
            
    
        }
        break;
    }
    case 'tag':{


        if($id == 'new') {

            $prep = new stdClass();
            $prep->module       = request_ifset('related_to');
            $prep->tagname      = request_ifset('text');
            $prep->only_for_user = $User->id;
            $prep->company_id                 = COMPANY_ID;

            $values = PrepSQLValues($prep);
            $id =  $MYB->InsertOrUpdate($values, "tags");

        }

        switch($action){        
            
            case 'bind':
            
                $prep = new stdClass();
                $prep->tag_id                   = $id;
                $prep->entity                   = request_ifset('related_to');
                $prep->entity_id                = request_ifset('entity_id');
                $prep->user_id                  = $User->id;
                
                $TagInfo = $MYB->GetTag($id, 'obj');
                $AuditLog = $MYB->NewAuditLog(
                    $prep->entity, // module
                    $prep->entity_id, // id
                    1, // 1 = create, 2 = update, 3 = delete
                    'tag', // field (optional)
                    false, // previous_value (optional)
                    $TagInfo->tagname, // postvalue (optional)
                );
             
                $values = PrepSQLValues($prep);
                echo $MYB->InsertOrUpdate($values, "tags_relations");

          
                
            break;

            case 'unbind':
            
                $related_to = request_ifset('related_to');
                $entity_id = request_ifset('entity_id');

                $TagInfo = $MYB->GetTag($id, 'obj');

                $AuditLog = $MYB->NewAuditLog(
                    $related_to, // module
                    $entity_id, // id
                    3, // 1 = create, 2 = update, 3 = delete
                    'tag', // field (optional)
                    $TagInfo->tagname, // postvalue (optional)
                    false
                );
                
                echo $MYB->DeleteWhere("entity = '{$related_to}' AND entity_id = '{$entity_id}' AND tag_id = '{$id}'", "tags_relations");
                
            break;
    
        }
        break;
    }
    
    case 'buyerleadhistory':{

    header('Content-type: text/html; charset=UTF-8');

                $BuyerLeadLog =  $MYB->GetBuyerLeads('contact', $id, 'obj');
                
                $result = "<h3>Cliente: {$BuyerLeadLog[0]->name} </h3>
                <table class='table table-responsive'>
                <tr><th width='140'>ID</th><th>IMMOBILE</th><th>CONSULENTE</th><th>STATO</th><th>NOTE</th><th>COMMENTO</th><th>DATA</th>";
                foreach($BuyerLeadLog as $BuyerRequest) {
                
                $BuyerRequest->status = option_value_to_map_name('richieste', 'lead_status', "{$BuyerRequest->status}");
                        if($BuyerRequest->listing_agent_id){
						
                            $ListingAgentUserData               =   Get_User_Info('id', $BuyerRequest->listing_agent_id);
                            $BuyerRequest->consulente_name			=	$ListingAgentUserData->name;
						} else {
							$AgentUserData                   =   Get_User_Info('maximizer_uid', $BuyerRequest->agent_id);
							$BuyerRequest->consulente_name			=	$AgentUserData->name;
						}
						
						if($BuyerRequest->forced_agent_id){
                            $ForcedAgentUserData           =   Get_User_Info('id', $BuyerRequest->forced_agent_id);
                            $BuyerRequest->consulente_name			=	$ForcedAgentUserData->name;
						}
                
                
                $PropertyData = $MYB->GetPropertyByRif($BuyerRequest->id_immobile, 'obj');
               
                $result .= <<<EOD
                <tr>
                    <td><a href='javascript:LogRecall({$BuyerRequest->id})'><button type='button' class='btn btn-primary btn-xs'><i class='material-icons'>notification_important</i></button></a> #{$BuyerRequest->id} <td>{$BuyerRequest->id_immobile} - {$PropertyData->address}, {$PropertyData->number} {$PropertyData->city}</td>
                    <td>{$BuyerRequest->consulente_name}</td>
                    <td>{$BuyerRequest->status}</td>
                    <td>{$BuyerRequest->note}</td>
                    <td>{$BuyerRequest->comment}</td>
                    <td>{$BuyerRequest->ts}</td>
                </tr>
EOD;
                }
        
                $result .= '</table>';
                echo $result;
        
            break;
    
        
    }
    
    case 'CalendarEvent': {

        

        switch($action){        

            case 'new':{


                $prep = new stdClass();
                
                $prep->user_id                  = request_ifset('user_id');
                $prep->event_owner              = request_ifset('event_owner');
                $user_name                      = request_ifset('user_name');
                $prep->event_time               = request_ifset('event_time');
                $prep->event_type               = request_ifset('event_type');
                $prep->event_room               = request_ifset('event_room');
                $prep->event_partecipants       = request_ifset('event_partecipants');
                $prep->event_duration           = request_ifset('event_duration');
                $prep->event_description        = request_ifset('event_description');
                $prep->status                   = 0;

             

                $webhook_resp = curlize("https://hook.eu1.make.com/br05zbkavhgchqgbu7d6ay17fi2dqqft", 
                                false, 
                                false, 
                                array(
                                    'event_owner' => "{$prep->event_owner}", 
                                    'user_name' => "{$user_name}", 
                                    'event_time' => "{$prep->event_time}",
                                    'event_type' => "{$prep->event_type}",
                                    'event_room' => "{$prep->event_room}",
                                    'event_id' => '',
                                    'event_partecipants' => "{$prep->event_partecipants}",
                                    'event_duration' => "{$prep->event_duration}",
                                    'event_description' => "{$prep->event_description}",
                                )
                            );

                 $prep->external_event_id                   = $webhook_resp;
                 $values = PrepSQLValues($prep);
                 $MYB->InsertOrUpdate($values, "calendar_events");
                            echo 1;


            }
            break;
            case 'update': {
             
                $prep = new stdClass();
                
                $prep->id           = $id;
                $prep->status       = request_ifset('status');
             
                $Event = $MYB->GetCalendarEvent($id, 'obj');
                
                $values = PrepSQLValues($prep);
                        
                
                switch($prep->status){
                
                    case 1: // Appuntamento Fissato
                        {
                            $webhook_resp = curlize("https://hook.eu1.make.com/br05zbkavhgchqgbu7d6ay17fi2dqqft", 
                                    false, 
                                    false, 
                                    array(
                                        'event_owner' => "{$Event->event_owner}", 
                                        'event_time' => "{$Event->event_time}",
                                        'event_type' => "{$Event->event_type}",
                                        'event_room' => "{$Event->event_room}",
                                        'event_id' => "{$Event->external_event_id}",
                                        'status' => "{$prep->status}",
                                        'event_partecipants' => "{$Event->event_partecipants}",
                                        'event_duration' => "{$Event->event_duration}",
                                        'event_description' => "{$Event->event_description}",
                                    )
                                );
                        }
                    break;
                    
                
                    case 2: // Appuntamento Cancellato
                    {
                        $webhook_resp = curlize("https://hook.eu1.make.com/br05zbkavhgchqgbu7d6ay17fi2dqqft", 
                                false, 
                                false, 
                                array(
                                    'event_owner' => "{$Event->event_owner}", 
                                    'event_time' => "{$Event->event_time}",
                                    'event_type' => "{$Event->event_type}",
                                    'event_room' => "{$Event->event_room}",
                                    'event_id' => "{$Event->external_event_id}",
                                    'status' => "{$prep->status}",
                                    'event_partecipants' => "{$Event->event_partecipants}",
                                    'event_duration' => "{$Event->event_duration}",
                                    'event_description' => "{$Event->event_description}",
                                )
                            );
                    }
                    break;
                }


                $MYB->InsertOrUpdate($values, "calendar_events");
                echo 1;
            }
            break;
            
            
        }
    break;
    }

    case 'buyerleads': {

        switch($action){        
           
            case 'update': {
             
                $prep = new stdClass();
                
                $prep->status       = request_ifset('status');
                $prep->comment      = request_ifset('comment');
                $event_date         = request_ifset('meeting_date');
        
                $values = PrepSQLValues($prep);
                
                $LeadInfo               = $MYB->GetBuyerLead($id, 'obj');
                $id_immobile            = maximizer_codice_to_id($LeadInfo->id_immobile);
                $Property               = $MYB->GetProperty($id_immobile, 'obj');
                $Consulente_Info        = Get_User_Info('id', $Property->uid);

                
                
                if($Property->listing_agent_id) {
                    $Consulente_Info = Get_User_Info('id', $Property->listing_agent_id);
                }
                
                if($LeadInfo->forced_agent_id) {
                    $Consulente_Info = Get_User_Info('id', $LeadInfo->forced_agent_id);
                }
                        
                
                switch($prep->status){
                
                
                
                    case 2: // Appuntamento Fissato
                    {
                    
                        $telegram_update_text = <<<EOD
                        \xE2\x9C\x85 <b>(ID #{$LeadInfo->id}) NUOVA RICHIESTA SPECIFICA</b>\n\n <b>Contatto:</b> {$LeadInfo->name}\n <b>Recapito</b>: {$LeadInfo->contact}\n <b>Immobile</b>: {$Property->address} ({$Property->price} / {$Property->cliente}) \n\n \xF0\x9F\x93\x8C Gestito: Appuntamento Fissato
EOD;
    
                        if($event_date){
                            $event_description = <<<EOD
🏡 	DATI PROPRIETARIO
{$Property->cliente}
{$Property->address}, {$Property->number} - {$Property->city}
{$Property->cell_cliente}

🕵️	 DATI RICHIESTA
{$LeadInfo->name} 
{$LeadInfo->contact}
{$LeadInfo->note}  - {$LeadInfo->private_notes}
---------

👉 APRI RICHIESTA SU {$Page->PLATFORM_NAME}
{$Page->BASE_URL_HTTPS}/buyer-leads/manage/{$LeadInfo->id}

-- Evento inserito da {$Page->PLATFORM_NAME} --
                            
EOD;
                            

                            echo $MYB->NewCalendarEvent(
                                $Consulente_Info->id, 
                                'property_visit', 
                                "AV | {$LeadInfo->name} - {$Property->rif_id} ({$Property->city})",
                                $event_date,
                                $event_description,
                                "{$Property->address}, {$Property->number} - {$Property->city}",
                                DEFAULT_PROPERTY_VISITS_DURATION,
                                GCALENDAR_PROPERTY_VISITS_ID
                            );

                          
                    }
                }
                    break;
                    
                     case 10: // Appuntamento VRA Fissato
                    {
                    
                        $telegram_update_text = <<<EOD
                        \xE2\x9C\x85 <b>(ID #{$LeadInfo->id}) NUOVA RICHIESTA SPECIFICA</b>\n\n <b>Contatto:</b> {$LeadInfo->name}\n <b>Recapito</b>: {$LeadInfo->contact}\n <b>Immobile</b>: {$Property->address} ({$Property->price} / {$Property->cliente}) \n\n \xF0\x9F\x93\x8C Gestito: Appuntamento VRA Fissato
EOD;
    
                        if($event_date){
                            $event_description = <<<EOD

🏡 	DATI PROPRIETARIO
{$Property->cliente}
{$Property->address}, {$Property->number} - {$Property->city}
{$Property->cell_cliente}

🕵️	 DATI RICHIESTA
{$LeadInfo->name} 
{$LeadInfo->contact}
{$LeadInfo->note}  - {$LeadInfo->private_notes}
---------

👉 APRI RICHIESTA SU {$Page->PLATFORM_NAME}
{$Page->BASE_URL_HTTPS}/buyer-leads/manage/{$LeadInfo->id}

-- Evento inserito da {$Page->PLATFORM_NAME} --
                            
EOD;

                        echo $MYB->NewCalendarEvent(
                            $Consulente_Info->id, 
                            'property_visit_vra', 
                            "VRA | {$LeadInfo->name} - {$Property->rif_id} ({$Property->city})",
                            $event_date,
                            $event_description,
                            "VIDEO",
                            '30',
                            GCALENDAR_PROPERTY_VISITS_ID
                        );
                            
                        }
                    }
                    break;
                    
                    case 6: // Non adatto
                    {
                    
                        $telegram_update_text = <<<EOD
                        \xE2\x9C\x85 <b>(ID #{$LeadInfo->id}) NUOVA RICHIESTA SPECIFICA</b>\n\n <b>Contatto:</b> {$LeadInfo->name}\n <b>Recapito</b>: {$LeadInfo->contact}\n <b>Immobile</b>: {$Property->address} ({$Property->price} / {$Property->cliente}) \n\n \xF0\x9F\x93\x8C Gestito: Immobile / Cliente Non adatto
EOD;
                    
                    }
                    break;
                    
                    case 9: // In attesa
                    {
                    
                        $telegram_update_text = <<<EOD
                        \xE2\x9A\xA0 <b>(ID #{$LeadInfo->id}) NUOVA RICHIESTA SPECIFICA</b>\n\n <b>Contatto:</b> {$LeadInfo->name}\n <b>Recapito</b>: {$LeadInfo->contact}\n <b>Immobile</b>: {$Property->address} ({$Property->price} / {$Property->cliente}) \n\n \xF0\x9F\x93\x8C Gestito: In Attesa
EOD;
                    
                    }
                    break;
                
                    case 8: { // Non risponde
                        $telegram_update_text = <<<EOD
                        \xE2\x9A\xA0 <b>(ID #{$LeadInfo->id}) NUOVA RICHIESTA SPECIFICA</b>\n\n <b>Contatto:</b> {$LeadInfo->name}\n <b>Recapito</b>: {$LeadInfo->contact}\n <b>Immobile</b>: {$Property->address} ({$Property->price} / {$Property->cliente}) \n\n \xF0\x9F\x93\x8C Gestito: Cliente non risponde
EOD;
                        
                        
                        Send_SMS($LeadInfo->contact, "Gentile Cliente, ho provato a contattarla per un immobile su cui ha richiesto informazioni. Mi può ricontattare  al {$Consulente_Info->cell}"); 
                
                    }
                    break;
                case 12: { // OK GESTITO
                        $telegram_update_text = <<<EOD
                        \xE2\x9C\x85 <b>(ID #{$LeadInfo->id}) NUOVA RICHIESTA</b>\n\n <b>Contatto:</b> {$LeadInfo->name}\n <b>Recapito</b>: {$LeadInfo->contact}\n\n\n \xF0\x9F\x93\x8C Ok - Gestito
EOD;


                    }
		    break;

		    case 14: {
			    #$encoded_full_id = COMPANY_ID.'_'.hashid($id, 'encode', 6);
			    $hash_encode_id = hashid($LeadInfo->id, 'encode', 6);
			    $encoded_full_id = COMPANY_ID.'_'.$hash_encode_id;

			    $msg_collaborazione = <<<EOD
Gentile Collega,
ci fa piacere aver ricevuto la tua richiesta di collaborazione per l'immobile Rif. {$LeadInfo->id_immobile} ({$prep->description}).

Puoi fissare un appuntamento da questo link:
{$Page->BASE_URL_HTTPS}/set-showing/{$encoded_full_id}

Grazie
EOD;

WAConnector_Send(ConvertPhoneNumber($LeadInfo->contact), $msg_collaborazione);
			} 

		   break;
 
                }
                
                $inline_keyboard = array('inline_keyboard' =>
                    array(
                        array(
                            array(
                                'text' => "\xF0\x9F\x93\x9D Modifica Esito su ".PLATFORM_NAME, 'url' => "{$Page->BASE_URL_HTTPS}/buyer-leads/manage/{$LeadInfo->id}"
                            )
                        )
                    ),
                );

                
                $telegram_info = explode("-", $LeadInfo->telegram_msg_id);
                $TelegramUpdate = Edit_Msg_Telegram($telegram_info[0], $telegram_info[1], $telegram_update_text, $inline_keyboard);

            
                
                echo $MYB->Update($values, "richieste", "id = {$id}");
            break;
            }
            
            case 'recall':{
            
            
            
            
             
                  save_in_db("INSERT INTO richieste_recall_log (id_richiesta) VALUES ({$id})");

                
                $LeadInfo               = $MYB->GetBuyerLead($id, 'obj');
                $SendBLNotif            = SendBuyerleadNotification($LeadInfo->id, $Page, 'recall');
                echo 1;
                break;
            
            }
            
            case 'sendfeedback': {
            
                $prep = new stdClass();
                $prep->id_richiesta     = $id;
                $prep->mode             = request_ifset('mode');

             
                if(request_ifset('mode') == 'sms'){
                
                    $LeadInfo               = $MYB->GetBuyerLead($id, 'obj');
                    $id_immobile            = maximizer_codice_to_id($LeadInfo->id_immobile);
                    $Property               = $MYB->GetProperty($id_immobile, 'obj');
                    $Consulente_Info        = Get_User_Info('id', $Property->uid);
                    
                    
                    if($Property->listing_agent_id) {
                        $Consulente_Info = Get_User_Info('id', $Property->listing_agent_id);
                    }
                    
                    if($LeadInfo->forced_agent_id) {
                        $Consulente_Info = Get_User_Info('id', $LeadInfo->forced_agent_id);
                    }
                    $cid = COMPANY_ID;
                    $hash_form_id = hashid($id, 'encode', 6);

                    Send_SMS($LeadInfo->contact, "Gentile Cliente, Le chiediamo di compilare un brevissimo questionario riguardo all'immobile che ha visitato con noi: {$Page->BASE_URL_HTTPS}/fv/{$cid}_{$hash_form_id}"); 
                    
                
                } 
                
                
                $values = PrepSQLValues($prep);
                
                $MYB->InsertOrUpdate($values, "richieste_survey");
                
                
                echo 1;
                break;
                
            }
            case 'getInfo':{
                $limit = 1;
                $where="bl.id = '{$id}'";
                echo $MYB->GetBuyerLeadsListForUser($User->id, $limit, $where, $Page);
                break;
            }
            
            case 'getList':{
                $limit = false;
                if(request_ifset('limit')) $limit = request_ifset('limit');
                if(request_ifset('cid')) $where="contact_id = '".request_ifset('cid')."'";
                echo $MYB->GetBuyerLeadsListForUser($User->id, $limit, $where, $Page);
                break;
            }
            case 'getListv2':{ //buyerleads
                $draw = $_POST['draw'];
                $row = $_POST['start'];
                $rowperpage = $_POST['length']; // Rows display per page
                $columnIndex = $_POST['order'][0]['column']; // Column index
                $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
                $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
                $searchValue = my_escape($_POST['search']['value']); // Search value
                $filterOutStatusZero = TRUE;

                $cid = request_ifset('cid');
               

                if(!empty($row) && !empty($rowperpage))
                    $limit = "{$row},{$rowperpage}";

                $where = "";

                //print_r($_POST);
                foreach($_POST['search'] as $search ){
        
                    $search_value='';

                    if($search['name'] == 'status'){
                        $filterOutStatusZero = FALSE;
                    } 

                    
                    if(!empty($search['value']) OR $search['value'] == 0){
                        switch($search['name']){
                            case 'id':

                                $field = $search['name'];
                                $operator = 'LIKE';
                                $search['value'] = str_replace("BUY", "", $search['value']);
                                $search_value = "'%{$search['value']}%'";

                            break;
                        
                            case 'status':
                            case 'lead_type':
                            case 'lead_source':

                                $field = $search['name'];
                                $operator = '=';
                                $search_value = "'{$search['value']}'";

                            break;
                            
                            case 'createdtime_daterange':
                            case 'modifiedtime_daterange':

                                $dates = DateRange_to_Dates($search['value']);
                                $date_start = $dates[0];
                                $date_end = $dates[1];

                                $field_explode = explode('_', $search['name']);
                                $field = $field_explode[0];
                                $operator = 'BETWEEN';
                                $search_value = "'{$date_start}' AND '{$date_end}'";
                                
                            break;

                            case 'tags':

                                $tags_filter[] = $search['value'];

                            break;

                            case 'primary_tags':

                                $primary_tags_filter[] = $search['value'];

                            break;
                            default:

                                $field = $search['name'];
                                $operator = 'LIKE';
                                $search_value = "'%{$search['value']}%'";

                            break;

                        }

                         if($field && $operator && $search_value){
                            $where.= " AND {$field} {$operator} {$search_value}";
                         }
                    }

                }

                if($searchValue) {
                    //$where = " AND (CONCAT(r.id, ' ', name, ' ', r.contact, ' ', r.email, ' ', r.id_immobile, ' ', r.status, ' ', r.note, ' ', imm.address, ' ', imm.city, ' ', imm.consulente) LIKE '%{$searchValue}%')";    
                }

                if($filterOutStatusZero){
                    $where.= " AND status != 0";
                }
                if($cid) {
                    $where.= " AND contact_id = '{$cid}'";
                }

                $response = $MYB->GetBuyerLeadsListForUserV2($User->id, $where, $limit, $Page, 'ssp');
                $response["draw"] = intval($draw);

                $response = json_encode($response);
                echo $response;     
                break;
            }

            case 'delete':{
            
                if(is_backoffice()){

                    $BuyerLead = $MYB->GetBuyerLead($id, 'obj');
                    // cancella notifica telegram 
                    $telegram_msg_to_delete = explode("-", $BuyerLead->telegram_msg_id);
                    $TelegramUpdate = Delete_Msg_Telegram($telegram_msg_to_delete[0], $telegram_msg_to_delete[1]);
    
                    $MYB->Delete($id, "richieste");
                    
                   echo 1;
                }
                break;

                
            
            }
            
            case 'edit':{
            
                $prep = new stdClass();
                
                $prep->internal_notes       = request_ifset('internal_notes');
                $prep->private_notes        = request_ifset('private_notes');
                $values = PrepSQLValues($prep);
              
                echo $MYB->Update($values, "richieste", "id = {$id}");
            }
            break;

            case 'requestShowing': {
                $LeadInfo               = $MYB->GetBuyerLead($id, 'obj');
                $Property               = $MYB->GetPropertyByRif($LeadInfo->id_immobile, 'obj');

               // print_r($LeadInfo);die();
                $Consulente_Info = Get_User_Info('id', $LeadInfo->listing_agent_uid);

                if($LeadInfo->buyer_agent_uid) {
                    $Consulente_Info = Get_User_Info('id', $LeadInfo->buyer_agent_uid);
                }
                
                if($LeadInfo->forced_agent_id) {
                    $Consulente_Info = Get_User_Info('id', $LeadInfo->forced_agent_id);
                }

                $prep = new stdClass();
                $prep->buyerlead_id     = $id;
                $prep->property_id      = $Property->gest_property_id;
                $prep->company_id = COMPANY_ID;

              
                $confirm_link = "{$Page->BASE_URL_HTTPS}/set-showing/".COMPANY_ID."_".hashid($id, 'encode', 6)."_".hashid($Property->cell_cliente, 'encode', 6)."/confirm";

                switch(request_ifset('status')){

                    default:
  
                        $Date = DateTime::createFromFormat('Y-m-d H:i',request_ifset('date'));  //create date time objects

                        $prep->description      = request_ifset('client_name');
                        $prep->startDate        = $Date->format('Y-m-d\TH:i:s\Z');
                        $prep->endDate          = $Date->modify('+'.request_ifset('duration').' minutes')->format('Y-m-d\TH:i:s\Z');
        
        
                        $MsgDate = new DateTime(request_ifset('date'), new DateTimeZone("UTC"));
                        $MsgDate->setTimezone(new DateTimeZone("Europe/Rome"));
                        $day = $MsgDate->format('d-m-Y');
                        $hour  = $MsgDate->format('H:i');
        
    
                        $prep->status           = 1;
                        
                        //Send_SMS(ConvertPhoneNumber($LeadInfo->contact), "Ti confermiamo di aver ricevuto la richiesta di appuntamento per il giorno {$day} alle ore {$hour} per l'immobile Rif. {$LeadInfo->id_immobile} ({$prep->description}). Riceverai una conferma nel più breve tempo possibile. Grazie"); 
                        WAConnector_Send(ConvertPhoneNumber($LeadInfo->contact), "Gentile Collega, ti confermiamo di aver ricevuto la richiesta di appuntamento per il giorno {$day} alle ore {$hour} per l'immobile Rif. {$LeadInfo->id_immobile} ({$prep->description}). Riceverai una conferma nel più breve tempo possibile. Grazie"); 
                        WAConnector_Send(ConvertPhoneNumber($Consulente_Info->cell), "Gentile Consulente, ti notifichiamo di aver ricevuto e gestito automaticamente la richiesta di appuntamento ricevuta da {$LeadInfo->name} per il giorno {$day} alle ore {$hour} per l'immobile Rif. {$LeadInfo->id_immobile} (per {$prep->description}). Un messaggio ègià  stato inviato al proprietario. Grazie"); 
                        WAConnector_Send(ConvertPhoneNumber($Property->cell_cliente), "Gentile Cliente, hai appena ricevuto una richiesta di appuntamento per il giorno {$day} alle ore {$hour} per l'immobile Rif. {$LeadInfo->id_immobile}. Puoi *confermare* o *rifiutare* l'appuntamento da questo link: {$confirm_link}"); 
                        
                    break;

                    case 2:
                       
                        $prep->status           = 2;


                        WAConnector_Send(ConvertPhoneNumber($LeadInfo->contact), "AGGIORNAMENTO: L'appuntamento per il giorno {$day} alle ore {$hour} per l'immobile Rif. {$LeadInfo->id_immobile} ({$prep->description}) è stato CONFERMATO. Grazie."); 
                        WAConnector_Send(ConvertPhoneNumber($Consulente_Info->cell), "Notifica di AGGIORNAMENTO richiesta di appuntamento DA {$LeadInfo->name} per il giorno {$day} alle ore {$hour} per l'immobile Rif. {$LeadInfo->id_immobile} (per {$prep->description}). Appuntamento CONFERMATO."); 
                        WAConnector_Send(ConvertPhoneNumber($Property->cell_cliente), "AGGIORNAMENTO: L'appuntamento per il giorno {$day} alle ore {$hour} per l'immobile Rif. {$LeadInfo->id_immobile} è stato confermato. Grazie"); 
                        

                    break;

                }
            
            
                $values = PrepSQLValues($prep);
                
                echo $MYB->InsertOrUpdate($values, "showings_bookings");
 
                break;
                
            }

            case 'deleteShowing': {
                $LeadInfo               = $MYB->GetBuyerLead($id, 'obj');
                $Property               = $MYB->GetPropertyByRif($LeadInfo->id_immobile, 'obj');
                $Consulente_Info = Get_User_Info('id', $LeadInfo->listing_agent_uid);

                if($LeadInfo->buyer_agent_uid) {
                    $Consulente_Info = Get_User_Info('id', $LeadInfo->buyer_agent_uid);
                }
                
                if($LeadInfo->forced_agent_id) {
                    $Consulente_Info = Get_User_Info('id', $LeadInfo->forced_agent_id);
                }

               // print_r($LeadInfo);die();
                $BookedSlot = $MYB->Get("id, startDate, endDate", "showings_bookings", "property_id = '{$Property->gest_property_id}' AND buyerlead_id = '{$id}' AND company_id = ".COMPANY_ID, "id asc", 1, false, 'obj');
                if($BookedSlot[0]) {
                    $Date = DateTime::createFromFormat(DATE_ATOM,$BookedSlot[0]->startDate);  //create date time objects
                    $Date->setTimezone(new DateTimeZone("Europe/Rome"));
                    $day = $Date->format('d-m-Y');
                    $hour  = $Date->format('H:i');
                    

                    WAConnector_Send(ConvertPhoneNumber($LeadInfo->contact), "AGGIORNAMENTO: L'appuntamento per il giorno {$day} alle ore {$hour} per l'immobile Rif. {$LeadInfo->id_immobile} ({$prep->description}) è stato RIFIUTATO. Grazie."); 
                    WAConnector_Send(ConvertPhoneNumber($Consulente_Info->cell), "Notifica di AGGIORNAMENTO richiesta di appuntamento DA {$LeadInfo->name} per il giorno {$day} alle ore {$hour} per l'immobile Rif. {$LeadInfo->id_immobile} (per {$prep->description}). Appuntamento RIFIUTATO."); 
                    WAConnector_Send(ConvertPhoneNumber($Property->cell_cliente), "AGGIORNAMENTO: L'appuntamento per il giorno {$day} alle ore {$hour} per l'immobile Rif. {$LeadInfo->id_immobile} è stato RIFIUTATO. Grazie"); 
                    

                    echo $MYB->Delete($BookedSlot[0]->id, "showings_bookings");

                }
                break;
                
            }
           
        }
    break;
    }
    
    case 'academylog': {

        switch($action){        
           
            case 'create':
             
                $prep = new stdClass();
                
                $prep->lesson_id    = $id;
                $prep->user_id    = request_ifset('user_id');
                $prep->date      = request_ifset('date');
        
                $values = PrepSQLValues($prep);
                
                echo $MYB->InsertOrUpdate($values, "academy_logbook");
            break;
            
            case 'delete':
                
                echo $MYB->Delete($id, "academy_logbook");
            break;
           
        }
    break;
    }
    
     case 'academyschedule': {

        switch($action){        
           
            case 'create':
             
                $prep = new stdClass();
                
                $prep->lesson_id        = $id;
                $prep->date_start       = request_ifset('date_start');
                $prep->duration         = request_ifset('duration');
                $prep->cal_id           = request_ifset('cal_id');
                //$prep->date_end         = request_ifset('date_end');
        
        
                if(request_ifset('date_range')){
                
                        $dates = DateRange_to_Dates(request_ifset('date_range'));
                        $prep->date_start = $dates[0];
                        $prep->date_end = $dates[1];
                }
                $values = PrepSQLValues($prep);
                echo $MYB->InsertOrUpdate($values, "academy_schedule");
            break;
            
            case 'delete':
                
                echo $MYB->Delete($id, "academy_schedule");
            break;
           
        }
    break;
    }
    
    case 'ticket':{
    
        switch($action){
        
            case 'update':
            
            
                $prep = new stdClass();
                $prep->id        = $id;
                $prep->status   = request_ifset('status');
                $values = PrepSQLValues($prep);

                
                $Ticket         = $MYB->GetTicket($id, 'obj');
                $AgenteInfo     = Get_User_Info('id', $Ticket->creator_user_id);


            $email_content = <<<EOD
            
            <h2>Aggiornamento Ticket: ID #{$Ticket->id}</H2>
            <hr/>
            <b>Oggetto:</b><br/>
            {$Ticket->task_title}
            <hr/>
            <b>AGGIORNAMENTO</b>:<br/>
            Il ticket in oggetto è stato aggiornato con il seguente esito<br/>
            <b style="color:green">STATO: COMPLETATO</span></b>
            <hr/>
            
EOD;
            $formatted_email =  mount_email_template($email_content, 2, $Page);
            
            
            SendEmailWAttachments("[{$Page->PLATFORM_NAME} Ticket] AGGIORNAMENTO: {$Ticket->task_title}", $formatted_email, $AgenteInfo->email, "{$Page->PLATFORM_NAME} Ticket", "ticket@mybrokerage.it");
            
            echo $MYB->Update($values, "tickets", "id = {$id}");

                
            break;
        
        }
    break;
    }
    

    
    case 'inboundcalls': {

        switch($action){        
           
            case 'getUpdates':
          
            break;
            case 'create':
             
                if($json = json_decode(file_get_contents("php://input"), true)) {
                    
                    $prep = new stdClass();
                    
                    $prep->cli    = request_ifset('cli');
                    $prep->dndid    = request_ifset('dndid');
                    $prep->exten      = request_ifset('exten');
            
                    $values = PrepSQLValues($prep);
                    
                    echo $MYB->InsertOrUpdate($values, "calls_log");
                    
                    
                }
                    
            break;
           
        }
    break;
    }
 
    case 'maximizerleads': {

        switch($action){        
           
            case 'create':
             
                require_once __DIR__.'/include/Gestim.Class.php';
                $gestAPI = new Gestim("https://api.gestim.biz/v1/", "48c348c8da97225d9b9217bc7f9d7f2314de482f");

                $data = array();
                $data['ip'] = $_SERVER['REMOTE_ADDR']; //tipo IP (esempio: 127.0.0.1), campo obbligatorio
                $data['idRichiesta']='88888'; //tipo intero, campo obbligatorio
                $data['id_agenzia']='1008'; //tipo intero, campo obbligatorio
                $data['dominio']='miosito.it'; //tipo stringa
                $data['id_agente']='8057'; //tipo intero
                $data['codice']='string'; //tipo stringa
                $data['idImmobile']='0'; //tipo intero
                $data['nome']='TEST RICHIEST'; //tipo stringa
                $data['cognome']='string'; //tipo stringa
                $data['telefono']='string'; //tipo stringa
                $data['email']='test@pippocasa.it'; //tipo email (esempio: test@pippocasa.it)
                $data['cellulare']='3926389076'; //tipo stringa
                $data['fax']='string'; //tipo stringa
                $data['motivazione']='string'; //tipo stringa
                $data['categoria']='string'; //tipo stringa
                $data['citta']='Roma'; //tipo stringa
                $data['zona']=''; //tipo stringa
                $data['mq_da']='100'; //tipo numerico (accettati solo . no decimali)
                $data['mq_a']='150'; //tipo numerico (accettati solo . no decimali)
                $data['prezzo_da']='1000000'; //tipo numerico (accettati solo . no decimali)
                $data['prezzo_a']='1.500.000'; //tipo numerico (accettati solo . no decimali)
                $data['descrizione']='string'; //tipo stringa
                $data['piano']='string'; //tipo stringa
                $data['camere_da']='1'; //tipo intero
                $data['camere_a']='3'; //tipo intero
                $data['bagni_da']='1'; //tipo intero
                $data['bagni_a']='3'; //tipo intero
                $data['locali_da']='1'; //tipo intero
                $data['locali_a']='3'; //tipo intero
                $data['garage']='string'; //tipo stringa

                $json = $gestAPI->post("richieste", $data);
                echo $json;
                
                //echo $MYB->Update($values, "richieste", "id = {$id}");
            break;
           
        }
    break;
    }

    case 'scoutingcard':{
        switch($action){        
            case 'delete':{
                    $BuyerLead = $MYB->GetBuyerLead($id, 'obj');
                    // cancella notifica telegram 
                   
                    $MYB->Delete($id, "potentials");
                    
                echo 1;
                break;

            }
        }
        break;
    }



     case 'fsbo': {

        switch($action){        
           
            case 'getAlerts':
             
                require_once __DIR__.'/include/Casafari.Class.php';
                $Casafari = new Casafari();
                

                echo $Casafari->getAlerts($id, request_ifset('alert_date_from'), request_ifset('alert_subtype'), request_ifset('limit'));
                
            break;
            case 'getListing':
             
                require_once __DIR__.'/include/Casafari.Class.php';
                $Casafari = new Casafari();
                

                echo $Casafari->getListing($id);
                
            break;
            case 'verify':
                require_once __DIR__.'/include/Casafari.Class.php';
                $Casafari = new Casafari();
                $CRM = new Vtiger();

                $Listing =  $Casafari->getListing($id, 2832, 'obj');
                
                $check_contact_by_mobile=$CRM->Find_Contact_by_Mobile($Listing->contacts_info->phone);
                if($check_contact_by_mobile) {
                    
                    $idContatto = $check_contact_by_mobile;
                    $msg_box =  $CheckContactStatus = $CRM->CheckContactIfWorkable($idContatto, $User);

                }
                
                  header('Content-type: application/json');
                    echo $json = json_encode($msg_box);
                    die();
                
            break;
            case 'requestListing':
             
                require_once __DIR__.'/include/Casafari.Class.php';
                $Casafari = new Casafari();
                
                $Listing =  $Casafari->getListing($id, 2832, 'obj');

               
		if(DELTASCOUTING_CREDITS_ON === true) { 
               		$CheckCredits           = $MYB->CheckTodayCredits4FSBO($User->id);
		} else {
			$CheckCredits 		= true;
		}
		
		$IsWorkable             = $MYB->AlertIDIsWorkable($Listing->alert_id);

                
                if($CheckCredits && $IsWorkable){


                        $prep_contact = new stdClass();
                        $prep_contact->fullname = 'Privato';
                        $prep_contact->mobile = $Listing->contacts_info->phone;
                        $prep_contact->lead_source = 27;
                        
                        $idContatto = $MYB->NewContact($prep_contact->fullname, $prep_contact->mobile, false, false, $prep_contact->lead_source);

                        $prep = new stdClass();
                        $prep->opportunity_name = "{$Listing->type_group_ita} in {$Listing->address}";
                        $prep->opportunity_type = 1;
                        $prep->assigned_to = $User->id;
                        $prep->contact_id = $idContatto;
                        $prep->status = 1;
                        $prep->zone_id = '';
                        $prep->source_id = 14;
                        $prep->source_url = $Listing->listing_url;
                        $prep->price = $Listing->sale_price;
                        $prep->description = "({$Listing->total_area}mq) - ".$Listing->description;
                        $prep->company_id = COMPANY_ID;


                        $ZoneId = $MYB->Get("*", "array_map", "module = 'Potentials' AND field = 'opportunity_zone' AND name LIKE '%{$Listing->location->name}%' AND only_for = ".COMPANY_ID, "id ASC", 1, false, 'obj');
                        $prep->zone_id = $ZoneId[0]->value;

                        $values = $MYB->PrepSQLValues($prep);
                        $NewPotential = $MYB->InsertOrUpdate($values, "crm_potentials");

                        if($InsertToOldCRM){

                            $CRM = new Vtiger();

                            $check_contact_by_mobile=$CRM->Find_Contact_by_Mobile($Listing->contacts_info->phone);

                            if($check_contact_by_mobile) {
                                
                                $idContatto = $check_contact_by_mobile;
                                
            
                            } else {
                                // prepara array per creare il contatto
                                $dataContact=array(
                                    'firstname' => 'Privato',
                                    'lastname' => 'Privato',
                                    'mobile' => "{$Listing->contacts_info->phone}",
                                    'leadsource' => 'DeltaScout',
                                    'cf_761' => 'Venditore'
                                );
                                
                                // inserisci contatto e restituisci l'ID
                                $idContatto = $CRM->Create('Contacts', $dataContact);
                            }
                        
                            $dataAnnuncio=array(
                                'potentialname' => "{$Listing->type_group_ita} {$Listing->location->name} {$Listing->total_area}mq {$Listing->sale_price}€ {$Listing->address} ",
                                'cf_753' =>  "{$Listing->locations_structure[3]->name}",
                                'cf_759' =>  "{$Listing->listing_url}",
                                'sales_stage' => 'New',
                                'closingdate' => "$fn(today())",
                                'description' => "{$Listing->description}",
                                'leadsource' => 'DELTAScout',
                                'amount' => "{$Listing->sale_price}",
                                'contact_id' => $idContatto,
                                'opportunity_type' => 'Vendita Residenziale',
                                'assigned_user_id' => "19x{$User->crm_id}",
                                );
                                
                                

                            // crea l'opportunità
                            $idPOT = $CRM->Create('Potentials', $dataAnnuncio);
                            $CleanID = $CRM->ExtractID($idPOT);
                            $msg_box = "<div class='alert alert-success' style='color:#000'>Opportunità creata correttamente (<b>ID: {$CleanID})</b><hr/><a target='_blank' href='https://".CRM_DOMAIN."/index.php?module=Potentials&view=Detail&record={$CleanID}'><button class='btn btn-primary'>→ Apri Scheda Notizia nel CRM</button></a></div>";
                            ;
                            
                        }

                    if($NewPotential){
                        $msg_box = "<div class='alert alert-success' style='color:#000'>Opportunità creata correttamente (<b>ID: POT{$NewPotential})</b><hr/><a target='_blank' href='{$Page->BASE_URL_HTTPS}/apps/AgentFlowCRM/Potentials::POT{$NewPotential}/view'><button class='btn btn-primary'>→ Apri Scheda Notizia nel CRM</button></a></div>";
                    }

                   
                    //exec("/usr/bin/xvfb-run --server-args=\"-screen 0, 1920x1080x24\" CutyCapt --url={$Listing->listing_url} --out=/home/remaxdelta/www/remax-delta.it/admin/assets/generated_content/cached-pot/$idPOT.pdf 2>&1", $output, $return_var);
                    
                    save_in_db("INSERT INTO scout_credits (user_id, credits, pot_id, alert_id) VALUES ('{$User->id}', 1, '{$NewPotential}', '{$Listing->alert_id}')");
                    
                   
                
                } 
                if(!$IsWorkable){
                    $msg_box = "<div class='alert alert-warning' style='color:#000'>Questa notizia è già stata scaricata in data odierna. <br/>Non è stato utilizzato nessun credito.</b></div>";

                }
                if(!$CheckCredits){
                    $msg_box = "<div class='alert alert-danger' style='color:#000'>Crediti giornalieri esauriti</b></div>";
                }
                
                 header('Content-type: application/json');
                    echo $json = json_encode($msg_box);
                    die();
                
            break;
           
        }
    break;
    }
    
      case 'pbx': {

        switch($action){        
           
            case 'listen':
            
                header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
                header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
                header("Cache-Control: post-check=0, pre-check=0", false);
                header("Pragma: no-cache");
                header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

             
                echo $Listening =  $MYB->PBX_Listening($User->pbx_exten, 5, 'json');
             
               
            break;
            case 'SSE':
            
        
                // Set file mime type event-stream
                header('Content-Type: text/event-stream');
                header('Cache-Control: no-cache');

                // Loop until the client close the stream
                while (true) {

                // Echo time
                $time = date('r');
                echo "data: The server time is: {$time}\n\n";
                
                // Flush buffer (force sending data to client)
                flush();

                // Wait 2 seconds for the next message / event
                sleep(2);  
                }
               // echo $MYB->PBX_Listening_SSE($User->pbx_exten, 5, 'json');
                //flush();
             
               
            break;
           
        }
    break;
    }
     case 'PACatasto': {

        switch($action){        
           
            case 'getProspetto':
                require_once __DIR__.'/include/PA.Class.php';
                $OpenApi = new OpenApi("catasto.openapi.it");
                

                echo $OpenApi->getProspettoCatastale("F","RM","GROTTAFERRATA","18","1962","4");
            break;
            case 'getElencoImmobili':
                require_once __DIR__.'/include/PA.Class.php';
                $OpenApi = new OpenApi("catasto.openapi.it");
                
                #echo $OpenApi->getProspettoCatastale("F","RM","GROTTAFERRATA","18","1962","");
                echo $OpenApi->getElencoImmobili("F","RM","GROTTAFERRATA","18","1962");
            break;
            case 'getAddressID':
                require_once __DIR__.'/include/PA.Class.php';
                $OpenApi = new OpenApi("catasto.openapi.it");
                echo $OpenApi->getAddressID(request_ifset('provincia'), request_ifset('comune'), request_ifset('indirizzo'));
            
            break;
            case 'getRichiestaCatasto':
                require_once __DIR__.'/include/PA.Class.php';
                $OpenApi = new OpenApi("catasto.openapi.it");
                echo $OpenApi->getRichiestaCatasto($id);
            break;
            case 'getRichiestaRintraccio':
                require_once __DIR__.'/include/PA.Class.php';
                $OpenApi = new OpenApi("rintraccio.openapi.it");
                echo $OpenApi->getRichiestaRintraccio($id);
            break;
             case 'getRintraccio':
                require_once __DIR__.'/include/PA.Class.php';
                $OpenApi = new OpenApi("rintraccio.openapi.it/richiesta");
                
                $response = $OpenApi->getRintraccio($id,"telefoni" );
                $res        = json_decode($response);
            
                print_r($res);
                    $response_id = $res->data->id;
                    
                    $prep               = new stdClass();
                    $prep->user_id      = $User->id;
                    $prep->module       = "rintraccio";
                    $prep->type         = "telefoni";
                    $prep->ref_id       = $response_id;
                    $prep->ref_name     = $id;
                    
                    
                    $values = PrepSQLValues($prep);
                    echo $MYB->InsertOrUpdate($values, "pa_requests");
                
            break;
            
        }
    break;
    }
    case 'GEO': {

        switch($action){        
           
            case 'getByAddress':
                require_once __DIR__.'/include/PA.Class.php';
                $OpenApi = new OpenApi("geocoding.realgest.it");
                

                echo $OpenApi->GEOByAddress(request_ifset('q'));
            break;
            
            
        }
    break;
    }
    case 'getMapValues': {
        $module = $id;
        $field = $action;
        echo $MYB->GetMapValues($module, $field);
    
    }
    case 'tags': {

        if($action == 'getList'){
            $module = $id;
            if(request_ifset('term')) {
                $term = request_ifset('term');
                $where = " AND tagname LIKE '%{$term}%'";
            }
            $Results = $MYB->Get('id, tagname as name', 'tags', "module = '{$module}' {$where} AND (only_for_user = '{$User->id}' OR only_for_user = 0) AND company_id = ".COMPANY_ID, 'id desc', 50, false, 'obj');
            $Output['items'] = $Results;
            echo json_encode($Output);
        }
    }
    break;

    case 'validatePhoneNumber':{

        switch($action){
            case 'formatE164':

                
                $resp =  ValidatePhoneNumber($id);
                echo $resp['phone_number'];

            break;
            case 'lookup':
        
                $resp =  ConvertPhoneNumber($id);
                echo $resp;

            break;

        }


    }
    break;
    case 'upload':{

        switch($action){
            case 'vtour':
                $content = $_FILES['content'];
                $rif_id = $id;
                $success = null;

                $path_to = __DIR__."/assets/generated_content/vtour/".COMPANY_ID."/{$rif_id}";
                $zip = $path_to."/".$content['name'];


                if(upload_content($content, $path_to, "vtour")){
                    $success = true;
                

                } else {
                    $success = false;
                }
                
                if ($success === true) {
                
                    $output = [];

                } elseif ($success === false) {

                    $output = ['error'=>'Error while uploading.'];
                    // delete any uploaded files
                    foreach ($paths as $file) {
                        unlink($file);
                    }

                } else {
                
                    $output = ['error'=>'Error'];
                }
             
                echo json_encode($output);
		$dest = __DIR__."/storage/s3-myb-b1/c-1/vtour/{$rif_id}/";
                $zip = new ZipArchive;
                $res = $zip->open($path_to."/vtour.zip");
                $zip->extractTo($path_to."/", 'app-files/data.js');
                extract_zip_subdir($path_to."/vtour.zip", "tiles", $path_to, "/tmp/");
		#$MYB->UploadToCDN($path_to."/", "/vtour/{$rif_id}/");
		$path_to_destination = __DIR__."/storage/s3-myb-b1/c-1/vtour/{$rif_id}/";
		#echo shell_exec("cp -R {$path_to}/ {$path_to_destination}");
            break;
        }

    }
    break;
    case 'calendar':{


        switch($action){

            case 'newEvent':

                $entity = request_ifset('entity');
                $entity_id = request_ifset('entity_id');
                $force_token = false;
                $calendarId = $id;

                $duration = request_ifset('event_duration');
                $event_type = request_ifset('event_type');
                $startdate = new DateTime(request_ifset('event_time'), new DateTimeZone("Europe/Rome"));
                $startdate->setTimezone(new DateTimeZone("UTC"));
                $enddate = new DateTime(request_ifset('event_time'), new DateTimeZone("Europe/Rome"));
                $enddate->setTimezone(new DateTimeZone("UTC"));
                $enddate = $enddate->modify("+{$duration} minutes");
                
                if(str_contains($id, 'personal.') && is_backoffice()) {
                    $explode = explode('.',$id);
                    $forced_user_id = hashid($explode[1], 'decode', 12);                    
                    $CalendarUser = my_all("SELECT id,name,gcalendar_token FROM users WHERE id = '{$forced_user_id}' AND company_id = ".COMPANY_ID." LIMIT 1");
                    $CalendarUser = $CalendarUser[0];

                } else {
                    $CalendarUser = $User;
                }

                if($entity && $entity_id){

    
                    $EventInfo = $MYB->GenerateEventInfo($Page, $entity, $entity_id,  $startdate->format('Y-m-d\TH:i:s\Z'),  $enddate->format('Y-m-d\TH:i:s\Z'), $event_type);
                    if($event_type == 11 || $event_type == 12 || $event_type == 13 || $event_type == 14 || $event_type == 16){
                        //handle as invitation - useful for not setup any agent gcalendar
                        $force_token = GCALENDAR_ACCESS_TOKEN;
                        $calendarId = GCALENDAR_PROPERTY_VISITS_ID;
                    }
                } else {


                    $event_type_text = map_get_value('agenda', 'event_type', request_ifset('event_type'));

                    $EventInfo = new stdClass();
                    $EventInfo->company_id = COMPANY_ID;
                    $EventInfo->title = "({$event_type_text}) {$fn(request_ifset('event_name'))}";
                    $EventInfo->type = request_ifset('event_type');
                    $EventInfo->description = request_ifset('event_description');
                    
                    
                    $EventInfo->startDate = $startdate->format('Y-m-d\TH:i:s\Z');
                    $EventInfo->endDate = $enddate->format('Y-m-d\TH:i:s\Z');

                    $EventInfo->description .= <<<EOD

- Evento inserito da {$Page->PLATFORM_NAME} -
EOD;

                    if(request_ifset('is_shared')) {

			    //handle as invitation - useful to NOT to setup any agent gcalendar
                        $calendarId = request_ifset('event_room');
                        $force_token = GCALENDAR_ACCESS_TOKEN;
                        $EventInfo->description = "- Creato da {$User->name} -".$EventInfo->description ;


                    }

                   # print_r($EventInfo);


                }

                
                echo $MYB->GoogleCalendar_NewEvent($calendarId, $CalendarUser->id, $EventInfo, $entity, $entity_id, $force_token);
    

            break;
        
            case 'getEvents':
                header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
                header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
                header("Cache-Control: post-check=0, pre-check=0", false);
                header("Pragma: no-cache");
                header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

                $GCalendarInstance = $MYB->GoogleCalendarNewInstance($User->id, $id);

            //    $todayStart = new \DateTime('today midnight', new DateTimeZone("Europe/Rome"));
                $timestamp_start = request_ifset('start');
                $timestamp_end = request_ifset('end');

                $optParams = array(
                    'maxResults' => 100,
                    'orderBy' => 'startTime',
                    'singleEvents' => TRUE,
                    'timeMin' => $timestamp_start,
                    'timeMax' => $timestamp_end
                );

                $results = $GCalendarInstance->service->events->listEvents($GCalendarInstance->calendarId, $optParams);

                if (count($results->getItems()) == 0) {
                    print "No upcoming events found.\n";
                } else {
                        $i=0;
                    foreach ($results->getItems() as $event) {

                    $start = $event->start->dateTime;
                    if (empty($start)) {
                        $start = $event->start->date;
                    }

                    
                    $eventres[$i]['id'] = $event->id;;
                    $eventres[$i]['start'] = $start;
                    $eventres[$i]['end'] = $event->end->dateTime;
                    $eventres[$i]['title'] = $event->getSummary();
                    $eventres[$i]['url'] = $event->htmlLink;
                    $eventres[$i]['description'] = $event->description;
                    $eventres[$i]['location'] = $event->location;
                    $eventres[$i]['organizer_email'] = $event->organizer->email;
                    $MYB_Event_Info = $MYB->GetCalendarEventByGoogleCalId($event->id, 'obj');
                    if($MYB_Event_Info){
                        $eventres[$i]['entity'] = $MYB_Event_Info->entity;
                        $eventres[$i]['entity_id'] = $MYB_Event_Info->entity_id;
                        $eventres[$i]['event_type'] = map_get_value('agenda', 'event_type', $MYB_Event_Info->type);

                    }
                        $i++;
                    }
                }
                echo json_encode($eventres);
            break;

            case 'deleteEvent':

                $eventID = request_ifset('eventID');
                $force_token = false;

                if(!is_backoffice()) {
                    $add_where = "AND user_id = '{$User->id}'";
                }

                $Event = $MYB->GetCalendarEvents("cal_event_id = '{$eventID}' {$add_where}", 'obj');

                if(request_ifset('is_shared')){
                    $force_token = GCALENDAR_ACCESS_TOKEN;
                    $add_where = '';
                    
                    if($Event){
                        $GCalendarInstance = $MYB->GoogleCalendarNewInstance($User->id, $Event->gcal_id, $force_token);
                        $results = $GCalendarInstance->service->events->delete($GCalendarInstance->calendarId, $eventID);
                        
                        if($results)   echo $MYB->SoftDelete($Event->id, 'cal_events', 'status', 2);

                    } else {

                        if(is_backoffice()){

                            $CalendarInfo = $MYB->GetCalendar($id, 'obj');
                            $GCalendarInstance = $MYB->GoogleCalendarNewInstance($User->id, $CalendarInfo->cal_id, $force_token);
                            $results = $GCalendarInstance->service->events->delete($GCalendarInstance->calendarId, $eventID);
        
                            if($results) echo 1;

                        }

                    }

                } else {
                    
                    $GCalendarInstance = $MYB->GoogleCalendarNewInstance($User->id, $id, $force_token);
                    $results = $GCalendarInstance->service->events->delete($GCalendarInstance->calendarId, $eventID);

                    if($Event && $results){
                        echo $MYB->SoftDelete($Event->id, 'cal_events', 'status', 2);
                    } else {
                        if($results) echo 1;
                    }
                }


                
            break;
        }
    }   
    break;
case 'WAConnector':{

	switch($action){

		case 'getQRCode':
			$acctok = $User->wa_access_token;
			if(!$User->wa_instance_id){
                $instance =  file_get_contents("https://app.waconnector.it/api/create_instance?access_token={$acctok}");
			    $instance = json_decode($instance);
                $wa_instance_id = $instance->instance_id;
            } else {
                $wa_instance_id = $User->wa_instance_id;
            }
			$prep               = new stdClass();
			$prep->id = $User->id;
			$prep->wa_instance_id = $wa_instance_id;

                    	$values = PrepSQLValues($prep);
                    	$MYB->InsertOrUpdate($values, "users");

			$content = file_get_contents("https://app.waconnector.it/api/get_qrcode?instance_id={$wa_instance_id}&access_token={$acctok}");
			$res = json_decode($content);
            if($res->status == 'success') {
                echo $content;
            } 
            if($res->status == 'error' && $res->message == "È stato utilizzato l'ID istanza"){
                $data['base64'] = 'data:image/png;base64, ';
                echo json_encode($data);
            }
            break;

        case 'resetInstance':
			$acctok = $User->wa_access_token;
			if($User->wa_instance_id){
              $instance =  file_get_contents("https://app.waconnector.it/api/reset_instance?instance_id={$wa_instance_id}&access_token={$acctok}");
            } 
			$prep               = new stdClass();
			$prep->id = $User->id;
			$prep->wa_instance_id = '';

                    	$values = PrepSQLValues($prep);
                    	echo $MYB->InsertOrUpdate($values, "users");

		break;

         case 'send':

		 if(request_ifset('media')) {		
			$Send = WAConnector_Send(ConvertPhoneNumber(request_ifset('phone')), $_REQUEST['content'], $User->id, "media", "https://mybrokerage.app/files_generated/".FCID."/MediaUploads/".request_ifset('media'));
		} else {

			$Send = WAConnector_Send(ConvertPhoneNumber(request_ifset('phone')), $_REQUEST['content'], $User->id);
		}

            if($Send->key->id) {
                $response['message'] = "Messaggio Inviato ({$Send->key->id})";
                echo json_encode($response);
            } else {
                http_response_code(406);
            }
		break;
	}

 }
    break;
    case 'automation':

            switch($id){

                    case 'weeklyreport':


                        $template = $_REQUEST['t'];

                        $WeeklyReportData = $MYB->GenerateReport(request_ifset('rif_id'), 'weekly');

                        $params = object_to_array($WeeklyReportData);
                        $append_params = http_build_query($params).'&';
                        $append_params = str_replace('photo_url=', 'photo_url[image]=', $append_params);
                        $append_params .= http_build_query($_REQUEST);

                        $filename = GenRandomString(10);

                        file_put_contents(__DIR__."/files_generated/temp/{$filename}.png", file_get_contents("https://api.placid.app/u/{$template}?{$append_params}"));
                   

                        $msg = <<<EOD
Gentile Cliente
di seguito il Report Settimanale delle attività effettuate sul suo immobile.

Potrà contattare il suo agente di riferimento per qualsiasi informazione.

Cordialmente
DELTA & Partners
www.deltaepartners.it

(_Messaggio automatico_)
EOD;
$msg_cc = <<<EOD

*$Page->PLATFORM_NAME* -- Messaggio inviato automaticamente al cliente:

{$msg}
EOD;
                       #WAConnector_Send('3939263', $msg, false, 'media', "{$Page->BASE_URL_HTTPS}/assets/generated_content/{$filename}.png");


$test_mode = false;
if($test_mode) {
	$params['listing_agent_mobile'] = '393927754719';
	$params['cell_cliente'] = '393927754719';
}
			WAConnector_Send($params['listing_agent_mobile'], $msg_cc, false, 'media', "{$Page->BASE_URL_HTTPS}/files_generated/temp/{$filename}.png");
                        WAConnector_Send($params['cell_cliente'], $msg, false, 'media', "{$Page->BASE_URL_HTTPS}/files_generated/temp/{$filename}.png");
echo "sent ---> to --> {$params['cell_cliente']}";

                    break;


            }

    break;
    case 'MediaGenerator':{
        switch($id){
            case 'weeklyreport':
	    
                $template = $_REQUEST['layer'];

			 $WeeklyReportData = $MYB->GenerateReport(request_ifset('id_annuncio'), 'weekly');

                        $params = object_to_array($WeeklyReportData);
                        $append_params = http_build_query($params).'&';
                        $append_params = str_replace('photo_url=', 'photo_url[image]=', $append_params);
                        #$append_params .= http_build_query($_REQUEST);


		    break;
	    case 'image':

                $template = $_REQUEST['layer'];

                    $Property = new Property();
                    $Property->rif_id = request_ifset('id_annuncio');
                    $PropertyData = $Property->GetFullData();

                     
                    $params = new stdClass;
                    $params->rif_id = $PropertyData->rif_id;
                    $params->offer_type = $PropertyData->offer_type;
                    $params->city = $PropertyData->city;
                    $params->address = "{$PropertyData->address} {$Property->number}";
                    $params->price = $PropertyData->price;
                    $params->mq_tot = $PropertyData->mq_tot;
                    $params->bedrooms = $PropertyData->bedrooms;
                    $params->bathrooms = $PropertyData->bathrooms;
                    $params->rooms = $PropertyData->rooms;
                    $params->listing_agent_name = $PropertyData->listing_agent_name;
                    $params->listing_agent_mobile = $PropertyData->consulente_cell;
                    $params->listing_agent_email = $PropertyData->consulente_email;
                    $params->features = $PropertyData->imm_features;
                    $params->photo_url = $Property->GetCover();

                    $params = object_to_array($params);

                    $append_params = http_build_query($params).'&';
                    $append_params = str_replace('photo_url=', 'photo_url[image]=', $append_params);


               break;
	}    

	$append_params .= http_build_query($_REQUEST);

                #echo "https://api.placid.app/u/{$template}?{$append_params}";die();
	if($_REQUEST['dd']) {
                header("Content-Type: image/png");
                echo curlize("https://api.placid.app/u/{$template}?{$append_params}");
	} else {
                header("Content-Type: image/png");
                echo base64_encode(curlize("https://api.placid.app/u/{$template}?{$append_params}"));
	}	
                
    }
    break;
    default: 
    
    http_response_code(401);
    break;
    
    

} 

