<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\User;
use App\Models\Subcategory;
use DataTables;
use App\Models\Orders;
use App\Models\OrdersData;
use App\Models\UserAddress;
use App\Models\Setting;
use App\Models\Token;
use App\Models\PaymentGateway;
use Session;
use Auth;
use Hash;
use Mail;
use DB;
use Carbon\Carbon;
class OrderControllers extends Controller
{
    
    public function show_order(){
        return view("admin.orders.default");
    }

    public function show_OrdersTable(){
         $order =Orders::all();
         return DataTables::of($order)
            ->editColumn('id', function ($order) {
                return $order->id;
            })
            ->editColumn('name', function ($order) {
                return User::find($order->user_id)?User::find($order->user_id)->name:'';
            })
            ->editColumn('datetime', function ($order) {
                return $order->date." ".$order->time;
            })
            ->editColumn('payment_method', function ($order) {
                return $order->payment_method;
            })
            ->editColumn('paid_amount', function ($order) {
                return number_format($order->final_total,2,'.','');
            })
            ->editColumn('more', function ($order) {
                return $order->id;
            })
            ->editColumn('print', function ($order) {
                return $order->id;
            })
            ->editColumn('status', function ($order) {
                if($order->status=='1'){
                    // return "Pending";
                    return  __('message.Pending');
                }
                if($order->status=='2'){
                    // return "Accepted";
                    return __('message.Accepted');
                }
                if($order->status=='3'){
                    // return "Rejected";
                    return __('message.Rejected');
                }
                if($order->status=='4'){
                    // return "Refunded";
                    return __('message.Refunded');
                }
                if($order->status=='5'){
                    // return "Sample collected";
                    return __('message.Sample collected');
                }
                if($order->status=='6'){
                    // return "Preparing Report";
                    return __('message.Preparing Report');
                }
                if($order->status=='7'){
                    // return "Complete";
                    return __('message.Complete');

                }
            })
            ->editColumn('action', function ($order) {
                $accept_labal=__('message.Accept');
                $Reject_labal=__('message.Reject');
                $sample_Collected_labal=__('message.Sample Collected');
                $refund_labal=__('message.Refund');
                $complete_labal=__('message.Complete');

                if($order->status=='1'){
                    $accept = url('change_order_status',array('id'=>$order->id,'status'=>2));
                    $reject = url('change_order_status',array('id'=>$order->id,'status'=>3));
                    return '<a   href="'.$accept.'" rel="tooltip"  class="btn btn-success" data-original-title="banner" style="margin-right: 10px;color: white !important;">'.$accept_labal.'</a><a href="javascript::void(0)" onclick="rejectorder('.$order->id.')" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#reject_order">'.$Reject_labal.'</a>';
                   
                }
                if($order->status=='2'){
                    $collected = url('change_order_status',array('id'=>$order->id,'status'=>5));
                    $reject = url('change_order_status',array('id'=>$order->id,'status'=>3));
                    return '<a  href="'.$collected.'" rel="tooltip"  class="btn btn-success" data-original-title="banner" style="margin-right: 10px;color: white !important;">'.$sample_Collected_labal.'</a><a href="javascript::void(0)" onclick="rejectorder('.$order->id.')" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#reject_order">'.$Reject_labal.'</a>';
                }
                if($order->status=='3'){
                    if($order->payment_method != "cod"){
                        $refund = url('change_order_status',array('id'=>$order->id,'status'=>4));
                        return '<a  href="'.$refund.'" rel="tooltip"  class="btn btn-danger" data-original-title="banner" style="margin-right: 10px;color: white !important;">'.$refund_labal.'</a>';
                    }
                    
                }
                if($order->status=='4'){ //refunded 
                    return "";
                }
                if($order->status=='5'){ // collected
                    $complete = url('change_order_status',array('id'=>$order->id,'status'=>7));
                    $reject = url('change_order_status',array('id'=>$order->id,'status'=>3));
                    return '<a href="javascript::void(0)" onclick="completeorder('.$order->id.')" class="btn btn-success mr-2" data-bs-toggle="modal" data-bs-target="#complete_order">'.$complete_labal.'</a><a href="javascript::void(0)" onclick="rejectorder('.$order->id.')" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#reject_order">'.$Reject_labal.'</a>';
                }else{
                     return "";
                }
            })         
            ->make(true);
    }

