<?php
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);     
ini_set("default_charset","UTF-8");  
ini_set("display_errors",1);
define('sugarEntry', 'index.php');
require_once('include/entryPoint.php');
require_once('include/utils/file_utils.php');
ob_start();

require_once('soap/SoapError.php');         
require_once('include/nusoap/nusoap.php');
require_once('modules/Contacts/Contact.php');   
require_once('modules/Accounts/Account.php');
require_once('modules/Opportunities/Opportunity.php');
require_once('modules/Cases/Case.php');
require_once('modules/Accounts/Account.php'); 

include_once('modules/Users/User.php');
///ALTER TABLE `sugarcrm_300610_test3`.`contacts` DROP INDEX `phone_search`,
// ADD INDEX `phone_search`(`phone_home`, `phone_work`, `phone_other`, `phone_fax`, `phone_mobile`, `deleted`);

//ALTER TABLE `sugarcrm_300610_test3`.`leads` ADD INDEX `phone_search`(`converted`, `phone_home`, `phone_mobile`, `phone_work`, `phone_other`, `phone_fax`, `deleted`);  
 
 $tm="1288387440";
 $a=$tm/24/60/60;
 
 

debvp(var_export($_REQUEST,true));         

                                                                       
$dt=$_REQUEST['voip'] ;
$dt=base64_decode($dt);
$dt=unserialize($dt);


foreach ($dt as $k=>$v){
$dto->$k=$v;
}
$dt=$dto;

if ($dt->sugar_username=="" or $dt->sugar_password==""){
echo "access forbiden - no username or password provided";
  exit;  
}else{
 $loginok=validate_sugar_user($dt->sugar_username, $dt->sugar_password);
 if ($loginok==false){
  echo "access forbiden - wrong username or password provided";       
  exit;
 }
}

  $username= $dt->sugar_username;
  $password= $dt->sugar_password;

  //var_export($dt,true);
 if ($dt->action==""){
   $dt->action="get_number"; 
 }
 
  //action
  
  
  

