<?php
/*
|--------------------------------------------------------------------------
| Controller
|--------------------------------------------------------------------------
|
*/
require 'vendor/autoload.php';

require_once('vendor/picqer/php-barcode-generator/src/BarcodeBar.php');


require_once('vendor/picqer/php-barcode-generator/src/Barcode.php');

require_once('vendor/picqer/php-barcode-generator/src/Types/TypeInterface.php');

require_once('vendor/picqer/php-barcode-generator/src/Types/TypeCode128.php');

require_once('vendor/picqer/php-barcode-generator/src/BarcodeGenerator.php');

require_once('vendor/picqer/php-barcode-generator/src/BarcodeGeneratorHTML.php');


 //require 'vendor/picqer/php-barcode-generator/src/BarcodeGeneratorHTML.php';
 //include('vendor/picqer/php-barcode-generator/src/BarcodeGeneratorHTML.php');
//include('classes/Class2.php');


_auth();
$ui->assign('_application_menu', 'invoices');
$ui->assign('_st', $_L['Invoices']);
$ui->assign('_title', $_L['Sales'] . '- ' . $config['CompanyName']);
$action = $routes['1'];
$user = User::_info();
$ui->assign('user', $user);
Event::trigger('invoices');

if(has_access($user->roleid,'sales','all_data')){

    $sales_all_data = true;

}
else{

    $sales_all_data = false;

}

switch ($action) {
  case 'checkacticvitytest':
  $text = $_POST['text'];
  //$text = "make appointment on next friday";

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, 'https://api.textrazor.com/');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, "extractors=entities,entailments,&text=".$text);

  $headers = array();
  $headers[] = 'X-Textrazor-Key: 4a4de832e60a6762e1ca063cbaa3fd70c26dfd2bbeab69f34d1bd36c';
  $headers[] = 'Content-Type: application/x-www-form-urlencoded';
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $result = curl_exec($ch);
  if (curl_errno($ch)) {
  echo 'Error:' . curl_error($ch);
  }
  else {
  $result = json_decode($result);
    /*echo "<pre>";
    print_r($result->response->entities);

    echo "</pre>";*/
    //if($result->response->entities);
    if(isset($result->response->entities)){
      if(isset($result->response->entities[0]->type[0])){
        if($result->response->entities[0]->type[0]=="Time"){
          if(isset($result->response->entities[0]->entityId)){
            //echo $result->response->entities[0]->entityId;
            $appointment_date = date('Y-m-d',strtotime($result->response->entities[0]->entityId));
            $view_date = date('d-M-Y',strtotime($result->response->entities[0]->entityId));

            foreach($result->response->entailments as $entailment){
              //  if($entailment)

                if(isset($entailment->entailedWords[0])){
                  //print_r($entailment->entailedWords); echo "<br/>";
                  $word = strtolower($entailment->entailedWords[0]);

                    if($word=="meeting" || $word=="meet" || $word=="appointment" || $word=="appoint")
                    {
                      echo "Do you want to  create an appointment on  ".$view_date." ?";
                      break;
                    }
                }

              }
          }
        }
      }
    }


  }
  curl_close($ch);

    //echo $text;
  break;

case 'getlatlon':

    $ch = curl_init();
    $urlPart="";
    if(isset($_POST['zip']))
      {
      $place  = urlencode(_post('zip'));
   //   $urlPart = $place.'&countrycode=sg';
      $urlPart = $place;

      }
    else if(isset($_POST['address']))
      {
    $place  = urlencode(_post('address'));
    $urlPart = $place.'&countrycode=sg';
    }
    
  //  $place = "thiruvalla";

    curl_setopt($ch, CURLOPT_URL, 'https://api.opencagedata.com/geocode/v1/json?q='.$urlPart.'&key='.OPENCAGEDATA.'&language=en&pretty=1');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        //echo 'Error:' . curl_error($ch);
        //your monthly quota is exhausted
        $arr = array('latitude' => $latitude, 'longitude' => $longitude, 'error' => 1, 'msg'=>'Curl Error');

    }
    else{
      //print_r($result);

        $result = json_decode($result);
      if($result->rate->remaining>0){


        if(!empty($result->results)) {

            $latitude = $result->results[0]->geometry->lat;
            $longitude = $result->results[0]->geometry->lng;
         //   echo "Latitude -".$latitude;
          //  echo "<br/>";
           // echo "Longitude -".$longitude;
           $arr = array('latitude' => $latitude, 'longitude' => $longitude, 'error' => 0, 'msg'=>'Fetch Latitude and Longitude Successfully');

            echo json_encode($arr);

        }
       
        else{
           // echo "invalid address";
           $arr = array('latitude' => '', 'longitude' => '', 'error' => 1, 'msg'=>'Invalid Address');

           echo json_encode($arr);

        }
      }
      else{
        //echo  "Your monthly quata is exuasted";
        $arr = array('latitude' => $latitude, 'longitude' => $longitude, 'error' => 1, 'msg'=>'Your monthly quota is exhausted');

        echo json_encode($arr);

      }

        
  //   print($longitude);
    }
    curl_close($ch);
    


      