    public function getorderdetails($id){
        $data = Orders::with('useraddressdetails')->where("id",$id)->first();
        $address = UserAddress::find($data->sample_collection_address_id);
        if($address){
            $address = $address->address;
        }else{
            $address = "";
        }
        
        if($data){
            $data->orderdata = OrdersData::with("memberdetails")->where("order_id",$id)->get();
            $setting = Setting::find(1);
            $getcurrency = explode("-",$setting->currency);
            $userinfo = User::find($data->user_id);
            $userinfo->address = $address;
            $data1 = array("data"=>$data,"currency"=>$getcurrency[1],"setting"=>$setting,"userinfo"=>$userinfo);
            // echo"<pre>";
            // print_r(json_encode($data));
            // exit();
            return json_encode($data1);
        }
        return 0;
    }


    public function show_manager_order(){
        return view("manager.order.default");
    }

    public function show_manager_OrdersTable(){
      
         $order=DB::table('orders')
                 ->select('orders.id','orders.user_id','orders.sample_collection_address_id','orders.date','orders.time','orders.payment_method','orders.final_total','orders.status')
                 ->orderby('orders.id','DESC')
                 ->join('user_addresses', 'user_addresses.id', '=', 'orders.sample_collection_address_id')
                 ->where('user_addresses.city',Auth::user()->city)                 
                 ->get();
         return DataTables::of($order)
            ->editColumn('id', function ($order) {
                return $order->id;
            })
            ->editColumn('name', function ($order) {
                return User::find($order->user_id)?User::find($order->user_id)->name:'';
            })
            ->editColumn('address', function ($order) {
                $data = UserAddress::find($order->sample_collection_address_id);
                return isset($data->address)?$data->address:'';
            })
            ->editColumn('datetime', function ($order) {
                return $order->date." ".$order->time;
            })
            ->editColumn('payment_method', function ($order) {
                return $order->payment_method;
            })
            ->editColumn('paid_amount', function ($order) {
                return number_format($order->final_total,2,'.','');
            })
            ->editColumn('more', function ($order) {
                return $order->id;
            })
            ->editColumn('print', function ($order) {
                return $order->id;
            })
            ->editColumn('status', function ($order) {
                if($order->status=='1'){
                    // return "Pending";
                    return  __('message.Pending');
                }
                if($order->status=='2'){
                    // return "Accepted";
                    return  __('message.Accepted');
                }
                if($order->status=='3'){
                    // return "Rejected";
                    return  __('message.Rejected');
                }
                if($order->status=='4'){
                    // return "Refunded";
                    return  __('message.Refunded');
                }
                if($order->status=='5'){
                    // return "Preparing Report";
                    return  __('message.Preparing Report');
                }
                if($order->status=='7'){
                    // return "Complete";
                    return  __('message.Complete');
                }
            }) 
            ->editColumn('action', function ($order) {
                $accept_labal=__('message.Accept');
                $Reject_labal=__('message.Reject');
                $sample_Collected_labal=__('message.Sample Collected');
                $refund_labal=__('message.Refund');
                $complete_labal=__('message.Complete');

                if($order->status=='1'){
                    $accept = url('change_order_status',array('id'=>$order->id,'status'=>2));
                    $reject = url('change_order_status',array('id'=>$order->id,'status'=>3));
                    return '<a   href="'.$accept.'" rel="tooltip"  class="btn btn-success" data-original-title="banner" style="margin-right: 10px;color: white !important;">'.$accept_labal.'</a><a href="javascript::void(0)" onclick="rejectorder('.$order->id.')" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#reject_order">'.$Reject_labal.'</a>';
                   
                }
                if($order->status=='2'){
                    $collected = url('change_order_status',array('id'=>$order->id,'status'=>5));
                    $reject = url('change_order_status',array('id'=>$order->id,'status'=>3));
                    return '<a  href="'.$collected.'" rel="tooltip"  class="btn btn-success" data-original-title="banner" style="margin-right: 10px;color: white !important;">'.$sample_Collected_labal.'</a><a href="javascript::void(0)" onclick="rejectorder('.$order->id.')" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#reject_order">'.$Reject_labal.'</a>';
                }
                if($order->status=='3'){
                    if($order->payment_method != "cod"){
                        $refund = url('change_order_status',array('id'=>$order->id,'status'=>4));
                        return '<a  href="'.$refund.'" rel="tooltip"  class="btn btn-danger" data-original-title="banner" style="margin-right: 10px;color: white !important;">'.$refund_labal.'</a>';
                    }
                    
                }
                if($order->status=='4'){ //refunded 
                    return "";
                }
                if($order->status=='5'){ // collected
                    $complete = url('change_order_status',array('id'=>$order->id,'status'=>7));
                    $reject = url('change_order_status',array('id'=>$order->id,'status'=>3));
                    return '<a href="javascript::void(0)" onclick="completeorder('.$order->id.')" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#complete_order">'.$complete_labal.'</a><a href="javascript::void(0)" onclick="rejectorder('.$order->id.')" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#reject_order">'.$Reject_labal.'</a>';
                }
            })          
            ->make(true);
    }

