<?php
// require __DIR__ . '/vendor/autoload.php';

// use Automattic\WooCommerce\Client;

/*
|--------------------------------------------------------------------------
| Controller for plugin
|--------------------------------------------------------------------------
|
*/

$action = route(2,'list');
_auth();
$ui->assign('_application_menu', 'bluesnap');
$ui->assign('_title', 'WooCommerce '.'- '. $config['CompanyName']);
$user = User::_info();
$ui->assign('user', $user);

$integrations = Integration::where('type','woocommerce')->get();

$options = '';

$api_url = '';
$api_key = '';
$api_secret = '';

foreach ($integrations as $opt_i) {
    $selected = '';
    if($opt_i->is_default == 1)
    {
        $selected = ' selected';
        $api_url = $opt_i->url;
        $api_key = $opt_i->key;
        $api_secret = $opt_i->secret;

    }
    $options .= '<option value="'.$opt_i->id.'" '.$selected.'>'.$opt_i->name.'</option>';
}

$integrations_count = $integrations->count();

$ui->assign('integrations',$integrations);
$ui->assign('integrations_count',$integrations_count);

$client = false;


if($api_url != '')
{
  



   //$client = new GuzzleHttp\Client(['auth' => [$api_key, $api_secret]]);



    // //print_r($api_url) ; die();
     //$credentials = base64_encode($api_key.':'.$api_secret);
     
    $client = new GuzzleHttp\Client([
        'base_uri' => $api_url.'/wp-json/wc/v2/',
        'auth' => [
            $api_key,
            $api_secret
            ],
          
           
                'query' => [
                   'consumer_key' => $api_key,
                   'consumer_secret' => $api_secret,
                
             ]
        //'verify' => false
    ]);

//     $client = new GuzzleHttp\Client(['auth' => [$api_key, $api_secret]]);
// $res = $client->request('GET',  $api_url.'/wp-json/wc/v2/' );
//$res->getStatusCode();
//$response = $res->getBody();
//print_r($res->getStatusCode()); die();


// //     // Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
// $ch = curl_init();

// //curl_setopt($ch, CURLOPT_URL, 'https://www.sglifestylezone.com'.'/wp-json/wc/v2/customers');
// curl_setopt($ch, CURLOPT_URL, 'https://www.sglifestylezone.com/wp-json/wc/v2/customers?consumer_key=ck_dc6ff2ae2e459cf7ce248b4355a62f1b675e58b6&consumer_secret=cs_9f60d39ba010490417576713a82f9aaeaeb24160');

// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// //curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

// //curl_setopt($ch, CURLOPT_USERPWD, 'ck_2e56ca85dc311e42b11b75410b7223e66ae8da6b' . ':' . 'cs_b797a469eb86081d19477d1344c9a9b817c87d32');

// $result = curl_exec($ch);
// print_r($result); die();
// if (curl_errno($ch)) {
//     echo 'Error:' . curl_error($ch);
// }
// curl_close($ch);
  


}

$welcome_msg = '';

$menu_items = [
    [
        'Dashboard',
        U . 'wcsuite/app/dashboard/',
        'fa fa-tachometer',
        'woocommerce_dashboard'
    ],
    [
        'Customers',
        U . 'wcsuite/app/customers/',
        'icon-users',
        'woocommerce_customers'
    ],
    [
        'Orders',
        U . 'wcsuite/app/orders/',
        'fa fa-server',
        'woocommerce_orders'
    ],
    [
        'Products',
        U . 'wcsuite/app/products/',
        'fa fa-cube',
        'woocommerce_products'
    ],
    [
        'Settings',
        U . 'wcsuite/app/settings/',
        'fa fa-cog',
        'woocommerce_settings'
    ]
];
$menu = array(
    'title' => '<a href="' . U . 'wcsuite/app/dashboard/"><img style="height: 30px;" src="' . APP_URL . '/apps/wcsuite/views/img/logo-woocommerce.png"> </a>',
    'panel_body_1' => '<div class="form-group">
    <select class="form-control" id="chooseStore" name="chooseStore" onchange="if (this.value) window.location.href=\''.U.'wcsuite/app/make-default-integration/\' + this.value">
      <option value="">Choose Store</option>
      '.$options.'
    </select>
  </div>', // Optional
    'items' => $menu_items,
//    'panel_body_2' => '', // Optional
  //  'panel_body_3' => '<a class="md-btn md-btn-primary md-btn-block envato_add_account">Add Store</a>'

    // Optional

);

