<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Brand;
use App\SalesOrder;
use App\SalesOrderAddress;
use DB;

class IvrController extends Controller
{
    public function gcc_ivr(Request $request){
        $is_ivr = false;
    

	if ($request["payment_gateway_names"][0] == "Cash on Delivery (COD)") {

//        if($request['gateway'] == 'Cash on Delivery (COD)'){
            $is_ivr = true;
        }
    
        $phone_number = str_replace(' ', '', $request['billing_address']['phone']);

        // if($is_ivr){
        //     $your_url = 'https://ivr.eocean.us/cgi-bin/TAV_outgoing/outbound.cgi?order_id='.str_replace('CC', '', $request->name).'&Amount='.str_replace('.00', '', $request->total_price).'&username=TAV&password=TAVCall@EoIVR&caller_id='.$phone_number.'&brand_id=3';
        //     $ch = curl_init($your_url);
        //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        //     $output = curl_exec($ch);

        //     DB::table('ivr_logs')->insert([
        //         'brand_id' => 4,
        //         'order_id' => $request->id,
        //         'order_name' => str_replace('CC', '', $request->name),
        //         'customer_phone' => $phone_number,
        //         'total_price' => $request->total_price,
        //         'recording_response' => 'Response Pending',
        //         'recording_response' => $output,
        //         'dialed' => 1,
        //         'created_at' => now(),
        //     ]);

        //     $customer = $request['billing_address']['first_name'];

        //     $message = 'Dear '.$customer.'! Thank you for the online order '.$request->name.'. Your order should be delivered in 2 to 3 working days. For any assistance, please contact us at 021-111-221-331';

        //     $ch = curl_init('https://bsms.its.com.pk/api.php?key=65ca30444c19598018c2914042bc4e9d&receiver='.$phone_number.'&sender=CottonCandy&msgdata='.urlencode($message));
        //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //     $result = curl_exec($ch);
        //     curl_close($ch);
        // }
    }

    public function yves_ivr(Request $request){
        $is_ivr = false;
    
        if($request['gateway'] == 'Cash on Delivery (COD)'){
            $is_ivr = true;
        }
    
        $phone_number = str_replace(' ', '', $request['billing_address']['phone']);

        // if($is_ivr){    
        //     $your_url = 'https://ivr.eocean.us/cgi-bin/TAV_outgoing/outbound.cgi?order_id='.str_replace('YR', '', $request->name).'&Amount='.str_replace('.00', '', $request->total_price).'&username=TAV&password=TAVCall@EoIVR&caller_id='.$phone_number.'&brand_id=1';
        //     $ch = curl_init($your_url);
        //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        //     $output = curl_exec($ch);

        //     DB::table('ivr_logs')->insert([
        //         'brand_id' => 3,
        //         'order_id' => $request->id,
        //         'order_name' => str_replace('YR', '', $request->name),
        //         'customer_phone' => $phone_number,
        //         'total_price' => $request->total_price,
        //         'recording_response' => 'Response Pending',
        //         'recording_response' => $output,
        //         'dialed' => 1,
        //         'created_at' => now(),
        //         'updated_at' => now()
        //     ]);

        //     $customer = $request['billing_address']['first_name'];

        //     $message = 'Dear '.$customer.'! Thank you for the online order '.$request->name.'. Your order should be delivered in 2 to 3 working days. For any assistance, please contact us at 021-111-221-331';

        //     $ch = curl_init('https://bsms.its.com.pk/api.php?key=bc98e3987b7b8f78e6257ca5fb48d331&receiver='.$phone_number.'&sender=Yves%20Rocher&msgdata='.urlencode($message));
        //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //     $result = curl_exec($ch);
        //     curl_close($ch);
        // }
    }