    public function TodayManagerOrdersTable(){
         $date1 = date("Y-m-d",strtotime($this->getsitedate()));
         $order=DB::table('orders')
                 ->select('orders.id','orders.user_id','orders.sample_collection_address_id','orders.date','orders.time','orders.payment_method','orders.final_total','orders.status')
                 ->orderby('orders.id','DESC')
                 ->join('user_addresses', 'user_addresses.id', '=', 'orders.sample_collection_address_id')
                 ->where('user_addresses.city',Auth::user()->city) 
                 ->where("orders.date",$date1)                
                 ->get();
         return DataTables::of($order)
            ->editColumn('id', function ($order) {
                return $order->id;
            })
            ->editColumn('name', function ($order) {
                return User::find($order->user_id)?User::find($order->user_id)->name:'';
            })
            ->editColumn('address', function ($order) {
                $data = UserAddress::find($order->sample_collection_address_id);
                return $data->address;
            })
            ->editColumn('datetime', function ($order) {
                return $order->date." ".$order->time;
            })
            ->editColumn('payment_method', function ($order) {
                return $order->payment_method;
            })
            ->editColumn('paid_amount', function ($order) {
                return number_format($order->final_total,2,'.','');
            })
            ->editColumn('more', function ($order) {
                return $order->id;
            })
            ->editColumn('print', function ($order) {
                return $order->id;
            })
            ->editColumn('status', function ($order) {
                if($order->status=='1'){
                    // return "Pending";
                    return  __('message.Pending');
                }
                if($order->status=='2'){
                    // return "Accepted";
                    return  __('message.Accepted');
                }
                if($order->status=='3'){
                    // return "Rejected";
                    return  __('message.Rejected');
                }
                if($order->status=='4'){
                    // return "Refunded";
                    return  __('message.Refunded');
                }
                if($order->status=='5'){
                    // return "Preparing Report";
                    return  __('message.Preparing Report');
                }
                if($order->status=='7'){
                    // return "Complete";
                    return  __('message.Complete');
                }
            }) 
            ->editColumn('action', function ($order) {
                
                $accept_labal=__('message.Accept');
                $Reject_labal=__('message.Reject');
                $sample_Collected_labal=__('message.Sample Collected');
                $refund_labal=__('message.Refund');
                $complete_labal=__('message.Complete');

                if($order->status=='1'){
                    $accept = url('change_order_status',array('id'=>$order->id,'status'=>2));
                    $reject = url('change_order_status',array('id'=>$order->id,'status'=>3));
                    return '<a   href="'.$accept.'" rel="tooltip"  class="btn btn-success" data-original-title="banner" style="margin-right: 10px;color: white !important;">'.$accept_labal.'</a><a href="javascript::void(0)" onclick="rejectorder('.$order->id.')" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#reject_order">'.$Reject_labal.'</a>';
                   
                }
                if($order->status=='2'){
                    $collected = url('change_order_status',array('id'=>$order->id,'status'=>5));
                    $reject = url('change_order_status',array('id'=>$order->id,'status'=>3));
                    return '<a  href="'.$collected.'" rel="tooltip"  class="btn btn-success" data-original-title="banner" style="margin-right: 10px;color: white !important;">'.$sample_Collected_labal.'</a><a href="javascript::void(0)" onclick="rejectorder('.$order->id.')" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#reject_order">'.$Reject_labal.'</a>';
                }
                if($order->status=='3'){
                    if($order->payment_method != "cod"){
                        $refund = url('change_order_status',array('id'=>$order->id,'status'=>4));
                        return '<a  href="'.$refund.'" rel="tooltip"  class="btn btn-danger" data-original-title="banner" style="margin-right: 10px;color: white !important;">'.$refund_labal.'</a>';
                    }
                    
                }
                if($order->status=='4'){ //refunded 
                    return "";
                }
                if($order->status=='5'){ // collected
                    $complete = url('change_order_status',array('id'=>$order->id,'status'=>7));
                    $reject = url('change_order_status',array('id'=>$order->id,'status'=>3));
                    return '<a href="javascript::void(0)" onclick="completeorder('.$order->id.')" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#complete_order">'.$complete_labal.'</a><a href="javascript::void(0)" onclick="rejectorder('.$order->id.')" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#reject_order">'.$Reject_labal.'</a>';
                }
            })          
            ->make(true);
    }