break;


case 'google_geocode':
  $api_key = GOOGLE_API; //"AIzaSyADRi9mnf9XtGagFtBCzfg2elcDMdMEnQw";
  $country_code = 'SG';
  if(isset($_POST['zip']))
  {
    
  $place  = urlencode(_post('zip'));
  $urlPart = 'components=postal_code:'.$place.'|country:'.$country_code;

  }
 else if(isset($_POST['address']))
  {
    $place  = urlencode(_post('address'));

    $urlPart = 'address='.$place.'&components=country:'.$country_code;
    
  } 
  else 
  {
    $arr = array('latitude' => '', 'longitude' => '', 'error' => 1, 'msg'=>'Invalid Address or Postal Code');

    echo json_encode($arr);

  }
  $q = "https://maps.googleapis.com/maps/api/geocode/json?key=".$api_key.'&'.$urlPart;

  
   $json = file_get_contents($q);
   $details = json_decode($json, TRUE);
   if($details['status']=="ZERO_RESULTS")
  {
   
    $arr = array('latitude' => '', 'longitude' => '', 'error' => 1, 'msg'=>'Invalid Address or Postal Code');
    echo json_encode($arr);

    //echo "Invalid  Postal Code. Please update zip code of this customer";
  }
  else {
    $latitude =  $details['results'][0]['geometry']['location']['lat'];
   $longitude = $details['results'][0]['geometry']['location']['lng'];
   $arr = array('latitude' => $latitude, 'longitude' => $longitude, 'error' => 0, 'msg'=>'Fetch Latitude and Longitude Successfully');

  echo json_encode($arr);
  }

  /*$arr = array('latitude' => '', 'longitude' => '', 'error' => 1, 'msg'=>'Invalid Address or Postal Code');

  echo json_encode($arr);
  
  // $arr = array('latitude' => '', 'longitude' => '', 'error' => 1, 'msg'=>'lat- '.$details['results'][0]['geometry']['location']['lng']);
/*
  // echo json_encode($arr);
 
  else
  {

  // $latitude =  $details['results'][0]['geometry']['location']['lat'];
  // $longitude = $details['results'][0]['geometry']['location']['lng'];
  }


  $latitude =  $details['results'][0]['geometry']['location']['lat'];
  $longitude = $details['results'][0]['geometry']['location']['lng'];
//   echo "Latitude -".$latitude;
//  echo "<br/>";
 // echo "Longitude -".$longitude;
 
 $arr = array('latitude' => $latitude, 'longitude' => $longitude, 'error' => 0, 'msg'=>'Fetch Latitude and Longitude Successfully');

  echo json_encode($arr);
  */


break;

case 'crm-sync-customer':
  //$customerid = $routes['2'];
  $email = base64_decode($_POST['email']);

  if($email != "")
  {
   
 

     $password = "1234566789";
      $customer =   ORM::for_table('crm_accounts')->where('email',$email)->find_one();
      
      if($customer)
      {
        
      
        
        
        $curl = curl_init();
            
        curl_setopt_array($curl, array(
        CURLOPT_URL => BACKOFFICEAPI_URL."users/create",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => array('username' => $customer->email,'password' => $password,'baseurl' => APP_URL, 'clients_client_id' => $config['client_id'], 'role' => 'Client'),
        ));
      
        $response = curl_exec($curl);

        
        curl_close($curl);
        $json = json_decode($response, true);
       // print_r($json);
        $cust =   ORM::for_table('crm_accounts')->where('id',$customer->id)->find_one();

       $password = Password::_crypt($password);

        $cust->password = $password;
        $cust->save();
        echo "1";
      
          //$json = json_decode($response, true);
          //print_r($json);die();
      }
      else
      {
        
 
              
            $account = '';
            if(isset($_POST['first_name']))
            {
                $account = $_POST['first_name'];
            }

            if(isset($_POST['second_name']))
            {
                $account .= ' '.$_POST['second_name'];
            }



            $contact = new Contact;
            $contact->account = $account;
            
          
            if(isset($email))
            {
                // check if exist
                $check = Contact::where('email',$email)
                    ->first();
                
                if($check)
                {
                  echo "Email Already exist in crm";
                    //continue;
                }
                
                $contact->email = $email;
                

            }
            else{
              echo "No email";
            }
            
           
            

            if(isset($_POST['postcode']))
            {
                $contact->zip = $_POST['postcode'];

                
            }
            
            if(isset($_POST['address_1']))
            {
                $contact->address = $_POST['address_1'];

            }
            // if(isset($_POST['address_2']))
            // {
            //     $billing_address_2 = $_POST['address_2'];
            // }
            if(isset($_POST['city']))
            {
                $contact->city = $_POST['city'];

            }
            if(isset($_POST['country']))
            {
              
                $contact->country = $_POST['country'];

            }

            if(isset($_POST['state']))
            {

                $contact->state = $_POST['state'];

            }

            if(isset($_POST['phone']))
            {
                $contact->phone = $_POST['phone'];
            }

          
            $api_key = GOOGLE_API;
            $country_code = 'SG';
            
            if($contact->zip!="")
            {
                
            $place  = urlencode($contact->zip);
            $urlPart = 'components=postal_code:'.$place.'|country:'.$country_code;

            }
            else if($billing_address_1!="")
            {
                $add = $billing_address_1.$billing_city;
                $place  = urlencode($add);

                $urlPart = 'address='.$place.'&components=country:'.$country_code;
                
            } 
            else 
            {
                $arr = array('latitude' => '', 'longitude' => '', 'error' => 1, 'msg'=>'Invalid Address or Postal Code');

               echo "Invalid Address or Postal Code";
              

            }
           
            $q = "https://maps.googleapis.com/maps/api/geocode/json?key=".$api_key.'&'.$urlPart;

           
            $json = file_get_contents($q);
            $details = json_decode($json, TRUE);
            if($details['status']=="ZERO_RESULTS")
            {
              echo "Invalid  Postal Code. Please update zip code of this customer";
            }
            else
            {

            $latitude =  $details['results'][0]['geometry']['location']['lat'];
            $longitude = $details['results'][0]['geometry']['location']['lng'];
              

            $contact->lat = $latitude;
            $contact->lon = $longitude;
          
            }
            // $arr = array('latitude' => '', 'longitude' => '', 'error' => 1, 'msg'=>'lat- '.$details['results'][0]['geometry']['location']['lng']);
            
            // echo json_encode($arr);




          $password = Password::_crypt($password);

          $contact->password = $password;
          

            $contact->save();


            $curl = curl_init();
        
            curl_setopt_array($curl, array(
            CURLOPT_URL => BACKOFFICEAPI_URL."users/create",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => array('username' => $contact->email,'password' => $password,'baseurl' => APP_URL, 'clients_client_id' => $config['client_id'], 'role' => 'Client'),
            ));

            $response = curl_exec($curl);


            curl_close($curl);
            $json = json_decode($response, true);
            // print_r($json);

            echo "1";


            





    
      }
  }
  else
  {
    print_r("email not found"); die();

  }
  