    public function sf_ivr(Request $request){
        $is_ivr = false;
    
        if($request['gateway'] == 'Cash on Delivery (COD)'){
           $is_ivr = true;
        }
    
        $phone_number = str_replace(' ', '', $request['billing_address']['phone']);

        // if($is_ivr){    
        //     $your_url = 'https://ivr.eocean.us/cgi-bin/TAV_outgoing/outbound.cgi?order_id='.str_replace('SF', '', $request->name).'&Amount='.str_replace('.00', '', $request->total_price).'&username=TAV&password=TAVCall@EoIVR&caller_id='.$phone_number.'&brand_id=2';
        //     $ch = curl_init($your_url);
        //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        //     $output = curl_exec($ch);

        //     DB::table('ivr_logs')->insert([
        //         'brand_id' => 2,
        //         'order_id' => $request->id,
        //         'order_name' => str_replace('SF', '', $request->name),
        //         'customer_phone' => $phone_number,
        //         'total_price' => $request->total_price,
        //         'recording_response' => 'Response Pending',
        //         'recording_response' => $output,
        //         'dialed' => 1,
        //         'created_at' => now(),
        //         'updated_at' => now()
        //     ]);

        //     $customer = $request['billing_address']['first_name'];

        //     $message = 'Dear '.$customer.'! Thank you for the online order '.$request->name.'. Your order should be delivered in 2 to 3 working days. For any assistance, please contact us at 021-111-221-331';

        //     $ch = curl_init('https://bsms.its.com.pk/api.php?key=4c9848c340e68d6cbbda0c0dad771fd8&receiver='.$phone_number.'&sender=SUPERFEET&msgdata='.urlencode($message));
        //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //     $result = curl_exec($ch);
        //     curl_close($ch);
        // }
    }