    public function show_change_order_status($id,$status,Request $request){
      $data = Orders::find($id);
      
      $setting=Setting::find(1);
      $msg = "";
      if($status=='2'){
            // $msg = "Order Has Been Accepted";
            $msg = __('message.Order Has Been Accepted');
            $data->status = $status;
            $data->accept_datetime = $this->getsitedate();
            $data->save();
            if($data){
                $android = $this->send_notification_order_android($setting->android_server_key,$data->user_id,$msg,$data->id);
                $ios = $this->send_notification_order_ios($setting->ios_server_key,$data->user_id,$msg,$data->id);
            }
           
      }
      if($status=='3'){
            // $msg = "Order Has Been Rejected";
            $msg = __('message.Order Has Been Rejected');
            $data->status = $status;
            $data->reject_description = $request->get("reject_description");
            $data->reject_datetime = $this->getsitedate();
            $data->save(); 
            if($data){
                $android = $this->send_notification_order_android($setting->android_server_key,$data->user_id,$msg,$data->id);
                $ios = $this->send_notification_order_ios($setting->ios_server_key,$data->user_id,$msg,$data->id);
            }
      }
      if($status=='4'){
            // $msg = "Order Has Been Refunded";
            $msg = __('message.Order Has Been Refunded');
            $result = $this->refunded_order_amount($data->payment_method,$data->token,$data->final_total);
            if($result==1){
                $data->status = $status;
                $data->refund_datetime = $this->getsitedate();
                $data->save();  
                if($data){
                $android = $this->send_notification_order_android($setting->android_server_key,$data->user_id,$msg,$data->id);
                $ios = $this->send_notification_order_ios($setting->ios_server_key,$data->user_id,$msg,$data->id);
                }
            }else{
                   // Session::flash('message',"Something Getting Worng");
                   Session::flash('message',__('message.Something Getting Worng'));
                   Session::flash('alert-class', 'alert-danger');
                   return redirect()->back();
            }
              
                      
      }
       if($status=='5'){
          // $msg = "The sample has been collected successfully";
          $msg = __('message.The sample has been collected successfully');
          $data->status = $status;
          $data->collected_datetime = $this->getsitedate();
          $data->save();
          if($data){
                $android = $this->send_notification_order_android($setting->android_server_key,$data->user_id,$msg,$data->id);
                $ios = $this->send_notification_order_ios($setting->ios_server_key,$data->user_id,$msg,$data->id);
            }
      }
      if($status=='7'){
            if ($files = $request->file('report')) {
                $file = $request->file('report');
                $filename = $file->getClientOriginalName();
                $extension = $file->getClientOriginalExtension() ?: 'png';               
                $picture = str_random(10).time() . '.' . $extension;
                $destinationPath = Storage_path("app/public/report");
                $request->file('report')->move($destinationPath, $picture);
                $report =$picture;
            }
            else{
                    $report="";
            }
          // $msg = "Order Is Complete";
          $msg = __('message.Order Is Complete');
          $data->status = $status;
          $data->complete_datetime = $this->getsitedate();
          $data->report = $report;
          $data->save();
          if($data){
                $android = $this->send_notification_order_android($setting->android_server_key,$data->user_id,$msg,$data->id);
                $ios = $this->send_notification_order_ios($setting->ios_server_key,$data->user_id,$msg,$data->id);
            }
      }
            $data1 = array();
            $data1['email']=User::find($data->user_id)?User::find($data->user_id)->email:'';
            $data1['msg']=$msg;
            $data1['order_id']=$id;
            $data1['customer_name'] = User::find($data->user_id)?User::find($data->user_id)->name:'';
            try {
                $result=Mail::send('email.order_status', ['user' => $data1], function($message) use ($data1){
                    $message->to($data1['email'],$data1['customer_name'])->subject(__('message.site_name'));
                });
            } catch (\Exception $e) {
            } 
      Session::flash('message',$msg); 
      Session::flash('alert-class', 'alert-success');
      return redirect()->back();
    }

