<?php
/*
|--------------------------------------------------------------------------
| Controller
|--------------------------------------------------------------------------
|
*/
require 'vendor/autoload.php';
use GuzzleHttp\Client;



_auth();
$ui->assign('_application_menu', 'crmdelivery');
$ui->assign('_st', 'Deliery Settings');
$ui->assign('_title', 'Deliery Settings' . '- ' . $config['CompanyName']);

$action = $routes['1'];
$user = User::_info();
$ui->assign('user', $user);
$ui->assign('_user', $user);

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

    $sales_all_data = true;

}
else{

    $sales_all_data = false;

}

switch ($action) {

    case 'driver-list':

        $ui->assign('content_inner',inner_contents($config['c_cache']));
        if($user['user_type'] != 'Admin'){
            r2(U."dashboard",'e',$_L['You do not have permission']);
        }

        $d = ORM::for_table('sys_users')->where_like('user_type','%Driver%')->find_many(); //where('status', 'Active')

        $relations = Relation::staffDepartmentsAll();



        $departments = TicketDepartment::all()->keyBy('id')->all();


        $ui->assign('d',$d);
        view('crmdriver-list',[
            'departments' => $departments,
            'relations' => $relations
        ]);

  
       break;
  
    case 'driver-add':

        $ui->assign('xfooter',Asset::js('settings/staff'));
        $ui->assign('content_inner',inner_contents($config['c_cache']));
//        if($user['user_type'] != 'Admin'){
//            r2(U."dashboard",'e',$_L['You do not have permission']);
//        }


        $departments = TicketDepartment::orderBy('sorder','asc')->get();

        $roles = M::factory('Models_Role')->find_array();
        $ui->assign('roles',$roles);


        view('crmdriver-add',[
            'departments' => $departments,
            'employee' => false
        ]);

        break;




  
    case 'driver-users-edit':
  
  
  
      //  $ui->assign('content_inner',inner_contents($config['c_cache']));
  
        $ui->assign('_application_menu', 'driver');
  
        $ui->assign('languages',IBilling_I18n::get_languages());
  
  
  
        $id  = $routes['2'];
        $d = ORM::for_table('sys_users')->find_one($id);
        if($d){
  
            if($user->id != $d->id){
  
                if(!has_access($user->roleid,'settings','edit')){
  
                    permissionDenied();
  
                }
  
            }
  
            $ui->assign('xheader', Asset::css(array('imgcrop/assets/css/croppic')));
  
  
            $ui->assign('xfooter', Asset::js(array('imgcrop/croppic')));
  
            $ui->assign('d',$d);
  
            // find user language
  
            if($d->language == ''){
                $selected_language = $config['language'];
            }
            else{
                $selected_language = $d->language;
            }
  
            $roles = M::factory('Models_Role')->find_array();
            $ui->assign('roles',$roles);
  
            view('driver-users-edit',[
                'selected_language' => $selected_language
            ]);
  
        }
        else{
            r2(U . 'driver/driver-users', 'e', $_L['Account_Not_Found']);
        }
  
        break;
  
    case 'driver-users-delete':
  
  
        $id  = $routes['2'];
        //prevent self delete
        if(($user->id) == $id){
            r2(U . 'driver/driver-users', 'e', 'Sorry You can\'t delete yourself');
        }
        $d = ORM::for_table('sys_users')->find_one($id);
        if($d){
  
            if($user->id != $d->id){
  
        /*        if(!has_access($user->roleid,'settings','delete')){
  
                    permissionDenied();
  
                }*/
  
            }
  
            $d->delete();
            r2(U . 'driver/driver-users', 's', 'User deleted Successfully');
        }
        else{
            r2(U . 'driver/driver-users', 'e', $_L['Account_Not_Found']);
        }
  
        break;
  
    case 'driver-post':
     // print_r(BACKOFFICE_URL); die();

  
        $username = _post('username');
        $fullname = _post('fullname');
        $password =  _post('password');
        $cpassword = _post('cpassword');
        $user_type = _post('user_type');
        $vehicle_type = _post('vehicle_type');
        $vehicle_number = _post('vehicle_number');
       
  
        /*if(!has_access($user->roleid,'settings','create')){
  
            permissionDenied();
  
        }*/
  
  
        $r = M::factory('Models_Role')->find_one($user_type);
  
        if($r){
            $role = $r->rname;
            $roleid = $user_type;
            $user_type = $r->rname;
        }
        else{
            $role = '';
            $roleid = 0;
            $user_type = 'Admin';
        }
  
  
        $msg = '';
        if(filter_var($username, FILTER_VALIDATE_EMAIL) == false){
            $msg .= $_L['notice_email_as_username']. '<br>';
        }
  
        if($password != $cpassword){
            $msg .= 'Passwords does not match'. '<br>';
        }
  //check with same name account is exist
        $d = ORM::for_table('sys_users')->where('username',$username)->find_one();
        if($d){
            $msg .= $_L['account_already_exist']. '<br>';
        }
  
  
        // create Roles
  
  
  
  
        if($msg == ''){
  
            $password = Password::_crypt($password);
            // Add Account
            $d = ORM::for_table('sys_users')->create();
            $d->username = $username;
            $d->password = $password;
            $d->fullname = $fullname;
            $d->user_type = $user_type;
  
            //others
            $d->phonenumber = _post('phone') ;
            $d->last_login = date('Y-m-d H:i:s');
            $d->email = '';
            $d->creationdate = date('Y-m-d H:i:s');
            $d->pin = '';
            $d->img = '';
            $d->otp = 'No';
            $d->pin_enabled = 'No';
            $d->api = 'No';
            $d->pwresetkey = '';
            $d->keyexpire = '';
            $d->status = 'Active';
            $d->role = $role;
            $d->roleid = $roleid;
            $d->vehicle_type = $vehicle_type;
            $d->vehicle_number = $vehicle_number;
            $d->work_mobile = _post('work_mobile');
  
            if (CRM_TYPE == "SAAS")
            {

                $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' => $username,'password' => _post('password'),'baseurl' => APP_URL, 'clients_client_id' => $config['client_id'], 'role' => $role),
            ));
            
            $response = curl_exec($curl);
            
            curl_close($curl);
             } 
         
          $json = json_decode($response, true);
       // print_r($json);die();
          if($json['status']=="success" && $json['error']==false){
            $d->save();
            r2(U . 'crmdelivery/driver-list', 's', $_L['account_created_successfully']);
          }
          else {
            r2(U . 'crmdelivery/driver-add', 'e', $json['message']);
          }
            
          
           
  
            
        }
        else{
            r2(U . 'crmdelivery/driver-add', 'e', $msg);
        }
  
        break;
  
  
    case 'driver-users-edit-post':
  
  
        $username = _post('username');
        $fullname = _post('fullname');
        $phonenumber = _post('phonenumber');
        $img = _post('picture');
  
        $img = str_replace(APP_URL.'/','',$img);
        $password = "123456789"; //_post('password');
        $cpassword = "123456789"; //_post('cpassword');
  
        $language = _post('user_language');
  
        $_SESSION['language'] = $language;
  
  
        $msg = '';
  
        if(filter_var($username, FILTER_VALIDATE_EMAIL) == false){
            $msg .= 'Please use a valid Email address as Username'. '<br>';
        }
  
        if($password != ''){
  
            if($password != $cpassword){
                $msg .= 'Passwords does not match'. '<br>';
            }
        }
        //find this user
        $id = _post('id');
        $d = ORM::for_table('sys_users')->find_one($id);
        if($d){
  
            if($user->id != $d->id){
  
                /*if(!has_access($user->roleid,'settings','edit')){
  
                    permissionDenied();
  
                }*/
  
            }
  
        }
        else{
            $msg .= 'Username Not Found'. '<br>';
        }
  //check with same name account is exist
        if($d['username'] != $username){
            $c = ORM::for_table('sys_users')->where('username',$username)->find_one();
            if($c){
                $msg .= $_L['account_already_exist']. '<br>';
            }
        }
  
  
  
        if(APP_STAGE == 'Demo'){
            $msg .= 'Editing User is disabled in the Demo Mode!'. '<br>';
        }
  
  
  
        $user_type = _post('user_type');
  
        $r = M::factory('Models_Role')->find_one($user_type);
  
        if($r){
            $role = $r->rname;
            $roleid = $user_type;
            $user_type = $r->rname;
        }
        else{
            $role = '';
            $roleid = 0;
            $user_type = 'Admin';
        }
  
  
        if($msg == ''){
  
  
  
  
            $d->username = $username;
  
            $d->language = $language;
            if($password != ''){
                $password = Password::_crypt($password);
                $d->password = $password;
            }
  
            $d->fullname = $fullname;
  
            $d->fullname = $fullname;
  
            $d->phonenumber = $phonenumber;
  
            if(($user->id) != $id){
  
                $d->user_type = $user_type;
                $d->role = $role;
                $d->roleid = $roleid;
            }
  
            $d->img = $img;
            $d->isupdated = 1;
  
  
  
            $d->save();
            r2(U . 'driver/driver-users-edit/'.$id, 's', 'User Updated Successfully');
        }
        else{
            r2(U . 'driver/driver-users-edit/'.$id, 'e', $msg);
        }
  
        break;
  
  
            case 'settings':
  
                $ui->assign('content_inner',inner_contents($config['c_cache']));
  
  
  
            //
  
            $delivery_method = ORM::for_table('driver_settings')->where('id',2)->find_one();
  
  
  
                view('driver_settings',[
                  'delivery_method' => $delivery_method
                ]);
  
                break;
  
  case 'driver-assign';
  $css_arr = array(
      's2/css/select2.min',
      'modal',
      'dp/dist/datepicker.min',
      'redactor/redactor'
  );
  $js_arr = array(
      'redactor/redactor.min',
      's2/js/select2.min',
      's2/js/i18n/' . lan() ,
      'dp/dist/datepicker.min',
      'dp/i18n/' . $config['language'],
      'numeric',
      'filter.min',
      'modal'
  );
  
  //$pos = route(4);
  
  //Event::trigger('add_invoice_rendering_form');
  $ui->assign('xheader', Asset::css($css_arr));
  $ui->assign('xfooter', Asset::js($js_arr));
  
  if(isset($_POST['current_date'])) {
  $current_date = _post('current_date');
  }
  else if(isset($routes['2'])){
    $cd = $routes['2'];
    $current_date = $cd;
  }
  
  
  //print_r($current_date);
  
  else if(!isset($_POST['current_date'])){
    $current_date = Date('Y-m-d');
  
  }
  
  
  
  
    $ui->assign('current_date', $current_date);
  
  
    $delivery_notes = ORM::for_table('sys_invoices')->where_not_equal('c1', '')->where_like('c2', $current_date.'%')->where_in('delivery_status', array('Unassigned', 'Assigned'))->order_by_desc('id')->find_array();
    //$c = ORM::for_table('sys_users')->select('id')->select('fullname')->select('username')->select('email')->order_by_desc('id')->where_like('user_type','%Driver%')->where('status', 'Active');
    $c = ORM::for_table('sys_users')->select('sys_users.id')->select('fullname')->select('username')->select('email')->select('crmdriver_availablity.date')->select("crmdriver_availablity.status")->join('crmdriver_availablity', "crmdriver_availablity.driver_id = sys_users.id and crmdriver_availablity.date='$current_date' and crmdriver_availablity.status = 1 " )->where_like('user_type','%Driver%')->where('status', 'Active');
  
  
    $c = $c->find_array();
    if(!empty($c)){
      $driver_available = count($c);
    }
    else {
        $driver_available = 0;
    }
    if(!empty($delivery_notes)){
      $total_delivery = count($delivery_notes);
    }
    else {
        $total_delivery = 0;
    }
    $ui->assign('driver_available', $driver_available);
    $ui->assign('total_delivery', $total_delivery);
  
    $ui->assign('c', $c);
    //$delivery_notes = ORM::for_table('sys_invoices')->where_not_equal('c1' '1')->order_by_desc('id')->find_array();//Invoice //DeliveryNote::all();
      $ui->assign('d', $delivery_notes);
  
    view('crmsmartdriverassign',[
  
    ]);
  break;
  
  case 'driver-availablity':
  $css_arr = array(
      's2/css/select2.min',
      'modal',
      'dp/dist/datepicker.min',
      'redactor/redactor'
  );
  $js_arr = array(
      'redactor/redactor.min',
      's2/js/select2.min',
      's2/js/i18n/' . lan() ,
      'dp/dist/datepicker.min',
      'dp/i18n/' . $config['language'],
      'numeric',
      'filter.min',
      'modal'
  );
  
  
  
  
  $ui->assign('xheader', Asset::css($css_arr));
  $ui->assign('xfooter', Asset::js($js_arr));
  $current_date = _post('current_date');
  
  if($current_date == ""){
    $current_date = Date('Y-m-d');
  
  }
  
  else if(isset($_SESSION['cdate']) || _post('current_date')==null) {
  //  $current_date = $_SESSION['cdate'];
  }
  
  
  
    $ui->assign('current_date', $current_date);
  
  
    $delivery_notes = ORM::for_table('sys_invoices')->where_not_equal('c1', '')->where_like('c2', $current_date.'%')->where_in('delivery_status', array('Unassigned', 'Assigned'))->order_by_desc('id')->find_array();
    $c = ORM::for_table('sys_users')->select('sys_users.id')->select('fullname')->select('username')->select('email')->select('crmdriver_availablity.date')->select("crmdriver_availablity.status")->left_outer_join('crmdriver_availablity', "crmdriver_availablity.driver_id = sys_users.id and crmdriver_availablity.date='$current_date'")->where_like('user_type','%Driver%')->where('status', 'Active');
  
    $c = $c->find_array();
   //print_r($c); die();
  
    $ui->assign('c', $c);
    //$delivery_notes = ORM::for_table('sys_invoices')->where_not_equal('c1' '1')->order_by_desc('id')->find_array();//Invoice //DeliveryNote::all();
    $ui->assign('d', $delivery_notes);
  
    view('crmdrivermanageavailablity',[
  
    ]);
  break;
  
  case 'driver-availablity-add':
    $current_date = $_POST["current_date"];
    $userid = $_POST['userid'];
  
  
    $_SESSION['cdate'] = $current_date;
    //$submit = $_POST['s'];
    //$c = ORM::for_table('sys_users')->select('sys_users.id')->select('fullname')->select('username')->select('email')->where_like('user_type','%Driver%')->where('status', 'Active');
  
    if(isset($_POST['status'])) {
        $status = $_POST['status'];
  
  
    }
    else{
      $status = [];
    }
    $x = ORM::for_table('crmdriver_availablity')->where('date', $current_date)->delete_many();
  
    foreach ($userid as $key => $value) {
        if(in_array($value,$status)){
          $st = 1;
        }
        else{
          $st = 0;
        }
  
      $d = ORM::for_table('crmdriver_availablity')->create();
      $d->driver_id = $value;
      $d->date = $current_date;
      $d->status = $st; 
      $d->save();
  
    }
    r2(U . 'crmdelivery/driver-availablity/'.$current_date, 's', 'Updated successfully');
  break;
  
  
  case 'driver-smart-assign':
    $url = 'https://api.routific.com/v1/';
    $client = new Client([
      'base_uri' => $url,
    ]);
    
    //$deliveryID = $_POST['deliveryid'];
    //print_r($deliveryID); die();
    $current_date = $_POST['current_date'];
    $delivery_notes = ORM::for_table('sys_invoices')->where_not_equal('c1', '')->where_like('c2', $current_date.'%')->where_in('delivery_status', array('Unassigned', 'Assigned'))->order_by_desc('id')->find_array();
      $visits = array();
    foreach ($delivery_notes as $key => $value) {
      //print_r($value); die();
        $order = array("location" => array(
                  "name" =>$value["shipping_street"],
                  "lat" => $value["c3"],
                  "lng" => $value["c4"]
              ));
              $order['start']='8:00';
              $order['end'] = '18:00';
              $order['duration'] = '10';
             // $visits[$value["invoicenum"].$value['cn'].'('.$value["id"].')'] = $order; //$value[id] 
              $visits[$value['id']] = $order; 
    }
    
    
    //Step 3: Prepare vehicles
    $c = ORM::for_table('sys_users')->select('sys_users.id')->select('fullname')->select('vehicle_number')->select('username')->select('email')->select('crmdriver_availablity.date')->select("crmdriver_availablity.status")->join('crmdriver_availablity', "crmdriver_availablity.driver_id = sys_users.id and crmdriver_availablity.date='$current_date' and crmdriver_availablity.status = 1 " )->where_like('user_type','%Driver%')->where('status', 'Active');
    
    
    $c = $c->find_array();
    
    $latitude = ORM::for_table('sys_appconfig')->where('setting','latitude')->find_one()->value;
    $longitude = ORM::for_table('sys_appconfig')->where('setting','longitude')->find_one()->value;
    //print_r($longitude); die();
    
    $vehicle1 = array();
    foreach ($c as $key => $value) {
       
        $start_location = new stdClass;
        $start_location->id = $value ['id'];
        $start_location->name = "Compant Office";
        $start_location->lat = $latitude;
        $start_location->lng = $longitude;
        
        $vehicle1['start_location'] = $start_location;
       
        $end_location = new stdClass;
        $end_location->id = $value ['id'];
        $end_location->name = "Compant Office";
        $end_location->lat = $latitude;
        $end_location->lng = $longitude;
        
        $vehicle1['end_location'] = $end_location;

        $vehicle1['shift_start']= '8:00';
        $vehicle1['shift_end']= '18:00';
       

       /* $vehicle1['start_location']['id']  = $value['id'];
        $vehicle1['start_location']['name'] = "Compant Office";
        $vehicle1['start_location']['lat'] = $latitude;
        $vehicle1['start_location']['lng']  = $longitude;
      
        $vehicle1['end_location']['id']  = $value['id'];
        $vehicle1['end_location']['name'] = "Compant Office";
        $vehicle1['end_location']['lat'] = $latitude;
        $vehicle1['end_location']['lng']  = $longitude;*/
  
    //$vechicle1['shift_start']= '8:00';
    //$vechicle1['shift_end']= '18:00';
    //print_r($vechicle); die();


      $vehicles["vehicle_".$value['vehicle_number']] = $vehicle1;
    }
    
    //Step 4: Prepare data payload
    $payload = array(
      "visits" => $visits,
      "fleet" => $vehicles
    );
    