    public function ivr_queue(){
        // $logs = DB::table('ivr_logs')->where('dialed', 0)->limit(5)->get();
        $logs = [];

        foreach($logs as $log){
            sleep(1);

            $order_time = strtotime($log->created_at)+(60*2);
            $current_time = strtotime(now());
    
            $brand = Brand::where('id', $log->brand_id)->first();

            $shopify_order = shopify_get_request($brand->api_target.'/admin/api/2021-04/orders/'.$log->order_id.'.json');
            $shopify_order = json_decode($shopify_order, true);

            if($shopify_order['order']['tags'] == ''){

                if($current_time >= $order_time){
                    $brand_ids = array(3 => 1, 2 => 2, 4 => 3);
        
                    $your_url = 'https://ivr.eocean.us/cgi-bin/TAV_outgoing/outbound.cgi?order_id='.$log->order_name.'&Amount='.str_replace('.00', '', $log->total_price).'&username=TAV&password=TAVCall@EoIVR&caller_id='.$log->customer_phone.'&brand_id='.$brand_ids[$log->brand_id];
                    $ch = curl_init($your_url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                    $output = curl_exec($ch);
            
                    if($output == '(200)OK'){
                        DB::table('ivr_logs')->where('id', $log->id)->update([
                            'recording_response' => $output,
                            'dialed' => 1,
                            'updated_at' => now()
                        ]);
                    }
                }

            }else{
                DB::table('ivr_logs')->where('id', $log->id)->update([
                    'recording_response' => 'SMS Verified or CS Verified',
                    'dialed' => 2,
                    'updated_at' => now()
                ]);
            }
        }
    }

    public function ivr_tav_return(Request $request){
        // if($request->input('brand_id') == 3){
        //     $counter = $request->input('order_id');
        //     $total = 8;
        //     $order_id = '';

        //     for($i=0; $i<$total-strlen($counter); $i++){
        //         $order_id .= 0; 
        //     }
            
        //     $order_id .= $request->input('order_id');

        //     try {
        //         $client = new \GuzzleHttp\Client();
        
        //         $response = $client->request('GET', 'https://www.getcottoncandy.com/commonhelper/index/update_call_status?order_id='.$order_id.'&response_code='.$request->input('recorded_response'));
        
        //         $result = $response->getBody()->getContents();
        //     }catch(\Exception $e) {
        //         $result = $e->getMessage();
        //     }
            
        //     DB::table('ivr_logs')->insert([
        //         'brand_id' => 4,
        //         'order_id' => $order_id,
        //         'recording_response' => $request->input('recorded_response'),
        //         'response' => json_encode($request->all()),
        //         'created_at' => now(),
        //         'updated_at' => now()
        //     ]);

        //     die;
        // }
        
        $brand_ids = array(1 => 3, 2 => 2, 3 => 4);
        
        $brand = Brand::where('id', $brand_ids[$request->input('brand_id')])->first();

        if(!$brand){
            return response()->json('Invalid Brand ID');
        }

        $fetch_row = DB::table('ivr_logs')->where([['order_name', $request->input('order_id')], ['brand_id', $brand->id]])->first();
        
        if(!$fetch_row){
            return response()->json('Invalid Order ID');
        }

        $shopify_order = shopify_get_request($brand->api_target.'/admin/api/2021-04/orders/'.$fetch_row->order_id.'.json');
        $shopify_order = json_decode($shopify_order, true);

        if($shopify_order['order']['tags'] == ''){
            $update_row = DB::table('ivr_logs')->where('id', $fetch_row->id)->update(array(
                'recording_response' => $request->input('recorded_response'),
                'response' => json_encode($request->all()),
                'response_date' => now()
            ));
    
            if($request->input('recorded_response') == '1'){
                shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "tags": "IVR Verified" } }');
                shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "note": "Order marked Verified via IVR" } }');
            }else{
                shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "tags": "IVR Canceled" } }');
                shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "note": "Order marked Canceled via IVR" } }');
                // shopify_create_transactions($brand->api_target, $fetch_row->order_id, '{ "transaction": { "kind": "void" } }');
                // shopify_cancel_order($brand->api_target, $fetch_row->order_id, '{ "restock": "true" }');
            }
            
            return response()->json('Order marked IVR Verified');
        }

        return response()->json('Order could not be marked IVR Verified');
    }

    public function order_sms_on_ivr_verified_yv(){
        $orders = SalesOrder::whereIn('tags', ['Verified', 'IVR Verified'])->where('brand_id', 3)->whereNull('sms_sent')->limit(20)->get();

        $apis = [
            3 => ['key' => 'bc98e3987b7b8f78e6257ca5fb48d331', 'mask' => 'Yves%20Rocher']
        ];

        
        foreach($orders as $order){
            $api = $apis[$order->brand_id];

            $address = SalesOrderAddress::where([['sales_order_id', $order->id], ['type', 'billing']])->first();
            $phone_number = str_replace(' ', '', $address->phone);
            // $phone_number = '03357496112';
            $message = 'Thank you for the online order '.$order->order_name.'. Your order should be delivered in 2 to 3 working days. For any assistance, please contact us at 021-38899742.';
            
            $ch = curl_init('http://bsms.its.com.pk/api.php?key='.$api['key'].'&receiver='.$phone_number.'&sender='.$api['mask'].'&msgdata='.urlencode($message));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);
            curl_close($ch);

            SalesOrder::where('id', $order->id)->update([
                'sms_sent' => 1
            ]);
        }
    }

    public function order_sms_on_ivr_verified_sf(){
        $orders = SalesOrder::whereIn('tags', ['Verified', 'IVR Verified'])->where('brand_id', 2)->whereNull('sms_sent')->limit(20)->get();

        $apis = [
            2 => ['key' => '4c9848c340e68d6cbbda0c0dad771fd8', 'mask' => 'SUPERFEET'],
        ];

        
        foreach($orders as $order){
            $api = $apis[$order->brand_id];

            $address = SalesOrderAddress::where([['sales_order_id', $order->id], ['type', 'billing']])->first();
            $phone_number = str_replace(' ', '', $address->phone);
            // $phone_number = '03357496112';
            $message = 'Thank you for the online order '.$order->order_name.'. Your order should be delivered in 2 to 3 working days. For any assistance, please contact us at 021-38899741.';
            
            $ch = curl_init('http://bsms.its.com.pk/api.php?key='.$api['key'].'&receiver='.$phone_number.'&sender='.$api['mask'].'&msgdata='.urlencode($message));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);
            curl_close($ch);

            SalesOrder::where('id', $order->id)->update([
                'sms_sent' => 1
            ]);
        }
    }

    public function kayseria_ivr(Request $request){
        $employee_codes = ['EmpTestingCoupon'];

        $coupon_code = null;

        foreach($request['discount_codes'] as $counpon){
            if(in_array($counpon['code'], $employee_codes)){
                $coupon_code = $counpon['code'];
           }
        }

        if(!is_null($coupon_code)){
            $price = $request['total_price'];

            if($price > 30000){
               die;
            }
        }

        $is_ivr = false;
    
	  if ($request["payment_gateway_names"][0] == "Cash on Delivery (COD)") {
       // if($request['gateway'] == 'Cash on Delivery (COD)'){
            $is_ivr = true;
        }

        if($is_ivr){

            $phone_number = str_replace(' ', '', $request['billing_address']['phone']);

            $phone_number = str_replace('+92', '0', $phone_number);

            $perum = array(
                'data1='.$request->id,
                'data2='.$request->total_price,
                'username=intellidesk',
                'password=intellidesk',
                'dialer_id=6',
                'destination='.$phone_number
            );
    
    $your_url = 'https://lck.contegris.com:4002/api/ringDialer/add?'.implode("&",$perum);

		


	$ch = curl_init($your_url);
           curl_setopt($ch, CURLOPT_∑
∑RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
           curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            $output = curl_exec($ch);
            curl_close($ch);



            DB::table('ivr_logs')->insert([
                'brand_id' => 15,
                'order_id' => $request->id,
                'order_name' => $request->name,
                'customer_phone' => $phone_number,
                'total_price' => $request->total_price,
                'recording_response' => $output,
                'dialed' => 1,
                'created_at' => now(),
                'updated_at' => now()
            ]);

        }
    }

    public function ivr_kayseria_return(Request $request){
        $brand = Brand::where('id', 15)->first();

        if(!$brand){
            return response()->json('Invalid Brand ID');
        }

        $fetch_row = DB::table('ivr_logs')->where([['order_id', $request->input('ordernum')], ['brand_id', 15]])->first();

        $update_row = DB::table('ivr_logs')->where('id', $fetch_row->id)->update(array(
            'recording_response' => $request->input('recording_response'),
            'response' => json_encode($request->all()),
            'response_date' => now()
        ));

        $message = '';

        if($request->input('recording_response') == '1'){
            shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "tags": "IVR Verified" } }');
            shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "note": "Order marked Verified via IVR" } }');
            $message = 'Order marked IVR Verified';
        }else{
            shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "tags": "IVR Canceled" } }');
            shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "note": "Order marked Canceled via IVR" } }');
            $message = 'Order marked IVR Canceled';
            // shopify_create_transactions($brand->api_target, $fetch_row->order_id, '{ "transaction": { "kind": "void" } }');
            // shopify_cancel_order($brand->api_target, $fetch_row->order_id, '{ "restock": "true" }');
        }

        return response()->json($message);
    }



 public function ismailfarid_ivr(Request $request){

        $employee_codes = ['EmpTestingCoupon'];

        $coupon_code = null;
    
        foreach($request['discount_codes'] as $counpon){
            if(in_array($counpon['code'], $employee_codes)){
                $coupon_code = $counpon['code'];
            }
        }

        if(!is_null($coupon_code)){
            $price = $request['total_price'];

            if($price > 30000){
               die;
            }
        }

        $is_ivr = false;
    
        if($request['gateway'] == 'Cash on Delivery (COD)'){
            $is_ivr = true;
        }

        if($is_ivr){

            $phone_number = str_replace(' ', '', $request['billing_address']['phone']);

            $phone_number = str_replace('+92', '0', $phone_number);

            $perum = array(
                'data1='.$request->id,
                'data2='.$request->total_price,
		 'data3='.$request->name,       
		'username=ismail.fareed',
                'password=ismail@fareed44496',
                'dialer_id=1',
                'destination='.$phone_number
            );
    

      
 $your_url = 'https://ismailfarid.contegris.com/api/ringDialer/add?'.implode("&",$perum);
        //  $your_url = 'https://lck.contegris.com:4002/api/ringDialer/add?'.implode("&",$perum);
           
            
            $ch = curl_init($your_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            $output = curl_exec($ch);
            curl_close($ch);
    
            DB::table('ivr_logs')->insert([
                'brand_id' => 24,
                'order_id' => $request->id,
                'order_name' => $request->name,
                'customer_phone' => $phone_number,
                'total_price' => $request->total_price,
                'recording_response' => $output,
                'dialed' => 1,
                'created_at' => now(),
                'updated_at' => now()
            ]);

        }
 }




public function ivr_ismailfarid_return(Request $request){
        $brand = Brand::where('id', 24)->first();

        if(!$brand){
            return response()->json('Invalid Brand ID');
        }

        $fetch_row = DB::table('ivr_logs')->where([['order_id', $request->input('ordernum')], ['brand_id', 24]])->first();

        $update_row = DB::table('ivr_logs')->where('id', $fetch_row->id)->update(array(
            'recording_response' => $request->input('recording_response'),
            'response' => json_encode($request->all()),
            'response_date' => now()
        ));

        $message = '';

        if($request->input('recording_response') == '1'){
            shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "tags": "IVR Verified" } }');
            shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "note": "Order marked Verified via IVR" } }');
            $message = 'Order marked IVR Verified';
	}
	// else{
elseif ($request->input('recording_response') == '2') {
            shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "tags": "IVR Canceled" } }');
            shopify_update_order($brand->api_target, $fetch_row->order_id, '{ "order": { "id": "'.$fetch_row->order_id.'", "note": "Order marked Canceled via IVR" } }');
            $message = 'Order marked IVR Canceled.';
            // shopify_create_transactions($brand->api_target, $fetch_row->order_id, '{ "transaction": { "kind": "void" } }');
            // shopify_cancel_order($brand->api_target, $fetch_row->order_id, '{ "restock": "true" }');
    $sales_orders = DB::table('sales_orders')
            ->where([['order_id', $request->input('ordernum')], ['brand_id', 24]])
            ->update(['tags' => 'Canceled']);

}

        return response()->json($message);
    }






}