    public function send_notification_order_android($key,$user_id,$msg,$id){
          $getuser=Token::where("type",1)->where('user_id',$user_id)->get();
          if(count($getuser)!=0){               
               $reg_id = array();
               foreach($getuser as $gt){
                   $reg_id[]=$gt->token;
               }
               $registrationIds =  $reg_id;    
               $message = array(
                    'message' => $msg,
                    'key'=>'Booking',
                    'title' => 'Booking Successfull',
                    'order_id'=>$id
                );
                
               $fields = array(
                  'registration_ids'  => $registrationIds,
                  'data'              => $message
               );

               $url = 'https://fcm.googleapis.com/fcm/send';
               $headers = array(
                 'Authorization: key='.$key,// . $api_key,
                 'Content-Type: application/json'
               );
              
              $json =  json_encode($fields);   
              try {
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$json);
                    $result = curl_exec($ch);  

                    if ($result === FALSE){
                       die('Curl failed: ' . curl_error($ch));
                    }     
                   curl_close($ch);
                   $response=json_decode($result,true); 
                   
                  } catch (\Exception $e) {
                    return 0;
                 }
                 
             if(isset($response)&&$response['success']>0)
              {
                   return 1;
              }
            else
               {
                  return 0;
               }
         }
         return 0;
    }
   
    public function send_notification_order_ios($key,$user_id,$msg,$id){
          $getuser=Token::where("type",2)->where('user_id',$user_id)->get();
          if(count($getuser)!=0){               
               $reg_id = array();
               foreach($getuser as $gt){
                   $reg_id[]=$gt->token;
               }
               $registrationIds =  $reg_id;    
               $message = array(
                    'message' => $msg,
                    'key'=>'Booking',
                    'title' => 'Booking Successfull',
                    'order_id'=>$id
                );
               $fields = array(
                  'registration_ids'  => $registrationIds,
                  'data'              => $message
               );

               $url = 'https://fcm.googleapis.com/fcm/send';
               $headers = array(
                 'Authorization: key='.$key,// . $api_key,
                 'Content-Type: application/json'
               );
              $json =  json_encode($fields);   
              try {
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$json);
                    $result = curl_exec($ch);  

                    if ($result === FALSE){
                       die('Curl failed: ' . curl_error($ch));
                    }     
                   curl_close($ch);
                   $response=json_decode($result,true); 
                  } catch (\Exception $e) {
                    return 0;
                 }
                 
             if(isset($response)&&$response['success']>0)
              {
                   return 1;
              }
            else
               {
                  return 0;
               }
         }
         return 0;
    }

    public function show_complete_order(Request $request){
        
           $data = Orders::find($request->get("id"));
        //   echo "<pre>";
        //   print_r($data);
        //   exit();
           if ($files = $request->file('report')) {
                $file = $request->file('report');
                $filename = $file->getClientOriginalName();
                $extension = $file->getClientOriginalExtension() ?: 'png';               
                $picture = rand().time() . '.' . $extension;
                $destinationPath = Storage_path("app/public/report");
                $request->file('report')->move($destinationPath, $picture);
                $report =$picture;
            }
            else{
                    $report="";
            }
          // $msg = "Order Is Complete";
          $msg = __('message.Order Is Complete');
          $data->status = '7';
          $data->complete_datetime = $this->getsitedate();
          $data->report = $report;
          $data->save(); 
          $data1 = array();
          $data1['email']=User::find($data->user_id)?User::find($data->user_id)->email:'';
          $data1['msg']=$msg;
          $data1['order_id']=$request->get("id");
          $data1['customer_name'] = User::find($data->user_id)?User::find($data->user_id)->name:'';
          $data1['report'] = $report;
          try {
                $result=Mail::send('email.order_status', ['user' => $data1], function($message) use ($data1){
                    $message->to($data1['email'],$data1['customer_name'])->subject(__('message.site_name'));
                    $message->attach(Storage_path("app/public/report").'/'.$data1['report']);
                });
          } catch (\Exception $e) {
          } 
          Session::flash('message',$msg); 
          Session::flash('alert-class', 'alert-success');
          return redirect()->back();
    }

    public function refunded_order_amount($method,$token,$amount){
        $getallkeys = PaymentGateway::all();
        $ls = array();
        foreach($getallkeys as $g){
            $ls[$g->payment_gateway_name."_".$g->key_name] = $g->meta_value;
        }
        if($method=="braintree"){
                $gateway = new \Braintree\Gateway([
                    'environment' => $ls['Braintree_environment'],
                    'merchantId' => $ls['Braintree_merchantId'],
                    'publicKey' => $ls['Braintree_publicKey'],
                    'privateKey' => $ls['Braintree_privateKey']
                 ]);
                 $result = $gateway->transaction()->refund($token);
                 if($result->success==true){
                    return 1;
                 }else{
                    return 0;
                 }
        }else if($method=="stripe"){
                \Stripe\Stripe::setApiKey($ls['Stripe_secert_key']);
                $refund = \Stripe\Refund::create([
                    'charge' => $token,
                    'amount' => (int)($amount * 100),  // For 10 $
                ]);
                echo "<pre>";print_r($refund);exit;

        }else{
            return 1;
        }
    }

}