//  echo '<pre>';
//         print_r($payload); 
//         echo '</pre>';
//         die();

    //Step 5: Send request
    //$token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1Y2U1MTdiYTg1ODVmMTFjOGFkZTk3ZjUiLCJpYXQiOjE1NTg1MTc2OTB9.9wxvuZypoSuRNAZ-mIbtDC0umWoKn4t1EmQLuDMmR0w';
    $token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZWJkMjMyZGFjNGMwZjAwMTdiNDY0ZjYiLCJpYXQiOjE1ODk0NTM2MTR9.e25_-9_UoSe7WA9K4GBqWSwq__g3Z9UgUdgK0wZi6s4';    
    try{
       

    $response = $client->post('vrp', [
      'json' => $payload,
      'headers' => [
        "Content-type" => "application/json",
        "Authorization" => "bearer " . $token
      ]
    ]);
    

    $result =  json_decode($response->getBody())->solution;
    // echo '<pre>';
    //     print_r($result); 
    //     echo '</pre>';
    //     die();
    foreach($result as $vno => $r){
     
      $i=0; $order = 1;
      foreach ($r as $key => $value) {
        if($i==0){
          $i++;
          $driver_id = $value->location_id;
          continue;
        }
        //print_r($r); echo "<br/>";
        $do = $value->location_id;

    $delivery_id = ORM::for_table('sys_invoices')->find_one($do);

    $delivery_id->c5 = $driver_id;
    $delivery_id->delivery_status = "Assigned";
    $delivery_id->sort_order = $order; 
    $delivery_id->save();
    $order++;


      }
    }
    r2(U."crmdelivery/driver-assign/".$current_date,'s',"Smart Assign System assigned drivers successfully");
    
    }
    catch (Exception $e) {
        //print_r($e->getBody()); die();
       // print_r($e->getResponse()->getBody()->solution); die();
      $error = json_decode($e->getResponse()->getBody()->getContents());
      //print_r($error->error);
      $time = strtotime($current_date);
      //print_r($time); die();
      r2(U."crmdelivery/driver-assign/".$current_date,'e',$error->error);
    }
    
    
    /*
    
    $url = 'https://api.routific.com/v1/';
    $client = new Client([
      'base_uri' => $url,
    ]);

    $current_date = $_POST['current_date'];
    $delivery_notes = ORM::for_table('sys_invoices')->where_not_equal('c1', '')->where_like('c2', $current_date.'%')->where_in('delivery_status', array('Unassigned', 'Assigned'))->order_by_desc('id')->find_array();
    $visits = array();
    foreach ($delivery_notes as $key => $value) {
        $order = array("location" => array(
                  "name" =>$value["id"],
                  "lat" => $value["c3"],
                  "lng" => $value["c4"]
              ));
              //$order['start']='8:00';
              //$order['end'] = '18:00';
              //$order['duration'] = '10';
              //$visits[$value["invoicenum"].$value['cn'].'('.$value["id"].')'] = $order; //$value[id] 
              $visits[$value['id']] = $order; 
              
              
    }

    $c = ORM::for_table('sys_users')->select('sys_users.id')->select('fullname')->select('vehicle_number')->select('username')->select('email')->select('crmdriver_availablity.date')->select("crmdriver_availablity.status")->join('crmdriver_availablity', "crmdriver_availablity.driver_id = sys_users.id and crmdriver_availablity.date='$current_date' and crmdriver_availablity.status = 1 " )->where_like('user_type','%Driver%')->where('status', 'Active');
  
  
    $c = $c->find_array();
    
    $latitude = ORM::for_table('sys_appconfig')->where('setting','latitude')->find_one()->value;
    $longitude = ORM::for_table('sys_appconfig')->where('setting','longitude')->find_one()->value;
    //print_r($longitude); die();
    
    $vechicle = array();
    foreach ($c as $key => $value) {
    
      $vehicle1 = array(
        "start_location" => array(
          "id" => $value['id'], //driver id;
          "name" => "Company Office",
          "lat" => $latitude,
          "lng" => $longitude
      ));
      $vehicles["vehicle_".$value['vehicle_number']] = $vehicle1;
  }
    // echo '<pre>';
    // print_r($vehicles); 
    // echo '</pre>';
    // die();
    


    $payload = array(
        "visits" => $visits,
        "fleet" => $vehicles
      );
    //   echo "<pre>";
    //   print_r($payload);
    //   echo "</pre>";
      
    //   die()
    //   Step 5: Send request
      $token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZWJkMjMyZGFjNGMwZjAwMTdiNDY0ZjYiLCJpYXQiOjE1ODk0NTM2MTR9.e25_-9_UoSe7WA9K4GBqWSwq__g3Z9UgUdgK0wZi6s4';    
      try{
      $response = $client->post('vrp', [
        'json' => $payload,
        'headers' => [
          "Content-type" => "application/json",
          "Authorization" => "bearer " . $token
        ]
      ]);
      $result =  json_decode($response->getBody())->solution;
      //print_r($result); echo "<br/><br/>"; die();
      foreach($result as $vno => $r){
        //print_r($r); echo "<br/><br/>";
        $i=0; $order = 1;
        foreach ($r as $key => $value) {
          if($i==0){
            $i++;
            $driver_id = $value->location_id;
            continue;
          }
          //print_r($r); echo "<br/>";
          $do = $value->location_id;
         
      //echo "delivery id - ".$driver_id ."  delivery order - ". $do. "<br/>";
      $delivery_id = ORM::for_table('sys_invoices')->find_one($do);
      $delivery_id->c5 = $driver_id;
      $delivery_id->code = $order;    //for sorting the order.
      $delivery_id->delivery_status = "Assigned";
      $delivery_id->save();
      $order++;
      
        }
      }
      //print_r($result); die();
      r2(U."crmdelivery/driver-assign/".$current_date,'s',"Smart Assign System assigned drivers successfully");
      
      }
      catch (Exception $e) {
        //$error = json_decode($e->getResponse()->getBody()->getContents());
        //print_r($error->error);
        $time = strtotime($current_date);
        echo "<pre>";
        print_r($e); 
        echo "</pre";
        die();
        r2(U."crmdelivery/driver-assign/".$current_date,'e',$error->error);
      }
      

*/
  
    //   echo '<pre>';
    // print_r($visits); 
    // echo '</pre>';
    // die();
    /*
  $url = 'https://api.routific.com/v1/';
  $client = new Client([
    'base_uri' => $url,
  ]);
  
  //$deliveryID = $_POST['deliveryid'];
  //print_r($deliveryID); die();
  $current_date = $_POST['current_date'];
  $delivery_notes = ORM::for_table('sys_invoices')->where_not_equal('c1', '')->where_like('c2', $current_date.'%')->where_in('delivery_status', array('Unassigned', 'Assigned'))->order_by_desc('id')->find_array();
  
   $visits = array();
    foreach ($delivery_notes as $key => $value) {
        $order = array("location" => array(
                  "name" =>$value["id"],
                  "lat" => $value["c3"],
                  "lng" => $value["c4"]
              ));
              //$order['start']='8:00';
              //$order['end'] = '18:00';
              //$order['duration'] = '10';
              $visits[$value["invoicenum"].$value['cn'].'('.$value["id"].')'] = $order; //$value[id] 

              
              
    }

  
    //   echo '<pre>';
    // print_r($visits); 
    // echo '</pre>';
    // die();
  
  
  //Step 3: Prepare vehicles
  $c = ORM::for_table('sys_users')->select('sys_users.id')->select('fullname')->select('vehicle_number')->select('username')->select('email')->select('crmdriver_availablity.date')->select("crmdriver_availablity.status")->join('crmdriver_availablity', "crmdriver_availablity.driver_id = sys_users.id and crmdriver_availablity.date='$current_date' and crmdriver_availablity.status = 1 " )->where_like('user_type','%Driver%')->where('status', 'Active');
  
  
  $c = $c->find_array();
  
  $latitude = ORM::for_table('sys_appconfig')->where('setting','latitude')->find_one()->value;
  $longitude = ORM::for_table('sys_appconfig')->where('setting','longitude')->find_one()->value;
  //print_r($longitude); die();
  
  $vechicle = array();
  foreach ($c as $key => $value) {
  
    $vehicle1 = array(
      "start_location" => array(
        "id" => $value['id'], //driver id;
        "name" => "Company Office",
        "lat" => $latitude,
        "lng" => $longitude
    ));
    $vehicles["vehicle_".$value['vehicle_number']] = $vehicle1;
}
//   echo '<pre>';
//   print_r($vehicles); 
//   echo '</pre>';
//   die();
  
  //Step 4: Prepare data payload
  $payload = array(
    "visits" => $visits,
    "fleet" => $vehicles
  );
  
  //Step 5: Send request
  $token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZWJkMjMyZGFjNGMwZjAwMTdiNDY0ZjYiLCJpYXQiOjE1ODk0NTM2MTR9.e25_-9_UoSe7WA9K4GBqWSwq__g3Z9UgUdgK0wZi6s4';

  try{
  $response = $client->post('vrp', [
    'json' => $payload,
    'headers' => [
      "Content-type" => "application/json",
      "Authorization" => "bearer " . $token
    ]
  ]);
  $result =  json_decode($response->getBody())->solution;
  //print_r($result); echo "<br/><br/>"; die();
  foreach($result as $vno => $r){
    //print_r($r); echo "<br/><br/>";
    $i=0; $order = 1;
    foreach ($r as $key => $value) {
      if($i==0){
        $i++;
        $driver_id = $value->location_id;
        continue;
      }
      //print_r($r); echo "<br/>";
      $do = $value->location_id;
     
  //echo "delivery id - ".$driver_id ."  delivery order - ". $do. "<br/>";
  $delivery_id = ORM::for_table('sys_invoices')->find_one($do);
  $delivery_id->c5 = $driver_id;
  $delivery_id->code = $order;    //for sorting the order.
  $delivery_id->delivery_status = "Assigned";
  $delivery_id->save();
  $order++;
  
    }
  }
  //print_r($result); die();
  r2(U."crmdelivery/driver-assign/".$current_date,'s',"Smart Assign System assigned drivers successfully");
  
  }
  catch (Exception $e) {
    $error = json_decode($e->getResponse()->getBody()->getContents());
    //print_r($error->error);
    $time = strtotime($current_date);
    // echo "<pre>";
    // print_r($e); 
    // echo "</pre";
    // die();
    r2(U."crmdelivery/driver-assign/".$current_date,'e',$error->error);
  }
  */
  break;
  
  
  case 'driver-manual-assign':
  
  $css_arr = array(
      's2/css/select2.min',
      'modal',
      'dp/dist/datepicker.min',
      'redactor/redactor'
  );
  $js_arr = array(
      'redactor/redactor.min',
      's2/js/select2.min',
      's2/js/i18n/' . lan() ,
      'dp/dist/datepicker.min',
      'dp/i18n/' . $config['language'],
      'numeric',
      'filter.min',
      'modal'
  );
  
  //$pos = route(4);
  
  //Event::trigger('add_invoice_rendering_form');
  $ui->assign('xheader', Asset::css($css_arr));
  $ui->assign('xfooter', Asset::js($js_arr));
  
  if(isset($_POST['current_date'])) {
  $current_date = _post('current_date');
  }
  else if(isset($routes['2'])){
    $cd = $routes['2'];
    $current_date = $cd;
  }
  
  
  //print_r($current_date);
  
  else if(!isset($_POST['current_date'])){
    $current_date = Date('Y-m-d');
  
  }
  
  
  
  
    $ui->assign('current_date', $current_date);
  
  
    $delivery_notes = ORM::for_table('sys_invoices')->where_not_equal('c1', '')->where_like('c2', $current_date.'%')->where_in('delivery_status', array('Unassigned', 'Assigned'))->order_by_desc('id')->find_array();
    //$c = ORM::for_table('sys_users')->select('id')->select('fullname')->select('username')->select('email')->order_by_desc('id')->where_like('user_type','%Driver%')->where('status', 'Active');
    $c = ORM::for_table('sys_users')->select('sys_users.id')->select('fullname')->select('username')->select('email')->select('crmdriver_availablity.date')->select("crmdriver_availablity.status")->join('crmdriver_availablity', "crmdriver_availablity.driver_id = sys_users.id and crmdriver_availablity.date='$current_date' and crmdriver_availablity.status = 1 " )->where_like('user_type','%Driver%')->where('status', 'Active');
  
  
    $c = $c->find_array();
    if(!empty($c)){
      $driver_available = count($c);
    }
    else {
        $driver_available = 0;
    }
    if(!empty($delivery_notes)){
      $total_delivery = count($delivery_notes);
    }
    else {
        $total_delivery = 0;
    }
    $ui->assign('driver_available', $driver_available);
    $ui->assign('total_delivery', $total_delivery);
  
    $ui->assign('c', $c);
    //$delivery_notes = ORM::for_table('sys_invoices')->where_not_equal('c1' '1')->order_by_desc('id')->find_array();//Invoice //DeliveryNote::all();
      $ui->assign('d', $delivery_notes);
  
    view('crmdrivermanualassign',[
  
    ]);

  break;
  

  
  case 'driver-map':
  if (!has_access($user->roleid, 'products_n_services', 'view')) {
      permissionDenied();
  }
  
  
  $d = ORM::for_table('sys_items')->order_by_asc('name')->find_array();
  
  echo '
  <div class="modal-header">
  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  <h3> Current Location</h3>
  </div>
  <div class="modal-body">
    <div id="map"></div>
  
  </div>
  <div class="modal-footer">
  
  <button type="button" data-dismiss="modal" class="btn btn-primary update">'.$_L['Close'].'</button>
  </div>
  <style type="text/css">
  
  </style>
  <script>
  // Initialize and add the map
  function initMap() {
  
  // The location of Uluru
  var uluru = {lat: -25.344, lng: 131.036};
  // The map, centered at Uluru
  
  var map = new google.maps.Map(
    document.getElementById("map"), {zoom: 4, center: uluru});
  // The marker, positioned at Uluru
  var marker = new google.maps.Marker({position: uluru, map: map});
  
  }
  </script>
  <!--Load the API from the specified URL
  * The async attribute allows the browser to render the page while the API loads
  * The key parameter will contain your own API key (which is not needed for this tutorial)
  * The callback parameter executes the initMap() function
  -->
  <script async defer
  src=https://maps.googleapis.com/maps/api/js?key=AIzaSyDK9Wyy81NpY3wkqekhOF4EBFHt5Tc-Yyw&callback=initMap>
  </script>
  ';
  
  break;
    
  
  case 'check_task':
  $invoice = ORM::for_table('sys_invoices')->where_not_equal('c5', "")->where('show_in_web', 1)->find_one();
  if($invoice!=""){
    //echo "yes";
    $status  = 1;
    $driverid = $invoice['c5'];
    if($driverid != ""){
      $c = ORM::for_table('sys_users')->select('sys_users.id')->select('sys_users.fullname')->select('sys_users.phonenumber')->where('id', $driverid)->find_one();
      if($c!=""){
        $status  = 1;
        if(strtolower($invoice['delivery_status']) == "successful"){
          $deliveryStatus = "completed";
        }
        else {
          $deliveryStatus = $invoice['delivery_status'];
        }
        $msg = $c['fullname']." ".$deliveryStatus. " the task";
        $invoice->show_in_web = 0 ;
        $invoice->save();
      }
      else{
        $status = 0;
        $msg = "Invalid Driver";
      }
    }else{
      $status = 0;
      $msg = "Driver Not Assigned";
    }
  
  }
  else{
    //echo "no";
    $status = 0;
    $msg = "No Delivery Chellan";
  
  }
  //print_r($status);
  jsonResponse([
      'status' => $status,
      'msg' => $msg
  ]);
  break;

  case 'deliverychallan-list':
      
      if(isset($_POST['today_date']))
      {
          $today = $_POST['today_date'];
      }
      else 
      {
         $today = date('Y-m-d'); 
      }

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

      $all_data = true;

  }
  else{
      $all_data = false;
  }

  $paginator = array();
  $mode_css = '';
  $mode_js = '';
  $view_type = 'default';
  $view_type = 'filter';
  $mode_css = Asset::css('footable/css/footable.core.min');
  $mode_js = Asset::js(array(
      'numeric',
      'footable/js/footable.all.min',
      'contacts/mode_search'
  ));


  $total_invoice = ORM::for_table('sys_invoices');

  if(!$all_data)
  {
      $total_invoice->where('aid',$user->id);
  }

  $total_invoice = $total_invoice->count();

  $ui->assign('total_invoice', $total_invoice);
  $f = ORM::for_table('sys_invoices');
  if (route(3) != '') {
      $s_f = route(3);
      if ($s_f == 'paid') {
          $f->where('status', 'Paid');
      }
      elseif ($s_f == 'unpaid') {
          $f->where('status', 'Unpaid');
      }
      elseif ($s_f == 'partially_paid') {
          $f->where('status', 'Partially Paid');
      }
      elseif ($s_f == 'cancelled') {
          $f->where('status', 'Cancelled');
      }
      else {
      }
  }

  if(!$all_data)
  {
      $f->where('aid',$user->id);
  }
  $f->where('c1' , 1);
  
  $d = $f->order_by_desc('id')->find_many();
  $paginator['contents'] = '';
  $ui->assign('_st', $_L['Invoices'] . '<div class="btn-group pull-right" style="padding-right: 10px;">
<a class="btn btn-success btn-xs" href="' . U . 'invoices/add/' . '" style="box-shadow: none;"><i class="fa fa-plus"></i></a>
<a class="btn btn-primary btn-xs" href="' . U . 'invoices/add/' . '" style="box-shadow: none;"><i class="fa fa-repeat"></i></a>
<a class="btn btn-success btn-xs" href="' . U . 'invoices/export_csv/' . '" style="box-shadow: none;"><i class="fa fa-download"></i></a>
</div>');
  $ui->assign('xheader', $mode_css);
  $ui->assign('xfooter', $mode_js);
  $ui->assign('view_type', $view_type);
  $ui->assign('d', $d);
  $ui->assign('paginator', $paginator);
  $ui->assign('xjq', '
   $(\'.amount\').autoNumeric(\'init\', {


dGroup: ' . $config['thousand_separator_placement'] . ',
aPad: ' . $config['currency_decimal_digits'] . ',
pSign: \'' . $config['currency_symbol_position'] . '\',
aDec: \'' . $config['dec_point'] . '\',
aSep: \'' . $config['thousands_sep'] . '\',
vMax: \'9999999999999999.00\',
          vMin: \'-9999999999999999.00\'

});
$(".cdelete").click(function (e) {
  e.preventDefault();
  var id = this.id;
  bootbox.confirm("' . $_L['are_you_sure'] . '", function(result) {
     if(result){
         var _url = $("#_url").val();
         window.location.href = _url + "delete/invoice/" + id;
     }
  });
});

$(\'[data-toggle="tooltip"]\').tooltip();

');


  $paid = ORM::for_table('sys_invoices');

  if(!$all_data)
  {
      $paid->where('aid',$user->id);
  }

  $paid =  $paid->where('status', 'Paid')->count();

  $unpaid = ORM::for_table('sys_invoices')->where('status', 'Unpaid');

  if(!$all_data)
  {
      $unpaid->where('aid',$user->id);
  }

  $unpaid = $unpaid->count();

  $partially_paid = ORM::for_table('sys_invoices')->where('status', 'Partially Paid');

      if(!$all_data)
      {
          $partially_paid->where('aid',$user->id);
      }

  $partially_paid = $partially_paid->count();

  $cancelled = ORM::for_table('sys_invoices')->where('status', 'Cancelled');

  if(!$all_data)
  {
      $cancelled->where('aid',$user->id);
  }

  $cancelled = $cancelled->count();

  $arr = array(
      'Paid' => $paid,
      'Unpaid' => $unpaid,
      'Partially Paid' => $partially_paid,
      'Cancelled' => $cancelled
  );

  $p = Ib_Math::array_percentage($arr);
  $invoice_paid_amount = Invoice::where('status', 'Paid');

  if(!$all_data)
  {
      $invoice_paid_amount->where('aid',$user->id);
  }

  $invoice_paid_amount = $invoice_paid_amount->sum('total');

  $invoice_un_paid_amount = Invoice::where('status', 'Unpaid');


  if(!$all_data)
  {
      $invoice_un_paid_amount->where('aid',$user->id);
  }

  $invoice_un_paid_amount = $invoice_un_paid_amount->sum('total');


  $invoice_partially_paid_amount = Invoice::where('status', 'Partially Paid');

  if(!$all_data)
  {
      $invoice_partially_paid_amount->where('aid',$user->id);
  }

  $invoice_partially_paid_amount = $invoice_partially_paid_amount->sum('credit');


  $invoice_cancelled_amount = Invoice::where('status', 'Cancelled');

  if(!$all_data)
  {
      $invoice_cancelled_amount->where('aid',$user->id);
  }

  $invoice_cancelled_amount = $invoice_cancelled_amount->sum('total');

  $contacts = Contact::all()->keyBy('id')->all();
  $delivery_notes = ORM::for_table('sys_invoices')->select('sys_invoices.*')->select('sys_users.fullname')->left_outer_join('sys_users', "sys_invoices.c5 = sys_users.id")->where('c1', '1')->where('c2', $today)->order_by_desc('c2')->find_array();
  $ui->assign('dn', $delivery_notes);
  $ui->assign('today', $today);
    

  view('crmdeliverychallan_list', [
    'paid' => $paid,
    'unpaid' => $unpaid,
    'partially_paid' => $partially_paid,
    'cancelled' => $cancelled,
    'invoice_paid_amount' => $invoice_paid_amount,
    'invoice_un_paid_amount' => $invoice_un_paid_amount,
    'invoice_cancelled_amount' => $invoice_cancelled_amount,
    'invoice_partially_paid_amount' => $invoice_partially_paid_amount,
    'p' => $p,
  'contacts' => $contacts
]);
  /*view('invoices_list', [
      'paid' => $paid,
      'unpaid' => $unpaid,
      'partially_paid' => $partially_paid,
      'cancelled' => $cancelled,
      'invoice_paid_amount' => $invoice_paid_amount,
      'invoice_un_paid_amount' => $invoice_un_paid_amount,
      'invoice_cancelled_amount' => $invoice_cancelled_amount,
      'invoice_partially_paid_amount' => $invoice_partially_paid_amount,
      'p' => $p,
    'contacts' => $contacts
  ]);*/


    break;

        
    case 'view': //Delivery challan  view;



        $extraHtml = '';
        $id = $routes['2'];
        $app->emit('invoices_view',[&$id]);



        $d = ORM::for_table('sys_invoices')->find_one($id);
        if ($d) {

            // find all activity for this user

            if(!$sales_all_data)
            {
                if($d->aid != $user->id)
                {
                    permissionDenied();
                }
            }

            $items = ORM::for_table('sys_invoiceitems')->where('invoiceid', $id)->order_by_asc('id')->find_many();
            $ui->assign('items', $items);

            // find related transactions

            $trs_c = ORM::for_table('sys_transactions')->where('iid', $id)->count();
            $trs = ORM::for_table('sys_transactions')->where('iid', $id)->order_by_desc('id')->find_many();
            $ui->assign('trs', $trs);
            $ui->assign('trs_c', $trs_c);
            $emls_c = ORM::for_table('sys_email_logs')->where('iid', $id)->count();
            $emls = ORM::for_table('sys_email_logs')->where('iid', $id)->order_by_desc('id')->find_many();
            $ui->assign('emls', $emls);
            $ui->assign('emls_c', $emls_c);
            $a = ORM::for_table('crm_accounts')->find_one($d['userid']);
            $ui->assign('a', $a);
            $ui->assign('d', $d);
            $i_credit = $d['credit'];
            $i_due = '0.00';
            $i_total = $d['total'];
            if ($d['credit'] != '0.00') {
                $i_due = $i_total - $i_credit;
            }
            else {
                $i_due = $d['total'];
            }

            $i_due = number_format($i_due, 2, $config['dec_point'], $config['thousands_sep']);
            $ui->assign('i_due', $i_due);
            $cf = ORM::for_table('crm_customfields')->where('showinvoice', 'Yes')->order_by_asc('id')->find_many();
            $ui->assign('cf', $cf);
            $ui->assign('xheader', Asset::css(array(
                's2/css/select2.min',
                'dropzone/dropzone',
                'dp/dist/datepicker.min',
                'sn/summernote',
                'sn/summernote-bs3',
                'modal'
            )));
            $ui->assign('xfooter', Asset::js(array(
                's2/js/select2.min',
                's2/js/i18n/' . lan() ,
                'dp/dist/datepicker.min',
                'dp/i18n/' . $config['language'],
                'numeric',
                'modal',
                'sn/summernote.min',
                'dropzone/dropzone'
            )));
            $x_html = '';
            Event::trigger('view_invoice');
            $ui->assign('x_html', $x_html);

            $upload_max_size = ini_get('upload_max_filesize');
            $post_max_size = ini_get('post_max_size');
            $ui->assign('upload_max_size', $upload_max_size);
            $ui->assign('post_max_size', $post_max_size);

            // count attachments

            $inv_files = Invoice::files($id);
            $inv_files_c = count($inv_files);
            $ui->assign('inv_files_c', $inv_files_c);
            $ui->assign('inv_files', $inv_files);
            $access_logs = ORM::for_table('ib_invoice_access_log')->where('iid', $id)->order_by_desc('id')->find_array();
            $ui->assign('access_logs', $access_logs);

            $currency_rate = 1;


            // find the company

            if($a->cid != '' || $a->cid != 0){
                $company = Company::find($a->cid);
            }
            else{
                $company = false;
            }


            // find the quote

            $quote = false;

            if($d->quote_id != '0'){
                $quote = ORM::for_table('sys_quotes')->find_one($d->quote_id);
            }

            $currencies_all = Currency::getAllCurrencies();

            if(isset($currencies_all[$d->currency_iso_code]))
            {
                $data_a_sign = $currencies_all[$d->currency_iso_code]['symbol'];
                $data_a_sep = $currencies_all[$d->currency_iso_code]['thousands_separator'];
                $data_a_dec = $currencies_all[$d->currency_iso_code]['decimal_mark'];

                if($currencies_all[$d->currency_iso_code] == true)
                {
                    $data_p_sign = 'p';
                }
                else{
                    $data_p_sign = 's';
                }

            }
            else{
                $data_a_sign = $config['currency_code'];
                $data_a_sep = $config['thousands_sep'];
                $data_a_dec = $config['dec_point'];
                $data_p_sign = $config['currency_symbol_position'];
            }

            //

            view('crmdeliverychallan_view', [
                'currencies' => Currency::all() ,
                'currency_rate' => $currency_rate,
                'company' => $company,
                'quote' => $quote,
                'extraHtml' => $extraHtml,
                'data_a_sign' => $data_a_sign,
                'data_a_sep' => $data_a_sep,
                'data_a_dec' => $data_a_dec,
                'data_p_sign' => $data_p_sign
            ]);
        }
        else {
            r2(U . 'customers/list', 'e', $_L['Account_Not_Found']);
        }

        break;


  case 'deliverychallan-add':
    case 'add':
    case 'edit':
  
  
  
          $customers_all_data = has_access($user->roleid,'customers','all_data');
  
          $extraHtml = '';
  
          $app->emit('invoices_add');
  
          $extra_fields = '';
          $extra_jq = '';
  
          Event::trigger('add_invoice');
  
          $ui->assign('extra_fields', $extra_fields);
  
      $recurring = false;
  
      $p_cid = '';
  
      $invoice = false;
      $contact = false;
      $items = false;
  
          if($action == 'add')
          {
              if (isset($routes['2']) AND ($routes['2'] == 'recurring')) {
                  $recurring = true;
              }
  
              if (isset($routes['3']) && ($routes['3'] != '') && ($routes['3'] != '0')) {
                  $p_cid = $routes['3'];
                  $p_d = ORM::for_table('crm_accounts')->find_one($p_cid);
                  if (!$p_d) {
                     $p_cid = '';
                  }
              }
  
              $ui->assign('_st', $_L['Add Invoice']);
          }
  
          elseif ($action == 'edit')
          {
              $id = route(2);
              $invoice = Invoice::find($id);
  
              $p_cid = $invoice->userid;
  
              if($invoice->r != 0)
              {
                  $recurring = true;
              }
  
  
          }
  
          if($invoice)
          {
              $contact = Contact::find($invoice->userid);
              $items = InvoiceItem::where('invoiceid',$invoice->id)->orderBy('id','asc')->get();
          }
      $ui->assign('p_cid', $p_cid);
  
  
  
      $ui->assign('recurring', $recurring);
  
          $c = ORM::for_table('crm_accounts')->select('id')->select('account')->select('company')->select('email')->order_by_desc('id')->where_like('type','%Customer%');
          $driver = ORM::for_table('sys_users')->select('id')->select('fullname')->select('username')->select('email')->order_by_desc('id')->where_like('user_type','%Driver%')->where('status', 'Active');
           $driver = $driver->find_array();

        $ui->assign('driver', $driver);


  
  
          if(!$customers_all_data)
          {
              $c->where('o',$user->id);
          }
  
  
          $c = $c->find_array();
  
          $ui->assign('c', $c);
          $t = ORM::for_table('sys_tax')->find_array();
          $ui->assign('t', $t);
          $ui->assign('idate', date('Y-m-d'));
  
          $tax_default = ORM::for_table('sys_tax')->where('is_default',1)->find_one();
  
  
          $tax_system = $config['tax_system'];
  
          switch ($tax_system){
  
              case 'India':
  
  
                  $states = Tax::indianStates();
  
  
                  break;
  
              default:
  
                  $states = [];
  
          }
  
  
          $css_arr = array(
              's2/css/select2.min',
              'modal',
              'dp/dist/datepicker.min',
              'redactor/redactor'
          );
          $js_arr = array(
              'redactor/redactor.min',
              's2/js/select2.min',
              's2/js/i18n/' . lan() ,
              'dp/dist/datepicker.min',
              'dp/i18n/' . $config['language'],
              'numeric',
              'filter.min',
              'modal',
              'js/filtertable',
              'js/redirect',
              'tinymce/tinymce.min',
              'js/editor',
              'imgcrop/croppic',
              'numeric',
          );
  
          $pos = route(4);
  
  
  
          Event::trigger('add_invoice_rendering_form');
          $ui->assign('xheader', Asset::css($css_arr));
          $ui->assign('xfooter', Asset::js($js_arr));
  
  
  
          view('crmdeliverychallan-add',[
              'pos' => $pos,
              'tax_default' => $tax_default,
              'states' => $states,
              'extraHtml' => $extraHtml,
              'currencies' => getActiveCurrencies(),
              'invoice' => $invoice,
              'contact' => $contact,
              'items' => $items
          ]);
  
  
  break;

  case 'deliverychallan-add-post':
    

    $invoice_id = _post('invoice_id');

    $invoice = false;

    if($invoice_id != '')
    {
        $invoice = Invoice::find($invoice_id);
    }

    $app->emit('invoices_add_post');

    $cid = _post('cid');

    // find user with cid

    $u = ORM::for_table('crm_accounts')->find_one($cid);
    $msg = '';
    if ($cid == '') {
        $msg.= $_L['select_a_contact'] . ' <br /> ';
    }

    $notes = _post('notes');

    $show_quantity_as = _post('show_quantity_as');


    if($_POST['lat']=='' || $_POST['lon'] == '' ){
      $msg.= "Latitude and Longitude is empty please update you address or add a new shipping address";
    } 

    // find currency

    $currency_id = _post('currency');
    $currency_find = Currency::where('iso_code',$currency_id)->first();
    if ($currency_find) {
        $currency = $currency_find->id;
        $currency_symbol = $currency_find->symbol;
        $currency_rate = $currency_find->rate;
    }
    else {
        $currency = 0;
        $currency_symbol = $config['currency_code'];
        $currency_rate = 1.0000;
    }

    if (isset($_POST['amount'])) {
        $amount = $_POST['amount'];
    }
    else {
        $msg.= $_L['at_least_one_item_required'] . ' <br /> ';
    }

    $idate = _post('idate');
    $its = strtotime($idate);


    $duedate = _post('duedate');


    $dd = '';

    if(!$invoice)
    {
        if ($duedate == 'due_on_receipt') {
            $dd = $idate;
        }
        elseif ($duedate == 'days3') {
            $dd = date('Y-m-d', strtotime('+3 days', $its));
        }
        elseif ($duedate == 'days5') {
            $dd = date('Y-m-d', strtotime('+5 days', $its));
        }
        elseif ($duedate == 'days7') {
            $dd = date('Y-m-d', strtotime('+7 days', $its));
        }
        elseif ($duedate == 'days10') {
            $dd = date('Y-m-d', strtotime('+10 days', $its));
        }
        elseif ($duedate == 'days15') {
            $dd = date('Y-m-d', strtotime('+15 days', $its));
        }
        elseif ($duedate == 'days30') {
            $dd = date('Y-m-d', strtotime('+30 days', $its));
        }
        elseif ($duedate == 'days45') {
            $dd = date('Y-m-d', strtotime('+45 days', $its));
        }
        elseif ($duedate == 'days60') {
            $dd = date('Y-m-d', strtotime('+60 days', $its));
        }
        else {
            $msg.= 'Invalid Date <br /> ';
        }

        if (!$dd) {
            $msg.= 'Date Parsing Error <br /> ';
        }
    }
    else{
        $dd = $duedate;
    }

    $repeat = _post('repeat');
    $nd = $idate;
    if ($repeat == '0') {
        $r = '0';
    }
    elseif ($repeat == 'daily') {
        $r = '+1 day';
        $nd = date('Y-m-d', strtotime('+1 day', $its));
    }
    elseif ($repeat == 'week1') {
        $r = '+1 week';
        $nd = date('Y-m-d', strtotime('+1 week', $its));
    }
    elseif ($repeat == 'weeks2') {
        $r = '+2 weeks';
        $nd = date('Y-m-d', strtotime('+2 weeks', $its));
    }
    elseif ($repeat == 'weeks3') {
        $r = '+3 weeks';
        $nd = date('Y-m-d', strtotime('+3 weeks', $its));
    }
    elseif ($repeat == 'weeks4') {
        $r = '+4 weeks';
        $nd = date('Y-m-d', strtotime('+4 weeks', $its));
    }
    elseif ($repeat == 'month1') {
        $r = '+1 month';
        $nd = date('Y-m-d', strtotime('+1 month', $its));
    }
    elseif ($repeat == 'months2') {
        $r = '+2 months';
        $nd = date('Y-m-d', strtotime('+2 months', $its));
    }
    elseif ($repeat == 'months3') {
        $r = '+3 months';
        $nd = date('Y-m-d', strtotime('+3 months', $its));
    }
    elseif ($repeat == 'months6') {
        $r = '+6 months';
        $nd = date('Y-m-d', strtotime('+6 months', $its));
    }
    elseif ($repeat == 'year1') {
        $r = '+1 year';
        $nd = date('Y-m-d', strtotime('+1 year', $its));
    }
    elseif ($repeat == 'years2') {
        $r = '+2 years';
        $nd = date('Y-m-d', strtotime('+2 years', $its));
    }
    elseif ($repeat == 'years3') {
        $r = '+3 years';
        $nd = date('Y-m-d', strtotime('+3 years', $its));
    }
    else {
        $msg.= 'Date Parsing Error <br /> ';
    }

        

    if ($msg == '') {

        $business_number = _post('business_number');

        if($business_number != '' && $u->business_number != $business_number)
        {
            $u->business_number = $business_number;
            $u->save();
        }

        $is_same_state = 1;

        if($config['tax_system'] == 'India')
        {
            $place_of_supply = _post('place_of_supply');

            if($place_of_supply == $config['business_location'])
            {
                $is_same_state = 1;
            }
            else{
                $is_same_state = 0;
            }
        }

        $qty = $_POST['qty'];
        $item_number = $_POST['item_code'];

        if (isset($_POST['taxed'])) {
            $taxed = $_POST['taxed'];
        }
        else {
            $taxed = false;
        }

        $sTotal = '0';
        $taxTotal = '0';
        $i = '0';
        $a = array();


        $taxval = '0.00';
        $taxname = '';
        $taxrate = '0.00';



        $taxed_amount = 0.00;
        $lamount = 0.00;

        $discounts = $_POST['discount'];

        $discount_type = _post('discount_type');

        $total_discount = 0.00;

        $sub_total_without_discount = 0.00;

        foreach($amount as $samount) {

            $samount = createFromCurrency($samount,$currency_id);
            $a[$i] = $samount;
            /* @since v 2.0 */

            $sqty = $qty[$i];
          //  $sqty = Finance::amount_fix($sqty);
            $sqty = createFromCurrency($sqty,$currency_id);

            $lTaxRate = $taxed[$i];

            $lTaxRate = Finance::amount_fix($lTaxRate);

            $line_discount = $discounts[$i];



            $line_discount = createFromCurrency($line_discount,$currency_id);

            $line_total = $samount * ($sqty);

            $line_total_without_discount = $line_total;

            if($discount_type == 'p')
            {
                $line_discount = $line_total*($line_discount/100);
            }


            $line_total = $line_total-$line_discount;

            $total_discount += $line_discount;

            $sTotal+= $line_total;
            $lamount = $line_total;

            $lTaxVal = ($lamount*$lTaxRate)/100;

            $taxed_amount += $lTaxVal;

            $sub_total_without_discount += $line_total_without_discount;

            $i++;
        }




        $invoicenum = _post('invoicenum');
        $cn = _post('cn');
        $fTotal = $sTotal;


     //   $discount_amount = _post('discount_amount');
        $discount_type = _post('discount_type');
        $discount_value = '0.00';



        $fTotal = $fTotal + $taxed_amount;



        $status = _post('status');
        if ($status != 'Draft') {
            $status = 'Unpaid';
        }

        $receipt_number = _post('receipt_number');

        $title = _post('title');

        $datetime = date("Y-m-d H:i:s");


        if(!$invoice)
        {

            $invoice = new Invoice;

            $vtoken = _raid(10);
            $ptoken = _raid(10);

            $invoice->vtoken = $vtoken;
            $invoice->ptoken = $ptoken;


        }

        $invoice->userid = $cid;
        $invoice->account = $u['account'];
        $invoice->date = $idate;
        $invoice->duedate = $dd;
        $invoice->datepaid = $datetime;
        $invoice->subtotal = $sub_total_without_discount;
        $invoice->discount_type = $discount_type;
        $invoice->discount_value = $discount_value;
        $invoice->discount = $total_discount;
        $invoice->total = $fTotal;
        $invoice->tax = $taxed_amount;
        $invoice->taxname = '';
        $invoice->taxrate = 0.00;
        $invoice->status = $status;
        $invoice->notes = $notes;
        $invoice->r = $r;
        $invoice->nd = $nd;
        $invoice->aid = $user->id;
        $invoice->is_same_state = $is_same_state;
        $invoice->show_quantity_as = $show_quantity_as;
        $invoice->invoicenum = $invoicenum;
        $invoice->cn = $cn;
        $invoice->tax2 = '0.00';
        $invoice->taxrate2 = '0.00';
        $invoice->paymentmethod = '';
        $invoice->currency = $currency;
        $invoice->currency_symbol = $currency_symbol;
        $invoice->currency_rate = $currency_rate;
        $invoice->currency_iso_code = $currency_id;
        $invoice->receipt_number = $receipt_number;
        $invoice->title = $title;
        
        $invoice->c1 = 1;
        $invoice->c2 = $_POST['delivery_date'];
        $invoice->c3 = $_POST['lat'];
        $invoice->c4 = $_POST['lon'];
        if($_POST['driver']==''){
          $invoice->c5 = '';
          
        }else
        {
          $invoice->c5 = $_POST['driver'];
          $invoice->delivery_status = "Assigned";
         
        }
        
        
        
        

        
        $invoice->save();



        $invoiceid = $invoice->id;
        $description = $_POST['desc'];

          /* For advanced Description */
        //   $rownumber = _post('table_row');
        //   $c_detail = _post('c_detail');
           /* For Description */



        if(isset($_POST['tax_code']))
        {
            $tax_code = $_POST['tax_code'];
        }
        else{
            $tax_code = [];
        }


        $i = '0';

        if($invoice)
        {
            InvoiceItem::where('invoiceid',$invoice->id)->delete();
        }
       // $rowcount= 0 ;// for detaild descriptiom
        foreach($description as $item) {


            $samount = $a[$i];

          //  $samount = Finance::amount_fix($samount);

         //   $samount = createFromCurrency($samount,$currency_id);
         if ($item == '' && $samount == '0.00') {
                $i++;
                continue;
            }

            $tax_rate = $taxed[$i];

            /* @since v 2.0 */
            $sqty = $qty[$i];
          //  $sqty = Finance::amount_fix($sqty);
            $sqty = createFromCurrency($sqty,$currency_id);

            $line_discount = $discounts[$i];
            $line_discount = createFromCurrency($line_discount,$currency_id);

            $line_total = $samount * ($sqty);

            if($discount_type == 'p')
            {
                $line_discount = $line_total*($line_discount/100);
            }

            $line_total = $line_total-$line_discount;

            $sTotal+= $line_total;
            $lamount = $line_total;

            $lTaxVal = ($lamount*$lTaxRate)/100;

            $taxed_amount += $lTaxVal;



            $d = ORM::for_table('sys_invoiceitems')->create();
            $d->invoiceid = $invoiceid;
            $d->userid = $cid;
        //     if($rownumber == $rowcount && $c_detail != "" ) {
        //         $d->description = $c_detail;
        //       }
        //       else{
        //       $d->description = $item;
        //       }
            $d->description = $item;
            $d->qty = $sqty;
            $d->amount = $samount;
            $d->total = $line_total;



            if($tax_rate == '' || $tax_rate == '0'){
                $tax_rate = 0.00;
                $d->taxed = '0';
            }
            else{
                $tax_rate = $taxed[$i];
                $d->taxed = '1';
            }

            $d->tax_rate = $tax_rate;

            $item_taxed_amount = round(($tax_rate*($sqty*$samount))/100,2);


            $d->type = '';
            $d->relid = '0';
            $d->itemcode = $item_number[$i];
            $d->taxamount = $item_taxed_amount;
            $d->duedate = date('Y-m-d');
            $d->paymentmethod = '';
            $d->notes = '';


            $d->discount_type = $discount_type;
            $d->discount_amount = $line_discount;

            if(isset($tax_code[$i]))
            {
                $d->tax_code = $tax_code[$i];
            }
            else{
                $d->tax_code = '';
            }

            $d->save();

            Inventory::decreaseByItemNumber($item_number[$i], $sqty);

            // Add Sales Count

            $item_r = Item::where('name', $item)->first();
            if ($item_r) {
                $item_r->sold_count = $item_r->sold_count + $sqty;
                $item_r->total_amount = $item_r->total_amount + $samount;
                $item_r->save();
            }

            $i++;
          //  $rowcount++; // for description

        }

        $code = _post('cn');

        update_option('invoice_code_current_number',current_number_would_be($cn));

        $app->emit('invoices_add_post_done',[$invoiceid]);

        echo $invoiceid;
    }
    else {
        echo $msg;
    }

    break;

    case 'deliverychallan-veiw':



      $extraHtml = '';
      $id = $routes['2'];
      $app->emit('invoices_view',[&$id]);



      $d = ORM::for_table('sys_invoices')->find_one($id);
      if ($d) {

          // find all activity for this user

          if(!$sales_all_data)
          {
              if($d->aid != $user->id)
              {
                  permissionDenied();
              }
          }

          $items = ORM::for_table('sys_invoiceitems')->where('invoiceid', $id)->order_by_asc('id')->find_many();
          $ui->assign('items', $items);

          // find related transactions

          $trs_c = ORM::for_table('sys_transactions')->where('iid', $id)->count();
          $trs = ORM::for_table('sys_transactions')->where('iid', $id)->order_by_desc('id')->find_many();
          $ui->assign('trs', $trs);
          $ui->assign('trs_c', $trs_c);
          $emls_c = ORM::for_table('sys_email_logs')->where('iid', $id)->count();
          $emls = ORM::for_table('sys_email_logs')->where('iid', $id)->order_by_desc('id')->find_many();
          $ui->assign('emls', $emls);
          $ui->assign('emls_c', $emls_c);
          $a = ORM::for_table('crm_accounts')->find_one($d['userid']);
          $ui->assign('a', $a);
          $ui->assign('d', $d);
          $i_credit = $d['credit'];
          $i_due = '0.00';
          $i_total = $d['total'];
          if ($d['credit'] != '0.00') {
              $i_due = $i_total - $i_credit;
          }
          else {
              $i_due = $d['total'];
          }

          $i_due = number_format($i_due, 2, $config['dec_point'], $config['thousands_sep']);
          $ui->assign('i_due', $i_due);
          $cf = ORM::for_table('crm_customfields')->where('showinvoice', 'Yes')->order_by_asc('id')->find_many();
          $ui->assign('cf', $cf);
          $ui->assign('xheader', Asset::css(array(
              's2/css/select2.min',
              'dropzone/dropzone',
              'dp/dist/datepicker.min',
              'sn/summernote',
              'sn/summernote-bs3',
              'modal'
          )));
          $ui->assign('xfooter', Asset::js(array(
              's2/js/select2.min',
              's2/js/i18n/' . lan() ,
              'dp/dist/datepicker.min',
              'dp/i18n/' . $config['language'],
              'numeric',
              'modal',
              'sn/summernote.min',
              'dropzone/dropzone'
          )));
          $x_html = '';
          Event::trigger('view_invoice');
          $ui->assign('x_html', $x_html);

          $upload_max_size = ini_get('upload_max_filesize');
          $post_max_size = ini_get('post_max_size');
          $ui->assign('upload_max_size', $upload_max_size);
          $ui->assign('post_max_size', $post_max_size);

          // count attachments

          $inv_files = Invoice::files($id);
          $inv_files_c = count($inv_files);
          $ui->assign('inv_files_c', $inv_files_c);
          $ui->assign('inv_files', $inv_files);
          $access_logs = ORM::for_table('ib_invoice_access_log')->where('iid', $id)->order_by_desc('id')->find_array();
          $ui->assign('access_logs', $access_logs);

          $currency_rate = 1;


          // find the company

          if($a->cid != '' || $a->cid != 0){
              $company = Company::find($a->cid);
          }
          else{
              $company = false;
          }


          // find the quote

          $quote = false;

          if($d->quote_id != '0'){
              $quote = ORM::for_table('sys_quotes')->find_one($d->quote_id);
          }

          $currencies_all = Currency::getAllCurrencies();

          if(isset($currencies_all[$d->currency_iso_code]))
          {
              $data_a_sign = $currencies_all[$d->currency_iso_code]['symbol'];
              $data_a_sep = $currencies_all[$d->currency_iso_code]['thousands_separator'];
              $data_a_dec = $currencies_all[$d->currency_iso_code]['decimal_mark'];

              if($currencies_all[$d->currency_iso_code] == true)
              {
                  $data_p_sign = 'p';
              }
              else{
                  $data_p_sign = 's';
              }

          }
          else{
              $data_a_sign = $config['currency_code'];
              $data_a_sep = $config['thousands_sep'];
              $data_a_dec = $config['dec_point'];
              $data_p_sign = $config['currency_symbol_position'];
          }

          //

          view('invoices_view', [
              'currencies' => Currency::all() ,
              'currency_rate' => $currency_rate,
              'company' => $company,
              'quote' => $quote,
              'extraHtml' => $extraHtml,
              'data_a_sign' => $data_a_sign,
              'data_a_sep' => $data_a_sep,
              'data_a_dec' => $data_a_dec,
              'data_p_sign' => $data_p_sign
          ]);
      }
      else {
          r2(U . 'customers/list', 'e', $_L['Account_Not_Found']);
      }

      break;

  
    case 'tasks':
        
       // $ui->assign('_application_menu', 'driver');
        if(!isset($_POST['selected_date'])){
          $mdate = date('Y-m-d');
        }
        else{
          $mdate = $_POST['selected_date'];
        }
      
        $unassigned = ORM::for_table('sys_invoices')->select('sys_invoices.*')->select('sys_users.fullname')->select('crm_accounts.address')->left_outer_join('sys_users', "sys_invoices.c5 = sys_users.id")->left_outer_join('crm_accounts', "crm_accounts.id = sys_invoices.userid")->where('c1', '1')->where_like('c2', $mdate.'%')->where("delivery_status", "Unassigned")->order_by_desc('id')->find_array();
        $assigned = ORM::for_table('sys_invoices')->select('sys_invoices.*')->select('sys_users.fullname')->select('crm_accounts.address')->left_outer_join('sys_users', "sys_invoices.c5 = sys_users.id")->left_outer_join('crm_accounts', "crm_accounts.id = sys_invoices.userid")->where('c1', '1')->where_like('c2', $mdate.'%')->where_not_equal("delivery_status", "Unassigned")->where_not_equal("delivery_status", "Successful")->order_by_desc('id')->find_array();
        $completed = ORM::for_table('sys_invoices')->select('sys_invoices.*')->select('sys_users.fullname')->select('crm_accounts.address')->left_outer_join('sys_users', "sys_invoices.c5 = sys_users.id")->left_outer_join('crm_accounts', "crm_accounts.id = sys_invoices.userid")->where('c1', '1')->where_like('c2', $mdate.'%')->where("delivery_status", "Successful")->order_by_desc('id')->find_array();
        $all =   ORM::for_table('sys_invoices')->select('sys_invoices.*')->select('sys_users.fullname')->select('crm_accounts.address')->left_outer_join('sys_users', "sys_invoices.c5 = sys_users.id")->left_outer_join('crm_accounts', "crm_accounts.id = sys_invoices.userid")->where('c1', '1')->where_like('c2', $mdate.'%')->order_by_desc('id')->find_array();
        
        $c = ORM::for_table('sys_users')->select('id')->select('fullname')->select('username')->select('email')->order_by_desc('id')->where_like('user_type','%Driver%')->where('status', 'Active');
        $c = $c->find_array();
      
        $ui->assign('c', $c);
        //$delivery_notes = ORM::for_table('sys_invoices')->where_not_equal('c1' '1')->order_by_desc('id')->find_array();//Invoice //DeliveryNote::all();
          $ui->assign('un', $unassigned);
          $ui->assign("as", $assigned);
          $ui->assign("co", $completed);
          $ui->assign("all", $all);
      
        //print_r($delivery_notes); die();
      /*  view('sales_delivery_notes',[
            'delivery_notes' => $delivery_notes
        ]);*/
      
        $ui->assign('mdate', $mdate);
        $ui->assign('xheader', Asset::css(array(
            'dropzone/dropzone',
            'modal',
            's2/css/select2.min',
            'dp/dist/datepicker.min'
        )));
        $ui->assign('xfooter', Asset::js(array(
            'modal',
            'dropzone/dropzone',
            's2/js/select2.min',
            's2/js/i18n/' . lan() ,
            'dp/dist/datepicker.min',
            'dp/i18n/' . $config['language'],
            'numeric'
        )));
      
        view('crmviewtask');
      

    break;

  
case 'assign_driver':
                        $invoice_id = _post('invoice');
                        $driver_id =  _post('cid');
                        if  ($driver_id==''){
                          $sql = "update sys_invoices set c5 = NULL, delivery_status='Unassigned' where id='$invoice_id'";
                        }else{
                        $sql = "update sys_invoices set c5='$driver_id', delivery_status='Assigned'  where id='$invoice_id'";
                      }
                        $data = ORM::execute($sql);
                        if ($data == 1)
                        {
                          echo "Successfully Assigned Driver";
                        }
                        else
                        {
                          echo "Error Occured";
                        }
                      break;

        
    case 'modal-item-details':  //For description adding in invoice and delivey chellan

        echo '
            <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3>Details</h3>
            </div>
            <div class="modal-body">

            <!--    <form class="form-horizontal" role="form" id="edit_form" method="post">-->


            <div class="form-group">
            <label for="message" class="col-sm-2 control-label">'.$_L['Message Body'].'</label>
            <div class="col-sm-10">
            <textarea id="crmproduct_description" name="crmproduct_description" class="form-control" rows="10"></textarea>

            </div>
            </div>

            <!--</form>-->

            </div>
            <div class="modal-footer">


            <button type="button" data-dismiss="modal" class="btn">'.$_L['Close'].'</button>
            <button id="update_editor" data-dismiss="modal" class="btn btn-primary">'.$_L['Save'].'</button>
            </div>
            ';


    break;

    case 'import_csv':

        $ui->assign('_application_menu', 'driver');
        
            $ui->assign('xheader', Asset::css(array('dropzone/dropzone')));
        
        
            $ui->assign('xfooter', Asset::js(array('dropzone/dropzone','crmjs/crmimport')));
        
        
        
            view('crmtask_import');
        
        
        
            break;

            case 'csv_upload':

    $uploader   =   new Uploader();
    $uploader->setDir('storage/temp/');
   // $uploader->sameName(true);
    $uploader->setExtensions(array('csv'));  //allowed extensions list//
    if($uploader->uploadFile('file')){   //txtFile is the filebrowse element name //
        $uploaded  =   $uploader->getUploadName(); //get uploaded file name, renames on upload//

        $_SESSION['uploaded'] = $uploaded;

    }else{//upload failed
        _msglog('e',$uploader->getMessage()); //get upload error message
    }


    break;

    case 'bsa_csvupload':
        
    break;
    

    case 'csv_uploaded':

        $alphabet = range('A', 'Z');
        $cn = 0;
        $col_data_missed = 0;
        $data_existed = 0;
        $email_empty = 0;
        $success = 1;
        $delivery_saved = 0;
        $error_array=[];
        $error_id = 0;
        $e = 0;
        if(isset($_SESSION['uploaded']))
        {
            
            
            $row = 1;
            $uploaded = $_SESSION['uploaded'];
            $csv = $fields = array(); $i = 0;
            

            $handle = fopen(APP_URL."/storage/temp/".$uploaded, "r");
            if ($handle) 
            {
                while (($row = fgetcsv($handle, 4096)) !== false) 
                {
                
                    
                     if (empty($fields)) {
                         $fields = $row;
                         continue;
                     }
                     $m=0;
                     foreach ($row as $k=>$value) {
                         //$csv[$i][$fields[$k]] = $value;
                         $csv[$i][$m++] = $value;
                         if(strpos($value, "\n") !== FALSE) {
                        //     echo 'New line break found';
                             $error_array[$error_id]['delivery_id'] =  $csv[$i][0];
                             $error_array[$error_id++]['log'] =  "New line break found at column ".$alphabet[$m-1].($i+1). "[value => $value ]";
                             $e=1;
                            }
                     }
                     $i++;
                }
                if (!feof($handle)) 
                {
                    // echo "Error: unexpected fgets() fail\n";
                     $success   = 0;
                }
                fclose($handle);
            }
          
            

        }
        else
        {
                $success = 0;
                //echo "File can't be opend";
        }


        if($success==1 && $e == 0)
        {
            // echo "<pre>";
            // print_r($csv); 
            // echo "</pre>";
            // die();
            $count = 0;
            for($i=0; $i<count($csv); $i = $i+$count)
            {
                echo "<br/>Selected $i th row";
                $count = 0;
                if(!isset($csv[$i][25])){
                
                    $error_array[$error_id]['delivery_id'] =  $csv[$i][0];
                    $error_array[$error_id++]['log'] =  "Incomplete data ";
                    
                    $count++;
                    continue; 
                }
                  $delivery_id = $csv[$i][0];
                  $col_data_missed++; 
                

                $d = ORM::for_table('sys_invoices')->where('cn', $delivery_id)->find_one();
                // echo "<br/>     now seletecd ".$delivery_id." of ".$i. "th row ";
                // echo " count = ".$count;
                if($d)
                {
                  //  echo " This is already existed <br/>";
                     $data_existed++;
                     
                     $error_array[$error_id]['delivery_id'] =  $csv[$i][0];
                     $error_array[$error_id++]['log'] =  "Duplicate Delivery ID";
                    

                    for($j=$i+1; $j<count($csv); $j++)
                    {   
                        // echo "i = ".$i. " and j = ".$j;
                        // echo "checking ".$csv[$i][0].' == '. $csv[$j][0];
                        // echo "<br/>";

                         if ($csv[$i][0]==$csv[$j][0]) 
                         {  
                             
                             $count++;
                         }
                         else
                         {
                            //$count++;   
                            break;
                         }
                    }

                    $count++; 
                     continue;
                }

                 $email = $csv[$i][3];
                 //check customer exist or not 
                
                
                if($email=="")
                {  
                    $error_array[$error_id]['delivery_id'] =  $csv[$i][0];
                    $error_array[$error_id++]['log'] =  "Email Field Empty";
                    
                    $email_empty++;
                    $count++;
                    continue;
                }
                 $d = ORM::for_table('crm_accounts')->where('email', $email)->find_one();
                if($d)
                {       //account already exist.

                     $delivery['userid'] = $d->id;
                     $delivery['account'] = $d->account;
                     
                }
                else
                {       //create new account

                    $account = $csv[$i][1];
                    if($account=="")
                    {
                        $account = $email;
                    }
                    $type = 'Customer';
                    $company =  $csv[$i][13];

                    $cid = 0;
                    if($company != ''){

                        $company_db= ORM::for_table('sys_companies')->where('company_name', $company)->find_array();
                        if(!empty($company_db))
                        {
                            $company = $company_db[0]['company_name'] ;
                            $cid = $company_db[0]['id'];
                            
                        }
                        else 
                        {
                           
                            $comp = ORM::for_table('sys_companies')->create();
                            $comp->company_name = $company;
                            $comp->save();
                            $cid = $comp->id;

                        }

                            
            
                    }

                    $username = $email;
                    $phone = $csv[$i][2];
                    

             
                    $address = $csv[$i][5];
                     
                     //$city = _post('city');
                     //$state = _post('state');
                    $zip = $csv[$i][7];
                    $country = "Sinagapore";
                    $code = predict_next_serial($config,'customer');
                     
  
                    $currency = '0';
             
                    $tags = '';
             
             
                    $msg = '';

                    if($phone != '')
                    {
            
                        $f = ORM::for_table('crm_accounts')->where('phone',$phone)->find_one();
            
                        if($f)
                        {
                            //$msg .= $_L['Phone number already exist'].' <br>';
                        }
                    }

                    $gid = 0;
                    $gname = '';
                    $password =  "123456789";
                    $cpassword = "123456789";
             
                    $u_password = '';

                    if($password != '')
                    {
             
             
             
                         if($password != $cpassword)
                         {
                             //$msg .= 'Passwords does not match'. '<br>';
                         }
             
             
                         $u_password = $password;
                         $password = Password::_crypt($password);
             
             
                    }

                     

                    if($msg == '')
                    {
            
                        Tags::save($tags,'Contacts');
            
                        $data = array();
            
                        $data['created_at'] = date('Y-m-d H:i:s');
                        $data['updated_at'] = date('Y-m-d H:i:s');
                        $owners = getOwners($user);
                        foreach($owners as $owner)
                            {
                              //  echo "";die();
                              
                             if($owner->id == $user->id)
                                 $owner_id = $owner->id ;
                            }
                    
                        $d = ORM::for_table('crm_accounts')->create();
                        $d->account = $account;
                        $d->email = $email;
                        $d->phone = $phone;
                        $d->address = $address;
                        $d->city = "";
                        $d->zip = $zip;
                        $d->state = "";
                        $d->country = $country;
                        $d->tags = Arr::arr_to_str($tags);
            
                        //others
                        $d->fname = '';
                        $d->lname = '';
                        $d->company = $company;
                        $d->jobtitle = '';
                        $d->cid = $cid;
                        $d->o = $owner_id;
                        $d->balance = '0.00';
                        $d->status = 'Active';
                        $d->notes = '';
                        $d->password = $password;
                        $d->token = '';
                        $d->ts = '';
                        $d->img = '';
                        $d->web = '';
                        $d->facebook = '';
                        $d->google = '';
                        $d->linkedin = '';
            
                        // v 4.2
            
                        $d->gname = $gname;
                        $d->gid = $gid;
            
                        // build 4550
            
                        $d->currency = $currency;
            
                        //
            
                        $d->created_at = $data['created_at'];
            
                        $d->type = $type;
            
                        //
            
                        $d->business_number = "";//"_post('business_number');
            
                        $d->fax = "";//_post('fax');
            
                        $drive = time().Ib_Str::random_string(12);
            
                        $d->drive = $drive;
            
                        $d->code = $code;
            
                        //
            
                        $d->secondary_email = "";//$secondary_email;




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

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

                            $urlPart = 'address='.$place.'&components=country:'.$country_code;
                            
                        } 
                        else 
                        {
                          //
                        

                        }
       
                        $q = "https://maps.googleapis.com/maps/api/geocode/json?key=".$api_key.'&'.$urlPart;
                    
                        $json = file_get_contents($q);
                        $details = json_decode($json, TRUE);
                       // print_r($details['status']); die();
                        if($details['status']=="ZERO_RESULTS" || $details['status']=="REQUEST_DENIED")
                        {
                        // 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'];
                        

                        $d->lat = $latitude;
                        $d->lon = $longitude;
                    
                        }

                        $d->o = $user->id;
                        
                            
                       $d->save();
            
                       //print_r(array('username' => $username,'password' => _post('password'),'baseurl' => APP_URL, 'clients_client_id' => $config['client_id'], 'role' => 'Client'));
                       $delivery['userid'] = $d->id;
                       $delivery['account'] = $d->account;
                    
                        $cid = $d->id();
            
                        if (CRM_TYPE == "SAAS")
                        {
                            $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' => $email,'password' => _post('password'),'baseurl' => APP_URL, 'clients_client_id' => $config['client_id'], 'role' => 'Client'),
                            ));
                        
                            $response = curl_exec($curl);
                            
                            curl_close($curl);
                        }  
                      
                        if($type == 'Supplier')
                        {
                            update_option('supplier_code_current_number',current_number_would_be($code));
                        }
                        else
                        {
                            update_option('customer_code_current_number',current_number_would_be($code));
                        }
            
                        _log($_L['New Contact Added'].' '.$account.' [CID: '.$cid.']','Admin',$user->id);
            
                        Event::trigger('contacts/add-post/_on_finished');
            
                            // send welcome email if needed
                
                            /*$send_client_signup_email = _post('send_client_signup_email');
                
                
                            if(($email != '') && ($send_client_signup_email == 'Yes') && ($u_password != '')){
                
                                $email_data = array();
                                $email_data['account'] = $account;
                                $email_data['company'] = $company;
                                $email_data['password'] = $u_password;
                                $email_data['email'] = $email;
                
                                $send_email = Ib_Email::send_client_welcome_email($email_data);
                
                
                
                            }*/
                
                
                
                            // Create Drive if this feature is enabled
                
            
                        if($config['client_drive'] == '1'){
            
                            if (!file_exists('storage/drive/customers/'.$drive.'/storage')) {
                                mkdir('storage/drive/customers/'.$drive.'/storage',0777,true);
                            }
            
                        }
            
          
            
            
                    }
                    else
                    {
                        //echo $msg;  //Account not created;
                    }





                }               //create new account ends


                $delivery['cn'] = $csv[$i][0];
                $delivery['deliverynum'] = '';
                $delivery['date'] = $csv[$i][4];
                $delivery['priority'] = $csv[$i][6];
                if(isset($csv[$i+1][0]))
                {   
                     
                    if( $csv[$i][0] == $csv[$i+1][0]  && $csv[$i+1][14] != "")
                    {
                       

                        $notes = "";
                        $invoice_id = "";
                        $invoice = false;

                        if($invoice_id != '')
                        {
                            $invoice = Invoice::find($invoice_id);
                        }

                        $app->emit('invoices_add_post');

                        $cid = _post('cid');

                        $currency = 0;
                        $currency_symbol = $config['currency_code'];
                        $currency_rate = 1.0000;

                        $amount ="0";

                        $idate = $csv[$i][4];
                        $its = strtotime($idate);                                
                        $duedate = 'days30';
                     
                        $dd = date('Y-m-d', strtotime('+30 days', $its));
                             
                        $repeat = "0";
                        $nd = $idate;
                         
                        $r = '0';

 
 
                        $business_number ="";
 
                      
                        $taxed = false;
 
                        $sTotal = '0';
                        $taxTotal = '0';
                     
                        $a = array();
 
 
                        $taxval = '0.00';
                        $taxname = '';
                        $taxrate = '0.00';
 
 
 
                        $taxed_amount = 0.00;
                        $lamount = 0.00;
 
                        $discounts =0.0;
 
                        $discount_type = "p";
 
                        $total_discount = 0.00;
 
                        $sub_total_without_discount = 0.00;
 
 
                        $line_total = 0.0;
 
                     
                        $lamount = 0.0;
             
                        $lTaxVal = 0.0;
             
                        $taxed_amount = 0.0;
                        $sub_total_without_discount  = 0.0;
 
                        $invoicenum = $config['invoice_code_prefix'];
                        $cn =  $delivery['cn'];
 
                        $fTotal = 0.0;
                        $discount_value = '0.00';
                        $status = 'Unpaid';
                        $receipt_number = "";
 
                        $title = "";
                 
                        $datetime = date("Y-m-d H:i:s");
                         
                        $invoice = new Invoice;
 
                        $vtoken = _raid(10);
                        $ptoken = _raid(10);
             
                        $invoice->vtoken = $vtoken;
                        $invoice->ptoken = $ptoken;
                        $invoice->userid = $d->id;
                        $invoice->account = $delivery['account'] ;
                     
                        $invoice->date =  $csv[$i][25];//$idate;
                        $invoice->duedate = $dd;
                     
                        $invoice->datepaid = $datetime;
                        $invoice->subtotal = $sub_total_without_discount;
                        $invoice->discount_type = $discount_type;
                        $invoice->discount_value = $discount_value;
                        $invoice->discount = $total_discount;
                        $invoice->total = $fTotal;
                        $invoice->tax = $taxed_amount;
                        $invoice->taxname = '';
                        $invoice->taxrate = 0.00;
                        $invoice->status = $status;
                        $invoice->notes = $notes;
                        $invoice->r = $r;
                        $invoice->nd = $nd;
                        $invoice->aid = $user->id;
 
                     
                        $invoice->show_quantity_as = "Qty";
                        $invoice->invoicenum = $invoicenum;
                        $invoice->cn = $cn;
                        $invoice->tax2 = '0.00';
                        $invoice->taxrate2 = '0.00';
                        $invoice->paymentmethod = '';
                        $invoice->currency = $currency;
                        $invoice->currency_symbol = "";//$currency_symbol;
                        $invoice->currency_rate = $currency_rate;
                        $invoice->currency_iso_code = "SGD";
                        $invoice->receipt_number = $receipt_number;
                        $invoice->title = $title;
         
                        $invoice->c1 = 1;
                        $invoice->c2 = $csv[$i][4];
                        $invoice->c3 = $d->lat;
                        $invoice->c4 = $d->lon;
                        if(isset($csv[$i][8]) && $csv[$i][8]!="")
                        {
                            
                            $driver_details= ORM::for_table('sys_users')->where('username', $csv[$i][8])->find_array();
                                
                            if(!empty($driver_details))
                            {
                              
                                 $invoice->c5 = $driver_details[0]['id'] ;
                                 $invoice->delivery_status = "Assigned";
                                 
                            }
                            else 
                            {
                                 $invoice->c5 ='';
                            }
                        }
                        else
                        {
                            $invoice->c5 = '';
                        }
                         
                        if($csv[$i][6]=="")
                        {
                            $invoice->sort_order = 0;
                        }
                        else 
                        {
                            $invoice->sort_order = $csv[$i][6];
                        }
                         
                        $invoice->logisticstaskno =$csv[$i][9]; 
                        $invoice->ourrefno	 =$csv[$i][10]; 
                        $invoice->yourrefno =$csv[$i][11]; 
                        $invoice->ltpaymentterms =$csv[$i][12]; 
                        $invoice->deliverynum =   $delivery['deliverynum'];
                        $invoice->ltnotes = $csv[$i][24];
                        //$invoice->c2 = $csv[$i][25];
                        

                        $delivery_saved++;
                        $invoice->save(); 
                         
                       
                        $count= 0;
                        for($j=$i+1; $j<count($csv); $j++)
                        {
                            if($csv[$i][0]==$csv[$j][0])
                            {
                                $count++;
                                $invoiceitems = ORM::for_table('sys_invoiceitems')->create();
                                $invoiceitems->invoiceid = $invoice->id;
                                $invoiceitems->userid = $invoice->userid;
                                $invoiceitems->relid = 0;
                                $invoiceitems->type = "";
                                $invoiceitems->description = $csv[$j][16];
                                $invoiceitems->qty = $csv[$j][15];
                                $invoiceitems->amount = 0.0;
                                $invoiceitems->taxed = 0;
                                $invoiceitems->tax_rate = 0.000;
                                $invoiceitems->taxamount = 0.00;
                                $invoiceitems->notes = "";
                                $invoiceitems->itemcode = $csv[$j][21]; //partno
                                $invoiceitems->discount_type = 'p';
    
                                $invoiceitems->paymentmethod = "";
                                $invoiceitems->duedate = $dd;
                                $invoiceitems->brand = $csv[$j][17];
                                $invoiceitems->model_no = $csv[$j][18];
                                
                                $invoiceitems->serial_no = $csv[$j][19];
                                $invoiceitems->tag_no = utf8_encode($csv[$j][20]);
                                $invoiceitems->part_no = $csv[$j][21];
                                $invoiceitems->range_item = utf8_encode($csv[$j][22]);
                                $invoiceitems->remarks = $csv[$j][23];
                                $invoiceitems->save();
    
                             
                            }
                            else
                            {
                                $count++;
                                break;
                            }
                        }

     


                    }

                }
               $count = 1;  
            }
            $append_text = "";
            if($data_existed>0)
            {
                $append_text = $append_text.'<br>  &nbsp&nbsp'.$data_existed.' Duplicate delivery orders founded and skiped';
            }

            if($email_empty>0)
            {
                $append_text = $append_text.'<br>  &nbsp&nbsp'.$email_empty.' No email id found for customers and skiped.';
            }
            _msglog('s',$delivery_saved.' Delivery Challan Imported'.$append_text);


        }
        else 
        {
            _msglog('e','An Error Occurred while uploading the CSV file');

        }

         ORM::for_table('crmcsv_error')->delete_many();
        for($i=0; $i<count($error_array); $i++)
        {
            $error_tb = ORM::for_table('crmcsv_error')->create();
            $error_tb->delivery_id = $error_array[$i]['delivery_id'];
            $error_tb->error_log = $error_array[$i]['log'];
            $error_tb->save();



        }
    break;
    case 'view_last_csv_error':
        $list = ORM::for_table('crmcsv_error')->select('delivery_id')->select('error_log')->find_array();

            // echo count($error_array);
        
            // echo "<pre>";
            // print_r($list);
            // echo "</pre>";

            echo '<!DOCTYPE html>
                           <html>  
                             <head>    
                               <meta charset="utf-8">    
                               <meta http-equiv="X-UA-Compatible" content="IE=edge">        
                               <title>BS Terminal</title>    
                               <meta name="description" content="">    
                               <meta name="viewport" content="width=device-width, initial-scale=1">    
                               <style>
                               @import url("https://fonts.googleapis.com/css?family=Ubuntu");
                                @import url("https://fonts.googleapis.com/css?family=Ubuntu+Mono"); 
                                body {  
                                background: linear-gradient(45deg, #57003f 0%,#f57453 100%); 
                                font-family: Ubuntu;
                                } 
                                #container {  
                                display: flex;  
                                justify-content: center;  
                                align-items: center;  
                                height: 100vh;
                                } 
                                #terminal {  
                                width: 70vw;  
                                height: 65vh;  
                                box-shadow: 2px 4px 10px rgba(0,0,0,0.5);
                                } 
                                #terminal__bar {  
                                display: flex;  
                                width: 100%;  
                                height: 30px;  
                                align-items: center;  
                                padding: 0 8px;  
                                box-sizing: border-box;  
                                border-top-left-radius: 5px;  
                                border-top-right-radius: 5px;  
                                background: linear-gradient(#504b45 0%,#3c3b37 100%);
                                } 
                                #bar__buttons {  
                                display: flex;  
                                align-items: center;
                                } 
                                .bar__button {  
                                display: flex;  
                                justify-content: center;  
                                align-items: center;  
                                padding: 0;  
                                margin-right: 5px;  
                                font-size: 8px;  
                                height: 12px;  
                                width: 12px;  
                                box-sizing: border-box;  
                                border: none;  
                                border-radius: 100%;  
                                background: linear-gradient(#7d7871 0%, #595953 100%);  
                                text-shadow: 0px 1px 0px rgba(255,255,255,0.2);  
                                box-shadow: 0px 0px 1px 0px #41403A, 0px 1px 1px 0px #474642;
                                }
                                .bar__button:hover {  
                                cursor: pointer;
                                }
                                .bar__button:focus {  
                                outline: none;
                                }
                                #bar__button--exit {  
                                background: linear-gradient(#f37458 0%, #de4c12 100%);    
                                background-clip: padding-box;
                                } 
                                #bar__user {   
                                color: #d5d0ce;  
                                margin-left: 6px;  
                                font-size: 14px;  
                                line-height: 15px;
                                } 
                                #terminal__body {  
                                background: rgba(56, 4, 40, 0.9);  
                                font-family: "Ubuntu Mono";  
                                height: calc(100% - 30px);  
                                padding-top: 2px;  
                                margin-top: -1px;
                                overflow: scroll;

                                } 
                                #terminal__prompt {  
                                display: flex;
                                }
                                #terminal__prompt--user {  
                                color: #7eda28;
                                }
                                #terminal__prompt--location { 
                                color: #4878c0;
                                }
                                #terminal__prompt--bling {  
                                color: #dddddd;
                                }
                                #terminal__prompt--cursor {  
                                display: block;  
                                height: 17px;  
                                width: 8px;  
                                margin-left: 9px;  
                                animation: blink 1200ms linear infinite;
                                } 
                                @keyframes blink {  
                                0% {    
                                background: #ffffff;  
                                }  
                                49% {    
                                background: #ffffff;  
                                }  
                                60% {    
                                background: transparent;  
                                }  
                                99% {    
                                background: transparent;  
                                }  100% {    
                                background: #ffffff;  
                                }
                                } 
                                @media (max-width: 600px) {  
                                #terminal {    
                                max-height: 90%;    
                                width: 90%;  
                                }
                                }
                                                            </style>
                                                            </head>  
                                                            <body>  
                                                            <main id="container">
                                <div id="terminal">
                                <!-- Terminal Bar -->       
                                <section id="terminal__bar">          
                                    <div id="bar__buttons">            
                                    <button class="bar__button" id="bar__button--exit">&#10005;</button>            
                                    <button class="bar__button">&#9472;</button>                
                                    <button class="bar__button">&#9723;</button>          
                                    </div>          
                                    <p id="bar__user">bs@admin: ~</p>        
                                </section>        
                                <!-- Terminal Body -->        
                                <section id="terminal__body">          
                                    <div id="terminal__prompt">            
                                    <span id="terminal__prompt--user">bs@admin:</span>            
                                    <span id="terminal__prompt--location">~</span>            
                                    <span id="terminal__prompt--bling">';
                                    if (!empty($list)) {
                                        echo 'Error Details <br>';
                                        echo '==============';
                                        echo "<pre>";
                                        print_r($list);
                                        echo "</pre>";
                                    }
                                    echo '<span id="terminal__prompt--cursor"></span>  
                                    
                                    </div>        
                                </section>      
                                </div>    
                                </main>
                                                            </body>
                                                        </html>';

        


        
 

    break;



    case 'test_csv':
        $cn = 0;
       // if(isset($_SESSION['uploaded']))
        {
           
            $row = 1;
            $uploaded = $_SESSION['uploaded'];
                
            if (($handle = fopen(APP_URL."/storage/temp/".$uploaded, "r")) !== FALSE)
             {
                $csv = array_map('str_getcsv', file(APP_URL."/storage/temp/".$uploaded, FILE_IGNORE_NEW_LINES));
                echo "<pre>";
                print_r($csv); 
                echo "</pre>";
                die();
                $count = 0;
                for($i=1; $i<count($csv); $i = $i+$count)
                {
                    
    
                        $delivery_id = $csv[$i][0];
                        $d = ORM::for_table('sys_invoices')->where('cn', $delivery_id)->find_one();
                        if($d)
                        {
                             
                            $count++;
                            continue;
                        }
                  
                        $email = $csv[$i][3];
                        //check customer exist or not 
                        if($email=="")
                        {
                            continue;
                        }
                        
                        $d = ORM::for_table('crm_accounts')->where('email', $email)->find_one();
                        if($d)
                        {
                            
                            $delivery['userid'] = $d->id;
                            $delivery['account'] = $d->account;
                            
                        }
                        else
                         {
                     
                            $account = $csv[$i][1];
                            if($account=="")
                            {
                                $account = $email;
                            }
    
                          
                            $type = 'Customer';
                            
                          //  $company = _post('company');
                    
                    
                            $company = '';
                            $cid = 0;
                    
                         
                            $username = $email;
                            $phone = $csv[$i][2];
                           
                         //   $currency = _post('currency');
                    
                            $address = $csv[$i][5];
                            //$city = _post('city');
                            //$state = _post('state');
                            $zip = $csv[$i][7];
                            $country = "Sinagapore";
                            $code = predict_next_serial($config,'customer');
                            
                            
                    
                            
                    
                    
                           
                    
                            $currency = '0';
                    
                            $tags = '';
                    
                    
                            $msg = '';
                            
                            //check if tag is already exisit
                            
                            
                            
                                
                            
                            //check account is already exist
                            //        $chk = ORM::for_table('crm_accounts')->where('account',$account)->find_one();
                            //        if($chk){
                            //            $msg .= 'Account already exist <br>';
                            //        }
                            
                                    
                    
                          
                    
                    
                            if($phone != '')
                            {
                    
                                $f = ORM::for_table('crm_accounts')->where('phone',$phone)->find_one();
                    
                                if($f)
                                {
                                    //$msg .= $_L['Phone number already exist'].' <br>';
                                }
                            }
                                
                            $gid = 0;
                            $gname = '';
                            $password =  "123456789";
                            $cpassword = "123456789";
                    
                            $u_password = '';
                    
                           
                            if($password != '')
                            {
                    
                    
                    
                                if($password != $cpassword)
                                {
                                    //$msg .= 'Passwords does not match'. '<br>';
                                }
                    
                    
                                $u_password = $password;
                                $password = Password::_crypt($password);
                    
                    
                            }
                    
                    
                    
                       
                    
                    
                            if($msg == '')
                            {
                    
                                Tags::save($tags,'Contacts');
                    
                                $data = array();
                    
                                $data['created_at'] = date('Y-m-d H:i:s');
                                $data['updated_at'] = date('Y-m-d H:i:s');
                    
                              //  $type = _post('type');
                              $owners = getOwners($user);
                                foreach ($owners as $owner)
                                    {
                                     if($owner->id == $user->id)
                                         $owner_id = $owner->id ;
                                    }
                                   
                               
                    
                                $d = ORM::for_table('crm_accounts')->create();
                    
                                $d->account = $account;
                                $d->email = $email;
                                $d->phone = $phone;
                                $d->address = $address;
                                $d->city = "";
                                $d->zip = $zip;
                                $d->state = "";
                                $d->country = $country;
                                $d->tags = Arr::arr_to_str($tags);
                    
                                //others
                                $d->fname = '';
                                $d->lname = '';
                                $d->company = $company;
                                $d->jobtitle = '';
                                $d->cid = $cid;
                                $d->o = $owner_id;
                                $d->balance = '0.00';
                                $d->status = 'Active';
                                $d->notes = '';
                                $d->password = $password;
                                $d->token = '';
                                $d->ts = '';
                                $d->img = '';
                                $d->web = '';
                                $d->facebook = '';
                                $d->google = '';
                                $d->linkedin = '';
                    
                                // v 4.2
                    
                                $d->gname = $gname;
                                $d->gid = $gid;
                    
                                // build 4550
                    
                                $d->currency = $currency;
                    
                                //
                    
                                $d->created_at = $data['created_at'];
                    
                                $d->type = $type;
                    
                                //
                    
                                $d->business_number = "";//"_post('business_number');
                    
                                $d->fax = "";//_post('fax');
                    
                                $drive = time().Ib_Str::random_string(12);
                    
                                $d->drive = $drive;
                    
                                $d->code = $code;
                    
                                //
                    
                                $d->secondary_email = "";//$secondary_email;
    
    
    
    
                                $api_key = GOOGLE_API;
                                $country_code = 'SG';
                
                                if($zip!="")
                                {
                                    
                                $place  = urlencode($zip);
                                $urlPart = 'components=postal_code:'.$place.'|country:'.$country_code;
    
                                }
                                else if($address!="")
                                {
                                  //  $add = $billing_address_1.$billing_city;
                                    $place  = urlencode($add);
    
                                    $urlPart = 'address='.$place.'&components=country:'.$country_code;
                                    
                                } 
                                else 
                                {
                                  //
                                
    
                                }
               
                                $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'];
                                
    
                                $d->lat = $latitude;
                                $d->lon = $longitude;
                            
                                }
    
                                
    
                    
                                //
                                // if(isset($_POST['lat']) &&  isset($_POST['lon']))
                                // {
                                //     $d->lat = _post('lat');
                                //     $d->lon = _Post('lon');
                                //  }
                                
                                $d->o = $user->id;
                                    
                               $d->save();
                    
                               //print_r(array('username' => $username,'password' => _post('password'),'baseurl' => APP_URL, 'clients_client_id' => $config['client_id'], 'role' => 'Client'));
                               $delivery['userid'] = $d->id;
                               $delivery['account'] = $d->account;
                              
                                $cid = $d->id();
                    
                                if (CRM_TYPE == "SAAS")
                                {
                                    $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' => $email,'password' => _post('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);die();
                    
                                if($type == 'Supplier')
                                {
                                    update_option('supplier_code_current_number',current_number_would_be($code));
                                }
                                else {
                                    update_option('customer_code_current_number',current_number_would_be($code));
                                }
                    
                                _log($_L['New Contact Added'].' '.$account.' [CID: '.$cid.']','Admin',$user->id);
                    
                             
                    
                                Event::trigger('contacts/add-post/_on_finished');
                    
                                // send welcome email if needed
                    
                                /*$send_client_signup_email = _post('send_client_signup_email');
                    
                    
                                if(($email != '') && ($send_client_signup_email == 'Yes') && ($u_password != '')){
                    
                                    $email_data = array();
                                    $email_data['account'] = $account;
                                    $email_data['company'] = $company;
                                    $email_data['password'] = $u_password;
                                    $email_data['email'] = $email;
                    
                                    $send_email = Ib_Email::send_client_welcome_email($email_data);
                    
                    
                    
                                }*/
                    
                    
                    
                                // Create Drive if this feature is enabled
                    
                    
                                if($config['client_drive'] == '1'){
                    
                                    if (!file_exists('storage/drive/customers/'.$drive.'/storage')) {
                                        mkdir('storage/drive/customers/'.$drive.'/storage',0777,true);
                                    }
                    
                                }
                    
                    
                    
                    
                                //
                    
                              //  echo $cid;
                    
                    
                    
                            }
                            else
                            {
                                //echo $msg;
                            }
                        }
                        
    
                        //check customer exist or not 
    
    
                        
                        $delivery['cn'] = $csv[$i][0];
                      
                       // $delivery['invoicenum'] = 
                        $delivery['date'] = $csv[$i][4];
                        $delivery['priority'] = $csv[$i][6];
    
                        if( isset($csv[$i+1][0]))
                        {   
                            
                            if( $csv[$i][0] == $csv[$i+1][0]  && $csv[$i+1][10] != "")
                            {
                              
    
    
                                $notes = "";
                                $invoice_id = "";
                                $invoice = false;
    
                                if($invoice_id != '')
                                {
                                    $invoice = Invoice::find($invoice_id);
                                }
    
                                $app->emit('invoices_add_post');
    
                                $cid = _post('cid');
    
                                $currency = 0;
                                $currency_symbol = $config['currency_code'];
                                $currency_rate = 1.0000;
    
                                $amount ="0";
    
    
       
                                $idate = $csv[$i][4];
                                $its = strtotime($idate);
                                
                                $duedate = 'days30';
                                //$dd = $duedate;
                                $dd = date('Y-m-d', strtotime('+30 days', $its));
                                    
                                $repeat = "0";
                                $nd = $idate;
                                
                                    $r = '0';
    
        
        
                                $business_number ="";
        
                               // $qty = $_POST['qty'];
                                //$item_number = $_POST['item_code'];   
                                $taxed = false;
        
                                $sTotal = '0';
                                $taxTotal = '0';
                            
                                $a = array();
        
        
                                $taxval = '0.00';
                                $taxname = '';
                                $taxrate = '0.00';
        
        
        
                                $taxed_amount = 0.00;
                                $lamount = 0.00;
        
                                $discounts =0.0;
        
                                $discount_type = "p";
        
                                $total_discount = 0.00;
        
                                $sub_total_without_discount = 0.00;
        
        
                                $line_total = 0.0;
        
                            
                                $lamount = 0.0;
                    
                                $lTaxVal = 0.0;
                    
                                $taxed_amount = 0.0;
                                $sub_total_without_discount  = 0.0;
        
                                $invoicenum = $config['invoice_code_prefix'];
                                $cn =  $delivery['cn'];
        
                                $fTotal = 0.0;
                                $discount_value = '0.00';
                                $status = 'Unpaid';
                                $receipt_number = "";
        
                                $title = "";
                        
                                $datetime = date("Y-m-d H:i:s");
                                
                                $invoice = new Invoice;
        
                                $vtoken = _raid(10);
                                $ptoken = _raid(10);
                    
                                $invoice->vtoken = $vtoken;
                                $invoice->ptoken = $ptoken;
        
                                $invoice->userid = $d->id;
                                $invoice->account = $delivery['account'] ;
                            
                                $invoice->date = $idate;
                                $invoice->duedate = $dd;
                            
                                $invoice->datepaid = $datetime;
                                $invoice->subtotal = $sub_total_without_discount;
                                $invoice->discount_type = $discount_type;
                                $invoice->discount_value = $discount_value;
                                $invoice->discount = $total_discount;
                                $invoice->total = $fTotal;
                                $invoice->tax = $taxed_amount;
                                $invoice->taxname = '';
                                $invoice->taxrate = 0.00;
                                $invoice->status = $status;
                                $invoice->notes = $notes;
                                $invoice->r = $r;
                                $invoice->nd = $nd;
                                $invoice->aid = $user->id;
        
                            
                                $invoice->show_quantity_as = "Qty";
                                $invoice->invoicenum = $invoicenum;
                                $invoice->cn = $cn;
                                $invoice->tax2 = '0.00';
                                $invoice->taxrate2 = '0.00';
                                $invoice->paymentmethod = '';
                                $invoice->currency = $currency;
                                $invoice->currency_symbol = "";//$currency_symbol;
                                $invoice->currency_rate = $currency_rate;
                                $invoice->currency_iso_code = "SGD";
                                $invoice->receipt_number = $receipt_number;
                                $invoice->title = $title;
                
                                $invoice->c1 = 1;
                                $invoice->c2 = $csv[$i][4];
                                $invoice->c3 = $d->lat;
                                $invoice->c4 = $d->lon;
                                if(isset($csv[$i][18]) && $csv[$i][18]!="")
                                {
                                    $driver_details= ORM::for_table('sys_users')->where('username', $csv[$i][18])->find_array();
                                    if(!empty($driver_details))
                                    {
                                        $invoice->c5 = $driver_details[0]['id'] ;
                                        $invoice->delivery_status = "Assigned";
                                    }
                                    else 
                                    {
                                        $invoice->c5 ='';
                                    }
                                }
                                else
                                {
                                    $invoice->c5 = '';
                                }
                                $invoice->sort_order = $csv[$i][6];
                                $invoice->save(); 
                                
                
                                    $count= 0;
                                for($j=$i+1; $j<count($csv); $j++)
                                {
                                    if($csv[$i][0]==$csv[$j][0])
                                    {
                                        $count++;
                                    $invoiceitems = ORM::for_table('sys_invoiceitems')->create();
                                    $invoiceitems->invoiceid = $invoice->id;
                                    $invoiceitems->userid = $invoice->userid;
                                    $invoiceitems->relid = 0;
                                    $invoiceitems->type = "";
                                    $invoiceitems->description = $csv[$j][10];
                                    $invoiceitems->qty = $csv[$j][9];
                                    $invoiceitems->amount = 0.0;
                                    $invoiceitems->taxed = 0;
                                    $invoiceitems->tax_rate = 0.000;
                                    $invoiceitems->taxamount = 0.00;
                                   //  $invoiceitems->tax1 = 0.0000;it
                                    //$invoiceitems->tax2 = 0.0000;
                                    $invoiceitems->notes = "";
                                    $invoiceitems->itemcode = $csv[$j][15];
                                    $invoiceitems->discount_type = 'p';
        
                                    $invoiceitems->paymentmethod = "";
                                    $invoiceitems->duedate = $dd;
                                    $invoiceitems->brand = $csv[$j][11];
                                    $invoiceitems->model_no = $csv[$j][12];
                                    
                                    $invoiceitems->serial_no = $csv[$j][13];
                                    $invoiceitems->tag_no = $csv[$j][14];
                                    $invoiceitems->part_no = $csv[$j][15];
                                    $invoiceitems->range_item = $csv[$j][16];
                                    $invoiceitems->remarks = $csv[$j][17];
                                    $invoiceitems->save();
        
                                    
                                    }
                                    else
                                    {
                                        $count++;
                                    break;
                                    }
                                }
    
            
    
    
    
    
    
    
    
    
    
    
    
    
                            }
                        }
                        
    
                        
                        
                        
                        
    
                  
                }
             
            
                fclose($handle);
            }





             _msglog('s',$cn.' Delivery Challan Imported');

        }
       // else 
        {
            _msglog('e','An Error Occurred while uploading the CSV file');

        }


    break;

     case 'deliverychallan-deleteall':
        if(!has_access($user->roleid,'settings','edit')){
  
            permissionDenied();

        }

        //print_r($_POST["did"]); die();
        if(isset($_POST['did']))
        {
            
                foreach($_POST['did'] as $did)
                {
                    $x = ORM::for_table('sys_invoiceitems')->where('invoiceid', $did)->delete_many();
                    $x = ORM::for_table('sys_invoices')->where('id', $did)->delete_many();
                   
                }
        }
        else
        {
           // $x = ORM::for_table('sys_invoiceitems')->delete_many();
            //$x = ORM::for_table('sys_invoices')->delete_many();
             r2(U . 'crmdelivery/deliverychallan-list', 'e', 'Please select the delivey chellans');


        }

        

        
         r2(U . 'crmdelivery/deliverychallan-list', 's', 'Delivery Challand Deleted Successfully');

        break;

        case 'activate-driver':


            $id  = $routes['2'];
            //prevent self delete
            if(($user->id) == $id){
                r2(U . 'settings/users', 'e', 'Sorry You can\'t delete yourself');
            }
            $d = ORM::for_table('sys_users')->find_one($id);
            if($d){
    
                if($user->id != $d->id){
    
                    if(!has_access($user->roleid,'settings','delete')){
    
                        permissionDenied();
    
                    }
    
                }
                $d->status = "Active";
    
                $d->save();
                r2(U . 'crmdelivery/driver-list', 's', 'User Activated Successfully');
            }
            else{
                r2(U . 'crmdelivery/driver-list', 'e', $_L['Account_Not_Found']);
            }
    
            break;
            case 'deactivate-driver':


                $id  = $routes['2'];
                //prevent self delete
                if(($user->id) == $id){
                    r2(U . 'settings/users', 'e', 'Sorry You can\'t delete yourself');
                }
                $d = ORM::for_table('sys_users')->find_one($id);
                if($d){
        
                    if($user->id != $d->id){
        
                        if(!has_access($user->roleid,'settings','delete')){
        
                            permissionDenied();
        
                        }
        
                    }
                    $d->status = "Inactive";
        
                    $d->save();
                    r2(U . 'crmdelivery/driver-list', 's', 'User Deactivated Successfully');
                }
                else{
                    r2(U . 'crmdelivery/driver-list', 'e', $_L['Account_Not_Found']);
                }
        
                break;   
                
       case 'change_password';
       
        $ui->assign('_application_menu', 'dashboard');

        $ui->assign('languages',IBilling_I18n::get_languages());



        $id  = $routes['2'];
        $d = ORM::for_table('sys_users')->find_one($id);
        if($d){

            if($user->id != $d->id){

                if(!has_access($user->roleid,'settings','edit')){

                    permissionDenied();

                }

            }

            $ui->assign('xheader', Asset::css(array('imgcrop/assets/css/croppic')));


            $ui->assign('xfooter', Asset::js(array('imgcrop/croppic')));

            $ui->assign('d',$d);



            // find user language

            if($d->language == ''){
                $selected_language = $config['language'];
            }
            else{
                $selected_language = $d->language;
            }

            $departments = TicketDepartment::all();

            $roles = M::factory('Models_Role')->find_array();
            $ui->assign('roles',$roles);

            $assigned_departments = Relation::where('type','staff_departments')->where('source_id',$id)->get()->keyBy('target_id')->all();



            view('crmchangepassword',[
                'selected_language' => $selected_language,
                'departments' => $departments,
                'assigned_departments' => $assigned_departments
            ]);

        }
        else{
            r2(U . 'crmdelivery/driver-list', 'e', $_L['Account_Not_Found']);
        }


       break;
       case 'change_password_post':
          
            $id = $_POST['id'];
            $password =  _post('password');
            $cpassword = _post('cpassword');
            $msg = "";     

            if($password != ''){
    
                if($password != $cpassword){
                    $msg .= 'Passwords does not match'. '<br>';
                }
            }
            
            $driver = User::find($id);

            if($driver){

                if($user->id != $driver->id){

                    if(!has_access($user->roleid,'settings','edit')){

                        permissionDenied();

                    }

                }

            }
            else{
                $msg .= 'Username Not Found'. '<br>';
            }
            
            if($msg == ''){
                if($password != ''){
                    $password = Password::_crypt($password);
                    $driver->password = $password;
                }
        
                $curl = curl_init();

                curl_setopt_array($curl, array(
                CURLOPT_URL => BACKOFFICEAPI_URL."users/changePassword",
                
                  //CURLOPT_URL => 'http://crm.akstechsolution.com/index.php/users/changePassword',
                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' => $driver->username,'baseurl' => APP_URL, 'new_password' => $cpassword),
                ));

                $response = curl_exec($curl);

                curl_close($curl);
                $json = json_decode($response, true);
                              
             
                $driver->save();

            
                 r2(U . 'crmdelivery/change_password/'.$id, 's', 'User Updated Successfully');
            }
            else{
                
                r2(U . 'crmdelivery/change_password/'.$id, 'e', $msg);
            }
                
            
                   



        break;

    
    
  
      default:
          echo 'action not defined';
  }
  