debvp( "
start1"); 
debvp($fp, "
dobj:".$dto->EVENT_DATE); 
//fwrite($fp, "
//darr:".$dto['EVENT_DATE']); 
debvp( var_export($dt,true)); 
debvp( var_export($dto,true));


 
if ($dt->action=="update_answered"){   
  update_answered($dt->SUGAR_CALL_ID,"Held",$dt->EVENT_DATE,$dt->SUGAR_ANSWERED);
} 

if ($dt->action=="update_end"){   
  update_end($dt->SUGAR_CALL_ID,$dt->SUGAR_MICROTIME,$dt->EVENT_DATE,$dt);
} 



 
if ($dt->action=="get_number"){
debvp("Nmbr".$dt->SUGAR_REAL_NUMBER);
 $ret=SearchByPhoneNumber($username,$password,$dt->SUGAR_REAL_NUMBER,$dt->EVENT_DATE,$dt) ;
//  $ret=SearchByPhoneNumber($username,$password,"0722608054",$dt->EVENT_DATE,$dt) ; 
 
debvp("Return:".var_export($ret,true));         
  
  ob_clean();  
   //  print_r($ret); 
 
//exit;
 $ret=serialize($ret);
 $ret=base64_encode($ret);

  
debvp("Return:".$ret);         

 echo $ret;
      $content = ob_get_contents();
    ob_end_clean();  
    echo $content;  
 
 //print_r($ret);
}

function get_extension_from_channel($SUGAR_CHANNEL){
 
 debvp("
Sugar Chanel:".$SUGAR_CHANNEL );         


    if (preg_match('~^(.*)/(.*)-([0-9a-zA-Z].*)$~', $SUGAR_CHANNEL, $match) )
    {
        $answered_ext = trim($match[2]);
        $answered_protocol = trim($match[1]);
        
    }


 debvp("
Sugar Ext:".$answered_ext );         


  return $answered_ext;
}
 
 function get_user_from_extension($extension){
  global $db,$current_user;
$sq="select * from dmc_sugarcrmvoipconnector where extension='".$extension."' and deleted=0";
$r=$db->query($sq);
$row=$db->fetchByAssoc($r);
$user_ext=$row['assigned_users'];
 if ($user_ext!=""){
 //change admin user with the extemsion user
  $current_user=new User();
  $current_user->retrieve($user_ext);
 }
//$current_user

return $user_ext;
 }
 
   function get_extension_from_user($extension){
  global $db,$current_user;
$sq="select * from dmc_sugarcrmvoipconnector where assigned_users='".$extension."' and deleted=0";
$r=$db->query($sq);
$row=$db->fetchByAssoc($r);
$user_ext=$row['extension'];


return $user_ext;
 }
 
 function update_end($call_id,$microtime,$event_date,$dt){

$extension=get_extension_from_channel($dt->channel);
$extension_user_id= get_user_from_extension($extension);

 if ($dt->direction=="INBOUND"){ 

$only_last_call=true;
//if onanswer does not trigger
if ($only_last_call==true){
$extension=get_extension_from_channel($dt->dstchannel);
$extension_user_id= get_user_from_extension($extension);

 $cl=new Call();
 $cl->retrieve($call_id);
 $cl->direction="Inbound";
 if ($dt->disposition=="ANSWERED"){
  $cl->status="Held";
 }else{
  $cl->status="Not Held";
 }
 $cl->save(); 

     global $db;     
     $sq="update calls_cstm set     answered_c='".$dt->answer."' where id_c='".$call_id."' ";
    $db->query($sq); 
     $sq="update calls_cstm set     call_ended_c='".$dt->end."' where id_c='".$call_id."' ";
    $db->query($sq); 
    $sq="update calls set date_start='".$dt->start."' where id='".$call_id."' and deleted=0";
    $db->query($sq);  
    if ($cl->status=="Held"){
    $sq="update calls_cstm set call_duration_c=TIMEDIFF(`call_ended_c`,`answered_c`) where id_c='".$call_id."'";
    $db->query($sq);    
    } 
    //on ver 2.0 is assigned user is there from answered action 
    //should be used only for 1.6   
if ($dt->disposition=="ANSWERED" and $extension_user_id!=""){   //'dstchannel' => 'Local/LC-008@from-internal-f457,1', not covered
    $sq="update calls set assigned_user_id='".$extension_user_id."' where id='".$call_id."' and deleted=0";
    $db->query($sq);      
}
}else{
//endif no trigger

   $diff= $microtime; 
$daysDiff = floor($diff/60/60/24); 
  $diff -= $daysDiff*60*60*24; 
  $hrsDiff = floor($diff/60/60); 
  $diff -= $hrsDiff*60*60/1000; 
  $minsDiff = floor($diff/60); 
  $diff -= $minsDiff*60; 
  $secsDiff = floor($diff); 
 $fp = fopen('__1111called_testa.txt', 'a+');
fwrite($fp,"
ds:".$daysDiff." h:".$hrsDiff."m:".$minsDiff."s:".$secsDiff." event date ".$event_date );         
fclose($fp);

     global $db;     
     $sq="update calls_cstm set     call_ended_c='".$event_date."' where id_c='".$call_id."' ";
    $db->query($sq);
   
 debvp("
sq:".$sq );         


    $sq="update calls set duration_hours='".$microtime."' where id='".$call_id."' and deleted=0";
    $db->query($sq);
    $sq="update calls_cstm set call_duration_c=TIMEDIFF(`call_ended_c`,`answered_c`) where id_c='".$call_id."'";
    $db->query($sq);
}
 
 }else{
 ///pr1v1    
 ///pr1v1    
 }
    
    
    
  
 debvp("
sq:".$sq );         
   
 }
 
 function update_answered($call_id,$status,$event_date,$SUGAR_ANSWERED){
//$extension=get_extension_from_channel($SUGAR_ANSWERED);
$extension= $SUGAR_ANSWERED;
$extension_user_id= get_user_from_extension($extension);

 debvp("
Ans Ext:".$SUGAR_ANSWERED." Found User: ".$extension_user_id );         
 
    global $db;     
    $sq="update calls set status='".$status."',direction='Inbound' where id='".$call_id."' and deleted=0";
    $db->query($sq);
    $dst=date("Y-m-d H:i:s");
    $sq="update calls set date_start='".$dst."' where id='".$call_id."' and deleted=0";
    $db->query($sq);
      $sq="update calls_cstm set     answered_c='".$event_date."' where id_c='".$call_id."' ";
    $db->query($sq);
    $sq="update calls set assigned_user_id='".$extension_user_id."' where id='".$call_id."' and deleted=0";
    $db->query($sq);    
 
 }
 
    
function create_session($user_name, $password)
{
    if(validate_sugar_user($user_name, $password))
    {
        return "Success";
    }

    return "Failed";
}
           

 
 
 
        
            
 function LogSugarCallRecord($username,$password,$subject,$startdate,$rel_to_type,$rel_to_id,$description,$add_type,$old_id,$taskdtls,$accountid,$call_type_c,$telnumber,$out_passed_case_id,$out_passed_opportunities_id,$out_passed_projects_id)
{

    validate_sugar_user($username, $password);
    global $current_user,$adb;
     require_once('modules/Calendar/DateTimeUtil.php');
     $td = new TimeDate();  
 $newtime= $td->handle_offset($startdate, "Y-m-d H:i:s", true,$current_user);
 $date_due_in_db_fmt=$td->swap_formats($startdate,"Y-m-d H:i:s", $td->get_date_time_format(true, $current_user));
   // echo $date_due_in_db_fmt;




    require_once('modules/Calls/Call.php');         
   $obj=new Call();
  
    $obj->name=$subject;
     $obj->date_start=$date_due_in_db_fmt;

     $obj->parent_type= $rel_to_type;      
     $obj->parent_id= $rel_to_id;        
 
 $_REQUEST['relate_id'] = $rel_to_id;
 $_REQUEST['relate_to'] = $rel_to_type;  
     
if ($accountid!=""){
     $_REQUEST['relate_id'] = $accountid;
 $_REQUEST['relate_to'] = "Accounts";  
     $obj->parent_type= "Accounts";      
     $obj->parent_id= $accountid;                

}
if ($rel_to_type=="Contacts"){ 
 $obj->contact_id=$rel_to_id;
 $_REQUEST['relate_id'] = $rel_to_id;
 $_REQUEST['relate_to'] = $rel_to_type;  

} 
if ($rel_to_type=="Leads"){ 
 $obj->lead_id=$rel_to_id;
  $_REQUEST['relate_id'] = $rel_to_id;
 $_REQUEST['relate_to'] = $rel_to_type;  
}


         
     $obj->save();
     global $db;
     $sq="select * from calls where id='".$obj->id."' and deleted=0";
     $r=$db->query($sq);
     $row_c=$db->fetchByAssoc($r);
     $saved_date=$row_c['date_start'];

  $GLOBALS['log']->fatal("obj type case id".$out_passed_case_id);      
 
$user_id = $userid ;
    $current_user = $seed_user;
    return $obj->id;   

  
   
}






  

function validate_sugar_user($user_name, $password){
global $server, $current_user, $sugar_config, $system_config;
$username = utf8_decode($username); 
$password = utf8_decode($password); 
    $user = new User();

    $user->user_name = $user_name;
    $system_config = new Administration();
    $system_config->retrieveSettings('system');
    $authController = new AuthenticationController((!empty($sugar_config['authenticationClass'])? $sugar_config['authenticationClass'] : 'SugarAuthenticate'));


    if($user->authenticate_user(md5($password))){
        $user->disable_row_level_security=true;
        $user->retrieve($user->id);
        $current_user = $user;
        return true;
    }else{
        $GLOBALS['log']->fatal("SECURITY: failed attempted login for $user_name using SOAP api");
        echo "Error847";
        return false;
    }

}



///pr2v1

///pr2v1


function ConverPhoneNumberForMySqlSearch($telnumber){
    $newnumber="";
    for ($i = 0; $i<= strlen($telnumber); $i++) {
         if (strlen(trim($newnumber))==0){
            $newnumber="%";
         }
if ( 
($i==0 and $telnumber{$i}=="0") or 
($i==1 and $telnumber{$i}=="0") or 
($i==0 and $telnumber{$i}=="+")){
   //skip
}else{    
          $newnumber.=  $telnumber{$i}."%";
}  
}


 return $newnumber;
}


function SearchByPhoneNumber($username,$password,$telnumber,$evdate,$dt)

{
    $savecall=1;
    $orig_telnumber=$telnumber;
   $telnumber= ConverPhoneNumberForMySqlSearch($telnumber)  ;
     

$username = utf8_decode($username); 
$password = utf8_decode($password); 
$sstr = utf8_decode($sstr); 

    if(!validate_sugar_user($username, $password)){
    echo "LoginFailed";
    exit;
    }else{
 
     $SugarObject =   GetSugarObject($telnumber,$out_passed_contact_id,$out_passed_lead_id,$out_passed_account_id);

 

   
   if ($savecall==1){
    if ($SugarObject[0]["stype"]=="Contacts" or $SugarObject[0]["stype"]=="Leads" or 1==1){
            $duration_h = 0;
            $duration_min = 0;
            $add_type="Call";
            $rel_to_id = $SugarObject[0]["id"];
            $rel_to_type = $SugarObject[0]["stype"];
            $CustomerID= $SugarObject[0]["CustomerID"];      
            $taskdtls[0]["direction"]=$direction;
            $taskdtls[0]["status"]=$status;

////////force to save with provided contact / lead id
if ($out_passed_contact_id!=""){
   $rel_to_id=$out_passed_contact_id;
   $rel_to_type="Contacts";
   $CustomerID=$out_passed_account_id;
}   

if ($out_passed_lead_id!=""){
   $rel_to_id=$out_passed_lead_id;
   $rel_to_type="Leads";
   $CustomerID="";
} 
/////////////////endforce


  if ($dt->direction=="INBOUND"){
 $subject="Call from :".$orig_telnumber;  
  }else{
 $subject="Outbound Call :".$orig_telnumber;  
 }
 
 
 $SugarCallRecord = LogSugarCallRecord($username,$password,$subject,$call_dt,$rel_to_type,$rel_to_id,$description,$add_type,$old_id,$taskdtls,$CustomerID,$call_type_c,$orig_telnumber,$out_passed_case_id,$out_passed_opportunities_id,$out_passed_projects_id);
 if ($dt->direction=="INBOUND"){
  $dirct="Inbound"; 
 }else{
  $dirct="Outbound";  
 }

  global $db;  
//pr5v1  

//pr5v1 
 //outbound_extension
 

 $sq="update calls set direction='".$dirct."',status='Not Held' where id='".$SugarCallRecord."' and deleted=0";  
 $db->query($sq);
    $sq="update calls set date_start='".$dt->EVENT_DATE."' where id='".$SugarCallRecord."' and deleted=0";
    $db->query($sq);   
 

debvp("Dir:".$dt->direction." Sq:".$sq);         

 
 
       $SugarObject[0]["SavedCallID"]=$SugarCallRecord;
       foreach ($SugarObject as $k=>$v){
         $SugarObject[$k]["SavedCallID"]=$SugarCallRecord; 
       }
$ol_resp=$SugarObject[0];
       unset($SugarObject);   
	   $SugarObject[0]=$ol_resp;    

   }
}else{
   $SugarObject[0]["SavedCallID"]="none";
}
 $SugarObject=xml_populate_empty_vals($SugarObject) ;

  
return $SugarObject;

}
}

function xml_populate_empty_vals($SugarObject){
if (!isset($SugarObject[0]["id"])){
 $SugarObject[0]["id"]="";
}
if (!isset($SugarObject[0]["CustomerID"])){
 $SugarObject[0]["CustomerID"]="";
}
 if (!isset($SugarObject[0]["ContactName"])){
 $SugarObject[0]["ContactName"]="";
}
if (!isset($SugarObject[0]["CompanyName"])){
 $SugarObject[0]["CompanyName"]="";
}
if (!isset($SugarObject[0]["stype"])){
 $SugarObject[0]["stype"]="";
}   
return $SugarObject; 
}

function RetrieveSugarData($query,$seed_contact,$output_list,$str,$type){
global $db;
$aai=0;
    $result = $db->query($query,true," Error filling in additional detail fields: ");
    $totnr = $db->getRowCount($result);
        while($aai<=$totnr)
    {
    $contact= $db->fetchByAssoc($result, $aai, false);


if(is_null($contact["name"])){
$contact["name"]="";
}

if ($type=="cts"){
$contact["name"]=$contact["first_name"]." ".$contact["last_name"];
}
if ($type=="lds"){
$contact["name"]=$contact["first_name"]." ".$contact["last_name"];
}

        $output_list[] = Array(
                "id" => $contact["id"], "CustomerID" => $contact["id"], "CompanyName"=>$contact["name"],  );


              $aai++;
    }

    $seed_contact = $seed_contact;
return $output_list;
}



   




 function GetSugarObject($telnumber){
     $out_passed_account_id=str_replace("/","",$out_passed_account_id);
global $db;
global $SugarObject;
$aai=0;
  $found_contacts=0;
  $found_leads=0;
  $totnr_users=0;
  $found_accounts=0;
########
 


///pr3v1
///pr3v1

 
  IF ($totnr_users==0){
  $query = get_search_sql("Contacts",$telnumber);
  global $db;
$aai=0;

    $result = $db->query($query,true," Error filling in additional detail fields: ");
    $totnr = $db->getRowCount($result);
        $found_contacts= $totnr;
        while($aai<=$totnr)
    {
    $contact= $db->fetchByAssoc($result, $aai, false);

     if ($contact["id"]!=""){
 $sa = get_search_sql("ContactsAccount",$telnumber,$contact); 

      $ra = $db->query($sa,true," Error filling in additional detail fields: ");          
        $account= $db->fetchByAssoc($ra, 0, false);  
     
      if ($out_passed_contact_id!=$contact["id"]){
         $output_list[] = Array(
                "id" => "".$contact["id"],
                "CustomerID" =>"".$account["account_id"],
                "ContactName"=>$contact["first_name"]." ".$contact["last_name"],  
                "CompanyName"=>"".$account["name"],         
                "stype"=>"Contacts",  
                "assigned_user_id"=>$contact["assigned_user_id"], 
                "assigned_user_ext"=>get_extension_from_user($contact["assigned_user_id"]),                
               );
     }
     }   
   #  }
    $aai++; 
    }

    
   #   if ($totnr==0 or 1==1){  
 $query = get_search_sql("Leads",$telnumber); 
 
         $result = $db->query($query,true," Error filling in additional detail fields: ");
    $totnr = $db->getRowCount($result);
    $found_leads= $totnr;

       $aai=0;
        while($aai<$totnr)
    {
    $contact= $db->fetchByAssoc($result, $aai, false);
     if ($out_passed_lead_id!=$contact["id"]){
          $output_list[] = Array(
                "id" => "".$contact["id"],
                "CustomerID" =>" ",
                "ContactName"=>$contact["first_name"]." ".$contact["last_name"],  
                "CompanyName"=>$contact["account_name"],         
                "stype"=>"Leads",  
                "assigned_user_id"=>$contact["assigned_user_id"], 
                "assigned_user_ext"=>get_extension_from_user($contact["assigned_user_id"]),                
               );  
    }        
    
    $aai++; 
    }
        
  #    }
      if ($found_contacts==0 and $found_leads==0){  
          $query = get_search_sql("Accounts",$telnumber); 
 
         $result = $db->query($query,true," Error filling in additional detail fields: ");
    $totnr = $db->getRowCount($result);
    $totnr1= $totnr;
    $found_accounts= $totnr;
        while($aai<=$totnr)
    {
    $contact= $db->fetchByAssoc($result, $aai, false);
     if ($out_passed_contact_id!=$contact["id"]){
          $output_list[] = Array(
                "id" => "".$contact["id"],
                "CustomerID" =>$contact["id"],
                "ContactName"=>" ",  
                "CompanyName"=>"".$contact["name"],         
                "stype"=>"Contacts",  
                "assigned_user_id"=>$contact["assigned_user_id"], 
                "assigned_user_ext"=>get_extension_from_user($contact["assigned_user_id"]),                 
               ); 
    }        
    
    $aai++; 
    }
        
      }
      
//pr4v1
//pr4v1
 }
    $seed_contact = $seed_contact;
return $output_list;
}


function get_search_sql($module,$telnumber,$contact){
    if ($module=="Contacts"){
 $query = "select * from contacts  where (contacts.phone_home like '$telnumber' or contacts.phone_work like '$telnumber' or contacts.phone_other like '$telnumber' or contacts.phone_fax like '$telnumber' or contacts.phone_mobile like '$telnumber' )  having contacts.deleted=0";
        
    }
    if ($module=="Leads"){
  $query = "select * from leads  where leads.converted=0 and (leads.phone_home like '$telnumber' or leads.phone_work like '$telnumber' or leads.phone_other like '$telnumber' or leads.phone_fax like '$telnumber' or leads.phone_mobile like '$telnumber' ) having leads.deleted=0";    
        
    }    
    if ($module=="ContactsAccount"){ 
       $query = "select * from accounts left join accounts_contacts on accounts.id=accounts_contacts.account_id where accounts_contacts.contact_id='".$contact["id"]."' and accounts_contacts.deleted =0 and accounts.deleted =0";
    }
     if ($module=="Accounts"){ 
          $query = "select * from accounts  where (phone_office like '$telnumber' or accounts.phone_fax like '$telnumber' or accounts.phone_alternate like '$telnumber' or accounts.phone_fax like '$telnumber'  ) having accounts.deleted=0";    
    } 
    return $query;  
} 





function debvp($msg){
    return true;
$fp = fopen('__1111called_testa.php', 'a+');
fwrite($fp, "
Mes: ".$msg); 


           
fclose($fp);
 } 

exit(); 
?>