break;

case 'getpackage_detail':
 $cid = $_POST['cid'];
 //$cid = 3;
 $customer_subscriptions = ORM::for_table('crmcustomer_subscriptions')->where('expired', 0)->where("customer_id",$cid)->find_array();

 //$current_subscription = ORM::for_table('crm_accounts')->select('current_subscription')->where("id",$cid)->find_array();
 $subscription_history = ORM::for_table('crmsubscriptions_history')->where('customer_id', $cid)->find_array();
   
 $totalhours = 0.0;
 $totalhoursused = 0.0;
 $i=0;
 if(!empty($customer_subscriptions))
 {
 foreach($customer_subscriptions as $csub)
 {

  $package_id = $csub['package_id'];
  $hours =  $csub['hours'];
  $csubid = $csub['id'];
  $package_name = $csub['package_name'];
  $subscription_history = ORM::for_table('crmsubscriptions_history')->where('customer_subscribe_id', $csubid)->find_array();
  //print_r($subscription_history); die  
  
  if(empty($subscription_history))
    {
    // $totalhoursused += 0;
    $his[$i]['used'] = 0.0;
      $his[$i]['csubid'] = $csubid;
      $his[$i]['packagename'] = $package_name;
      $his[$i]['remaing'] = $hours;
      $his[$i]['totalhours'] = $hours;

    }
    else 
    { 
      $used = 0.0;
     
      foreach($subscription_history as $sh)
      {
        $used += $sh['total_hours'];
      }
      $remaing = $hours - $used;
      if($remaing <= 0 )
      {
        $cust_subscri = ORM::for_table('crmcustomer_subscriptions')->find_one($csubid);
        $cust_subscri->expired = 1;
        $cust_subscri->save();
        continue;
      }
      $his[$i]['used'] = $used;
      $his[$i]['csubid'] = $csubid;
      $his[$i]['packagename'] = $package_name;
      $his[$i]['remaing'] = $hours - $used ;
      $his[$i]['totalhours'] = $hours;

      
    }
    $i++;
    

 }
}
else{
  $his[$i]['used'] = -1;
      $his[$i]['csubid'] = -1;
      $his[$i]['packagename'] = -1;
      $his[$i]['remaing'] = -1;
}
 
//  echo "<pre>";
//     print_r($his);
//     echo "</pre>";

   echo json_encode($his);


break;

case 'test-barcode':
  $generator = new Picqer\Barcode\BarcodeGeneratorHTML();
  echo $generator->getBarcode('081231723897', $generator::TYPE_CODE_128);
  //echo "<br/>";
  echo "ererere";
  
break;

case 'test':

  $crmclientsub = ORM::for_table('crmcustomer_subscriptions')->create();
  $crmclientsub->customer_id = 12;
   $crmclientsub->package_id = 1;
   $crmclientsub->package_name = "package_name";
   $crmclientsub->hours = 100.2;
   $crmclientsub->remaining = 12.2;
  $crmclientsub->invoice_id = 2;
   $crmclientsub->invoice_item_id = 12;
                      

   $crmclientsub->save();
break;

default:
    echo "Action Not defined";
break;

}