$view = new View();


switch ($action)
{
    case 'dashboard':


        view('app_wrapper',[
            '_include' => 'dashboard',
            'menu' => $view->buildMenuListGroup($menu, 'woocommerce_dashboard')->getHtml()

        ]);

        break;

    case 'customers':


        view('app_wrapper',[
            '_include' => 'customers',
            'menu' => $view->buildMenuListGroup($menu, 'woocommerce_customers')->getHtml()
        ]);



        break;


    case 'orders':

        view('app_wrapper',[
            '_include' => 'orders',
            'menu' => $view->buildMenuListGroup($menu, 'woocommerce_orders')->getHtml()
        ]);


        break;


    case 'products':

        view('app_wrapper',[
            '_include' => 'products',
            'menu' => $view->buildMenuListGroup($menu, 'woocommerce_products')->getHtml()
        ]);


        break;


    case 'settings':


        $hooks = [
            [
                'name' => 'Customer created',
                'topic' => 'Customer created',
                'delivery_url' => U.'wcsuite/app/webhook/customer-created'
            ],
            [
                'name' => 'Customer updated',
                'topic' => 'Customer updated',
                'delivery_url' => U.'wcsuite/app/webhook/customer-updated'
            ],
            [
                'name' => 'Customer deleted',
                'topic' => 'Customer deleted',
                'delivery_url' => U.'wcsuite/app/webhook/customer-deleted'
            ],
            [
                'name' => 'Order created',
                'topic' => 'Order created',
                'delivery_url' => U.'wcsuite/app/webhook/order-created'
            ],
            [
                'name' => 'Order updated',
                'topic' => 'Order updated',
                'delivery_url' => U.'wcsuite/app/webhook/order-updated'
            ],
            [
                'name' => 'Order deleted',
                'topic' => 'Order deleted',
                'delivery_url' => U.'wcsuite/app/webhook/order-deleted'
            ],
            [
                'name' => 'Product created',
                'topic' => 'Product created',
                'delivery_url' => U.'wcsuite/app/webhook/product-created'
            ],
            [
                'name' => 'Product updated',
                'topic' => 'Product updated',
                'delivery_url' => U.'wcsuitee/app/webhook/product-updated'
            ],
            [
                'name' => 'Product deleted',
                'topic' => 'Product deleted',
                'delivery_url' => U.'wcsuite/app/webhook/product-deleted'
            ]
        ];

        view('app_wrapper',[
            '_include' => 'settings',
            'menu' => $view->buildMenuListGroup($menu, 'woocommerce_settings')->getHtml(),
            'hooks' => $hooks
        ]);


        break;


    case 'add-store':

        view('app_wrapper',[
            '_include' => 'integration',
            'menu' => $view->buildMenuListGroup($menu, 'woocommerce_settings')->getHtml(),
            'integration' => false
        ]);

        break;


    case 'save-integration':

        $name = _post('name');
        $url = _post('url');
        $key = _post('key');
        $secret = _post('secret');
        $id = _post('id');

        if($name == '' || $url == '' || $key == '' || $secret == '')
        {
            r2(U.'wcsuite/app/add-store','e','All fields are required.');
        }

        $integration = false;
        if($id != '' || $id != 0)
        {
            $integration = Integration::find($id);
            $message = 'Integration updated successfully';
        }
        if(!$integration)
        {
            $integration = new Integration;
            $integration->type = 'woocommerce';
            if($integrations_count == 0)
            {
                $integration->is_default = 1;
            }
            else{
                $integration->is_default = 0;
            }
            $message = 'Integration added successfully';
        }


        $integration->name = $name;
        $integration->url = $url;
        $integration->key = $key;
        $integration->secret = $secret;

        $integration->save();


        r2(U.'wcsuite/app/settings','s',$message);

        break;

    case 'make-default-integration':

        $id = route(3);

        $integration = false;
        if($id != '' || $id != '0'){
            $integration = Integration::find($id);
        }


        if($integration)
        {
            Integration::where('type','woocommerce')->update([
                'is_default' => 0
            ]);

            $integration->is_default = 1;
            $integration->save();

            r2(U.'wcsuite/app/settings','s','Updated successfully');
        }

        break;


    case 'edit-integration':

        $id = route(3);

        $integration = Integration::find($id);

        if($integration)
        {
            view('app_wrapper',[
                '_include' => 'integration',
                'menu' => $view->buildMenuListGroup($menu, 'woocommerce_settings')->getHtml(),
                'integration' => $integration
            ]);
        }

        break;


    case 'delete-integration':

        $id = route(3);

        $integration = Integration::find($id);

        if($integration)
        {
            $integration->delete();
        }

        r2(U.'wcsuite/app/settings','s','Deleted successfully');

        break;


    case 'x_orders':

        if($client)
        {
            $response = $client->get('orders', [

            ]);

            $body = (string) $response->getBody();



            $data = json_decode($body);
        }
        else{
            $data = false;
        }

        view('content_only',[
            '_include' => 'x_orders',
            'orders' => $data
        ]);

        break;


    case 'x_customers':
        

        if($client)
        {


            $response = $client->get('customers', [

            ]);



            $body = (string) $response->getBody();



                $data = json_decode($body);
    /*        echo "<pre>";  
            print_r($data);
            echo "</pre>";
            die();*/
        }
        else{
            $data = false;
        }


        view('content_only',[
            '_include' => 'x_customers',
            'customers' => $data
        ]);


        break;


    case 'x_products':


        if($client)
        {
            $response = $client->get('products', [

            ]);

            $body = (string) $response->getBody();



            $data = json_decode($body);
        }
        else{
            $data = false;
        }



        view('content_only',[
            '_include' => 'x_products',
            'products' => $data
        ]);


        break;

    case 'x_dashboard':

        $total_order_amount = 0.00;
        $total_customers = 0;

        if($client)
        {
            $response = $client->get('orders', [

            ]);

            $body = (string) $response->getBody();
            $data = json_decode($body);

           // dd($data);

            $collection = collect($data);

            $total_order_amount = $collection->sum('total');

            $response = $client->get('customers', [

            ]);

            $body = (string) $response->getBody();

            $data = json_decode($body);

            $collection = collect($data);

            $total_customers = $collection->count();

        }

        view('content_only',[
            '_include' => 'x_dashboard',
            'total_order_amount' => $total_order_amount,
            'total_customers' => $total_customers
        ]);

        break;


    case 'view-customer':

        $id = route(3);

        if($client)
        {
            $response = $client->get('customers/'.$id, [

            ]);

            $body = (string) $response->getBody();



            $data = json_decode($body);

            view('app_wrapper',[
                '_include' => 'customer',
                'menu' => $view->buildMenuListGroup($menu, 'woocommerce_customers')->getHtml(),
                'data' => $data
            ]);
        }


        break;


        case 'sync-transaction';
        $id = route(3);
        if($client)
        {
            $response = $client->get('orders/'.$id, [

            ]);

            $body = (string) $response->getBody();



            $data = json_decode($body);

            $account =  ORM::for_table('sys_accounts')->find_array();
            if(count($account))
            {
                $u = ORM::for_table('crm_accounts')->where('email',$data->billing->email)->find_one();
                 

                   

                $account_id = $account[0]['id'];
                $account_name = $account[0]['account'];
                $d = ORM::for_table('sys_transactions')->create();
                if(!$u){
                    $d->payerid = "0";
                }
                else {
                    
                    $d->payerid = $u->id;
                    $d->payer = $u->account;
                }

                $d->account = $account_name;
                $d->account_id = $account_id;
                $d->type = 'Income';
                ;//$payerid;
                $d->tags = '';//Arr::arr_to_str($tags);
                $d->amount = $data->total;
                $d->category = "E-commerse Website";// $cat;
                $d->cat_id = '0';//$cat_id;
                $d->method = 'Cash';//$pmethod;
                $d->ref = '';
                $d->description = "Order No: # ". $data->id." payment ";

                // Build 4560

                $d->attachments = '';
                $d->date = date('Y-m-d');
                $d->dr = '0.00';
                $d->cr = $data->total;;
                $d->bal = 0.00;

                // others
                $d->payer = '';
                $d->payee = '';
                $d->payeeid = '0';
                $d->status = 'Cleared';
                $d->tax = '0.00';
                $d->iid = 0;
                $d->aid = $user->id;

                $d->vid = _raid(8);

//                $d->status = $status;

                $d->currency_iso_code = $data->currency;

                $d->updated_at = date('Y-m-d H:i:s');

                //

                //$d->code = "";
                $d->staff_id = 0;

                
                $d->company_id = 0;

               
                $d->save();

                //print_r($account_id);
                r2(U.'wcsuite/app/view-order/'.$id,'s',"Payment Updated");

            }
            else
            {
                r2(U.'wcsuite/app/view-order/'.$id,'e',"Please create a transaction account");
    
            }

        }
       

        
        break;
    case 'sync-invoice':
        $id = route(3);
        if($client)
        {
            $response = $client->get('orders/'.$id, [

            ]);

            $body = (string) $response->getBody();



            $data = json_decode($body);
                // echo "<pre>";
                // print_r($data);
                // echo "</pre>";
                // die();
            $invoice_id = $id;

            $invoice = false;
        
            if($invoice_id != '')
            {
                //$invoice = Invoice::find($invoice_id);
                $invoice =  ORM::for_table('sys_invoices')->where('wp_orderid',$invoice_id)->find_array();

            }


            if(!$invoice)
            {
        
                    $u = ORM::for_table('crm_accounts')->where('email',$data->billing->email)->find_one();
                //  print_r($u); die();

                    if(!$u){
                        $cid = '';
                    }
                    else {
                    $cid = $u->id; 
                    }
                // print_r($cid); die();

                    $msg = '';
                    
                    if ($cid == '') {
                        $msg.= 'Please Synchronize Customer first'  . ' <br /> ';
                    }
                
                    $notes = $data->customer_note;
                
                    $show_quantity_as = "Qty";
                
                
                    if(!isset($u->lat) ||  !isset($u->lon) ){
                    $msg.= "Latitude and Longitude is empty, please update you address  <br/>";
                    }
                    else{
                        $lat = $u->lat;
                        $lon  = $u->lon;
                    } 
                
                    // find currency
                        $currency_id = $data->currency;

                        $currency = 0;
                        $currency_symbol = $config['currency_code'];
                        $currency_rate = 1.0000;
                    
                
                
                        $amount = $data->total;
                    
                    if (count($data->line_items)==0) {
                        $msg.= $_L['at_least_one_item_required'] . ' <br /> ';
                    }
                    $idate = $data->date_created;// _post('idate');
                    $its = strtotime($idate);
                    
                
                
                
                
                    $dd = $idate;
                    $duedate = 'due_on_receipt';
                    
                
                    $repeat = '0';
                    $nd = $idate;
                    if ($repeat == '0') {
                        $r = '0';
                    }
                    
                
                    if ($msg == '') {
        
                $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 ($data->total_tax!=0.0) {
                    $taxed = $data->total_tax;
                }
                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;
        
        
        
        
        
                $invoicenum = $data->id;// _post('invoicenum');
                $cn = _post('cn');
                $fTotal = $data->total;
        
        
             //   $discount_amount = _post('discount_amount');
                $discount_type = 'p';//_post('discount_type');
                $discount_value = '0.00';
        
        
        
              //  $fTotal = $fTotal + $taxed_amount;
        
        
              $status = 'Unpaid';

              $receipt_number = "";
              $title = "";


        
        
        
                $datetime = date("Y-m-d H:i:s");
        
                $total_discount    = $data->discount_total;  
                $taxed_amount = $data->total_tax;       
                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 = $data->total;//$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 = 1;//$user->id;
                $invoice->is_same_state = $is_same_state;
                $invoice->show_quantity_as = $show_quantity_as;
                $invoice->invoicenum = "WP-";
                $invoice->cn = $invoicenum;
                $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 = "0";
                $invoice->show_in_invoice = 1;
                $invoice->wp_orderid = $invoicenum;


                //$invoice->c2 = $deliverydate;//$_POST['delivery_date'];
                $invoice->c3 = $lat;//$_POST['lat'];
                $invoice->c4 = $lon;//$_POST['lon'];
                // if($_POST['driver']==''){
                //   $invoice->c5 = '';
                  
                // }else
                // {
                //   $invoice->c5 = $_POST['driver'];
                //   $invoice->delivery_status = "Assigned";
                 
                // }
                
                
                
                
        
                
                $invoice->save();
        
        
        
                $invoiceid = $invoice->id;
                /*
                $description = $_POST['desc'];
        
                    
        
                if(isset($_POST['tax_code']))
                {
                    $tax_code = $_POST['tax_code'];
                }
                else{
                    $tax_code = [];
                }
        
        
                $i = '0';
             */
                if($invoice)
                {
                    InvoiceItem::where('invoiceid',$invoice->id)->delete();
                }
        
                foreach($data->line_items as $item) {
        
        
                    //$samount = $a[$i];
        
                  //  $samount = Finance::amount_fix($samount);
        
                 //   $samount = createFromCurrency($samount,$currency_id);
        
                    if ($item->name == '' || $item->subtotal == '0.00') {
                        $i++;
                        continue;
                    }
        
                   
        
                    $d = ORM::for_table('sys_invoiceitems')->create();
                    $d->invoiceid = $invoiceid;
                    $d->userid = $cid;
                    $d->description = $item->name;
                    $d->qty = $item->quantity;
                    $d->amount = $item->subtotal;
                    $d->total = $item->total;
        
        
        
                    if($item->tax_class==''){
                        $tax_rate = 0.00;
                        $d->taxed = '0';
                    }
                    else{
                        $tax_rate =$item->subtotal_tax;
                        $d->taxed = '1';
                    }
        
                    $d->tax_rate = $tax_rate; //$item->subtotal_tax;
        
                    //$item_taxed_amount = round(($tax_rate*($sqty*$samount))/100,2);
        
        
                    $d->type = '';
                    $d->relid = '0';
                    $d->itemcode = $item->id;
                    $d->taxamount = $item->total_tax;
                    $d->duedate = date('Y-m-d');
                    $d->paymentmethod = '';
                    $d->notes = '';
        
        
                    $d->discount_type = "p";
                    $d->discount_amount = 0.0;
        
                 
                        $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++;
                }
        
             
        
            
        
          
                r2(U.'wcsuite/app/view-order/'.$invoice_id,'s','Invoice Created');
                }
                else
                {

                   // r2(U.'wcsuite/app/view-order/'.$invoice_id,'s','Delivery Created');

                    r2(U.'wcsuite/app/view-order/'.$invoice_id,'e',$msg);
                }


        
           
            }
            else 
            {
               // print_r($invoice[0]['delivery_status']);die();
                // if($invoice[0]['delivery_status']=="Unassigned"){
                 $d = ORM::for_table('sys_invoices')->where('wp_orderid', $invoice[0]['wp_orderid'])->find_one();
                    
                      $d->show_in_invoice = 1;
                     $d->save();
                   
                //     r2(U.'wcsuite/app/view-order/'.$invoice_id,'s','Delivery Updated');

                // }
                r2(U.'wcsuite/app/view-order/'.$invoice_id,'s', 'Invoice  Created Successfully' );

                //r2(U.'wcsuite/app/customers','s','Sync successful. '.$i.' customers added.');

               // echo "Delivery Already Updated";
            }
        }



    break;
    case 'sync-order':
        $id = route(3);
        $delivery_date = route(4);
        if($client)
        {
            $response = $client->get('orders/'.$id, [

            ]);

            $body = (string) $response->getBody();



            $data = json_decode($body);
            //$email = $data->billing->email;


            
            

                $invoice_id = $id;

                $invoice = false;
            
                if($invoice_id != '')
                {
                    //$invoice = Invoice::find($invoice_id);
                    $invoice =  ORM::for_table('sys_invoices')->where('wp_orderid',$invoice_id)->find_array();

                }
            
              //  $app->emit('invoices_add_post');
            
               // $cid = $data->cid;
            
                // find user with cid
                $format = 'Y-m-d';
                $d = DateTime::createFromFormat($format, $delivery_date);
                // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
                if ($d && $d->format($format) === $delivery_date)
                {
                    $deliverydate = $delivery_date;
                }
                else{
                $deliverydate = new DateTime('tomorrow');
                $deliverydate =   $deliverydate->format('Y-m-d');
                }
                if(!$invoice)
                {
            
                        $u = ORM::for_table('crm_accounts')->where('email',$data->billing->email)->find_one();
                    //  print_r($u); die();

                        if(!$u){
                            $cid = '';
                        }
                        else {
                        $cid = $u->id; 
                        }
                    // print_r($cid); die();

                        $msg = '';
                        
                        if ($cid == '') {
                            $msg.= 'Please Synchronize Customer first'  . ' <br /> ';
                        }
                    
                        $notes = $data->customer_note;
                    
                        $show_quantity_as = "Qty";
                    
                    
                        if(!isset($u->lat) ||  !isset($u->lon) ){
                        $msg.= "Latitude and Longitude is empty, please update you address  <br/>";
                        }
                        else{
                            $lat = $u->lat;
                            $lon  = $u->lon;
                        } 
                    
                        // find currency
                            $currency_id = $data->currency;

                            $currency = 0;
                            $currency_symbol = $config['currency_code'];
                            $currency_rate = 1.0000;
                        
                    
                    
                            $amount = $data->total;
                        
                        if (count($data->line_items)==0) {
                            $msg.= $_L['at_least_one_item_required'] . ' <br /> ';
                        }
                        $idate = $data->date_created;// _post('idate');
                        $its = strtotime($idate);
                        
                    
                    
                    
                    
                        $dd = $idate;
                        $duedate = 'due_on_receipt';
                        
                    
                        $repeat = '0';
                        $nd = $idate;
                        if ($repeat == '0') {
                            $r = '0';
                        }
                        
                    
                        if ($msg == '') {
            
                    $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 ($data->total_tax!=0.0) {
                        $taxed = $data->total_tax;
                    }
                    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($data->line_items as $item) {
            
                    //   //  $samount = createFromCurrency($samount,$currency_id);
                    //    $samount] = $samount->subtotal;
                    //     /* @since v 2.0 */
            
                    //     $sqty = $samount->quantity;
                    //   //  $sqty = Finance::amount_fix($sqty);
                    //     //$sqty = createFromCurrency($sqty,$currency_id);
            
                    //     $lTaxRate = $samount->total_tax//$taxed[$i];
            
                    //    // $lTaxRate = Finance::amount_fix($lTaxRate);
            
                    //     $line_discount = 0;//$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 = $data->id;// _post('invoicenum');
                    $cn = _post('cn');
                    $fTotal = $data->total;
            
            
                 //   $discount_amount = _post('discount_amount');
                    $discount_type = 'p';//_post('discount_type');
                    $discount_value = '0.00';
            
            
            
                  //  $fTotal = $fTotal + $taxed_amount;
            
            
                  $status = 'Unpaid';

                  $receipt_number = "";
                  $title = "";


            
            
            
                    $datetime = date("Y-m-d H:i:s");
            
                    $total_discount    = $data->discount_total;  
                    $taxed_amount = $data->total_tax;       
                    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 = 1;//$user->id;
                    $invoice->is_same_state = $is_same_state;
                    $invoice->show_quantity_as = $show_quantity_as;
                    $invoice->invoicenum = "WP-";
                    $invoice->cn = $invoicenum;
                    $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->wp_orderid = $invoicenum;
                    
                    $invoice->c1 = 1;
                   
                    $invoice->c2 = $delivery_date;//$_POST['delivery_date'];
                    $invoice->c3 = $lat;//$_POST['lat'];
                    $invoice->c4 = $lon;//$_POST['lon'];
                    // if($_POST['driver']==''){
                    //   $invoice->c5 = '';
                      
                    // }else
                    // {
                    //   $invoice->c5 = $_POST['driver'];
                    //   $invoice->delivery_status = "Assigned";
                     
                    // }
                    
                    
                    
                    
            
                    
                    $invoice->save();
            
            
            
                    $invoiceid = $invoice->id;
                    /*
                    $description = $_POST['desc'];
            
                        
            
                    if(isset($_POST['tax_code']))
                    {
                        $tax_code = $_POST['tax_code'];
                    }
                    else{
                        $tax_code = [];
                    }
            
            
                    $i = '0';
                 */
                    if($invoice)
                    {
                        InvoiceItem::where('invoiceid',$invoice->id)->delete();
                    }
            
                    foreach($data->line_items as $item) {
            
            
                        //$samount = $a[$i];
            
                      //  $samount = Finance::amount_fix($samount);
            
                     //   $samount = createFromCurrency($samount,$currency_id);
            
                        if ($item->name == '' || $item->subtotal == '0.00') {
                            $i++;
                            continue;
                        }
            
                       
            
                        $d = ORM::for_table('sys_invoiceitems')->create();
                        $d->invoiceid = $invoiceid;
                        $d->userid = $cid;
                        $d->description = $item->name;
                        $d->qty = $item->quantity;
                        $d->amount = $item->subtotal;
                        $d->total = $item->total;
            
            
            
                        if($item->tax_class==''){
                            $tax_rate = 0.00;
                            $d->taxed = '0';
                        }
                        else{
                            $tax_rate =$item->subtotal_tax;
                            $d->taxed = '1';
                        }
            
                        $d->tax_rate = $tax_rate; //$item->subtotal_tax;
            
                        //$item_taxed_amount = round(($tax_rate*($sqty*$samount))/100,2);
            
            
                        $d->type = '';
                        $d->relid = '0';
                        $d->itemcode = $item->id;
                        $d->taxamount = $item->total_tax;
                        $d->duedate = date('Y-m-d');
                        $d->paymentmethod = '';
                        $d->notes = '';
            
            
                        $d->discount_type = "p";
                        $d->discount_amount = 0.0;
            
                     
                            $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++;
                    }
            
                 
            
                
            
              
                    r2(U.'wcsuite/app/view-order/'.$invoice_id,'s','Delivery Created');
                    }
                    else
                    {

                       // r2(U.'wcsuite/app/view-order/'.$invoice_id,'s','Delivery Created');

                        r2(U.'wcsuite/app/view-order/'.$invoice_id,'e',$msg);
                    }


            
               
                }
                else 
                {
                   // print_r($invoice[0]['delivery_status']);die();
                    if($invoice[0]['delivery_status']=="Unassigned"){
                        $d = ORM::for_table('sys_invoices')->where('wp_orderid', $invoice[0]['wp_orderid'])->find_one();
                        $d->c2 = $deliverydate;
                        $d->c1 = "1";
                        $d->save();
                       
                        r2(U.'wcsuite/app/view-order/'.$invoice_id,'s','Delivery Updated');

                    }
                    r2(U.'wcsuite/app/view-order/'.$invoice_id,'e', 'Delivery Already Updated');

                    //r2(U.'wcsuite/app/customers','s','Sync successful. '.$i.' customers added.');

                   // echo "Delivery Already Updated";
                }

   
           
          
        }


    break;

    case 'view-order':

        $id = route(3);

        if($client)
        {
            $response = $client->get('orders/'.$id, [

            ]);

            $body = (string) $response->getBody();



            $data = json_decode($body);
            $email = $data->billing->email;


            $curl = curl_init();

            curl_setopt_array($curl, array(
            CURLOPT_URL => BACKOFFICEAPI_URL."users/check_user_exist",
            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,'role' => 'Client'),
            ));

            $response = curl_exec($curl);

            curl_close($curl);
            $json = json_decode($response, true);
       //  print_r($json['status']); die();
            if($json['status']=="failed"){
                $data->issync = 0;
            }
            else {
                $data->issync = 1;
            }
            
            $check = Contact::where('email',$email)->first();
            if($check)
            {
                if($check->lat=="" || $check->lon=="")
                {
                    $data->candelivery = 0;
                }
                else
                {
                    $data->candelivery = 1;


                }
                $data->customer_id = $check->id;

            }
            else
            {
                $data->issync = 0;
            }

               $invoice =  ORM::for_table('sys_invoices')->where('wp_orderid',$id)->find_array();
                if(count($invoice))
                {
                
                $data->delivery_id = $invoice[0]['id'];  
                $data->invoice_id = $invoice[0]['id'];  
                    if($invoice[0]['c1']==1)
                    {
                        $data->deliveryExist = 1;
                    }   
                    else
                    {
                        $data->deliveryExist = 0;

                    }

                    if($invoice[0]['show_in_invoice']==1)
                    {
                        $data->invoiceExist = 1;
                    }   
                    else
                    {
                        $data->invoiceExist = 0;

                    }
                }
                else
                {
                    $data->deliveryExist = 0;
                    $data->invoiceExist = 0;

                }  
               
            //  echo "<pre>";  
            //     print_r($data);
            //  echo "</pre>";
            //  die();
            view('app_wrapper',[
                '_include' => 'order',
                'menu' => $view->buildMenuListGroup($menu, 'woocommerce_orders')->getHtml(),
                'data' => $data
            ]);
        }


        break;

    case 'sync-customers':


        if($client)
        {

            $response = $client->get('customers', [

            ]);

            $body = (string) $response->getBody();

            $customers = json_decode($body);

            $i = 0;
            // echo "<pre>";
            // print_r($customers);die();
            // echo "<pre>";
            $password = "123456789";
            foreach ($customers as $customer)
            {   


                
                $account = '';
                if(isset($customer->first_name))
                {
                    $account = $customer->first_name;
                }

                if(isset($customer->last_name))
                {
                    $account .= ' '.$customer->last_name;
                }



                $contact = new Contact;
                $contact->account = $account;

                if(isset($customer->email))
                {
                    // check if exist
                    $check = Contact::where('email',$customer->email)
                        ->first();

                    if($check)
                    {
                        continue;
                    }

                    $contact->email = $customer->email;
                }
                else{
                    continue;
                }

                if(isset($customer->billing->postcode))
                {
                    $billing_postcode = $customer->billing->postcode;
                    $contact->zip = $customer->billing->postcode;

                    
                }
                if(isset($customer->billing->address_1))
                {
                    $billing_address_1 = $customer->billing->address_1;
                    $contact->address = $customer->billing->address_1;

                }
                if(isset($customer->billing->address_2))
                {
                    $billing_address_2 = $customer->billing->address_2;
                }
                if(isset($customer->billing->city))
                {
                    $billing_city = $customer->billing->city;
                    $contact->city = $customer->shipping->city;

                }
                if(isset($customer->billing->country))
                {
                    $billing_country_code = $customer->billing->country;
                    $contact->country = $customer->billing->country;

                }

                if(isset($customer->billing->state))
                {
                    $billing_state = $customer->billing->state;

                    $contact->state = $customer->billing->state;

                }

                if(isset($customer->billing->phone))
                {
                    $billing_phone = $customer->billing->phone;
                    $contact->phone = $customer->billing->phone;
                }


                /*
                if(isset($customer->shipping->postcode))
                {
                    $shipping_postcode = $customer->shipping->postcode;
                    $contact->zip = $customer->shipping->postcode;

                }
                if(isset($customer->shipping->address_1))
                {
                    $shipping_address_1 = $customer->shipping->address_1;
                    $contact->address = $customer->shipping->address_1;

                }
                if(isset($customer->shipping->address_2))
                {
                    $shipping_address_2 = $customer->shipping->address_2;
                }
                if(isset($customer->shipping->city))
                {
                    $shipping_city = $customer->shipping->city;
                    $contact->city = $customer->shipping->city;

                }
                if(isset($customer->shipping->state))
                {
                    $shipping_state = $customer->shipping->state;
                    $contact->state = $customer->shipping->state;

                }

                if(isset($customer->shipping->country))
                {
                    $shipping_country_code = $customer->shipping->country;
                    $contact->country = $customer->shipping->country;

                }
                if(isset($customer->shipping->phone))
                {
                    $shipping_phone = $customer->shipping->phone;
                    $contact->phone = $customer->shipping->phone;
                }
                    */

                /*if(isset($customer->billing->address_1))
                {
                    $contact->address = $customer->billing->address_1;
                }

                if(isset($customer->billing->city))
                {
                    $contact->city = $customer->billing->city;
                }

                if(isset($customer->billing->postcode))
                {
                    $contact->zip = $customer->billing->postcode;
                }

                if(isset($customer->billing->state))
                {
                    $contact->state = $customer->billing->state;
                }

                if(isset($customer->billing->country))
                {
                    $contact->country = $customer->billing->country;
                }

                if(isset($customer->billing->phone))
                {
                    $contact->phone = $customer->billing->phone;
                }
                */



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

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

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

                   // echo json_encode($arr);
                   continue;

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

                
                $json = file_get_contents($q);
                $details = json_decode($json, TRUE);
                // $arr = array('latitude' => '', 'longitude' => '', 'error' => 1, 'msg'=>'lat- '.$details['results'][0]['geometry']['location']['lng']);

                // echo json_encode($arr);


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

               // echo json_encode($arr);

               $contact->lat = $latitude;
               $contact->lon = $longitude;


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

               $contact->password = $password;
               

                $contact->save();


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

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


                $i++;


            }

            r2(U.'wcsuite/app/customers','s','Sync successful. '.$i.' customers added.');
        }
        else{
            r2(U.'wcsuite/app/customers','e','Failed.');
        }





        break;


    case 'webhook-generate-secret':

        $secret = _raid(20);

        update_option('woocommerce_webhooks_secret',$secret);

        r2(U.'wcsuite/app/settings/','s','Successfully updated.');

        break;


}