<?php 

namespace App\Http\Controllers;

use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Models\User;
use App\Models\Product;
use App\Models\Order;
use App\Models\BusinessInformation;
use Illuminate\Support\Facades\Validator;
use Illuminate\Notifications\Notification;
use App\Notifications\NewOrder;
use Illuminate\Support\Str;
use App\Traits\OrderTrait;
use App\Traits\BusinessInformationTrait;
use Redirect;
use Mail;
use Illuminate\Support\Facades\Log;

class NMIController extends Controller
{
    // private $login;
    // private $order;
    // private $billing;
    // private $shipping;
    // private $responses;
   
    // const ERROR = 3;

    use OrderTrait,BusinessInformationTrait;
    public function nmiform()
    {
        return view('nmiform');
    }   

    public function processPayment(Request $request)
    {
        $security_key = "x8N4rRYS2cxN4nK2u32cnr9237yWn7MP";
        $dataa = "";

        $dataa .= 'type=sale';
        $dataa .= '&amount='.$request->amount;
        $dataa .= '&security_key='.$security_key;
        $dataa.=  '&payment_token='.$request->payment_token;
           $dataa.= '&first_name='.$request->fname;
           $dataa.=  '&last_name='.$request->lname;
           $dataa.=  '&address='.$request->address1;


        
        $pt  =$request->payment_token;
       $query  = "";   
// $response = Http::post('https://secure.nmi.com/api/transact.php?type=sale&security_key'.$security_key.'&amount=1.00&payment_token='.$dataa
//        );  

$response = Http::post('https://secure.nmi.com/api/transact.php?'.$dataa);  
       if ($response->failed()) {
                    return 'ERROR';
                }
                $response_string = $response->body();
            // dd($response_string);
        $parameters = explode('&', $response_string);

        $transactionId = null;
        $responseno = null;

        foreach ($parameters as $parameter) {
            list($key, $value) = explode('=', $parameter);

             if ($key === 'transactionid') {
                $transactionId = $value;
            }
            if ($key === 'response') {
                $responseKey = $value;
            }
            if ($transactionId !== null && $responseKey !== null) {
                break;
            }
        }

        if ($responseKey == 1) {

            if(Order::where('client_id',Auth()->User()->id)->exists())
            
            {
                $status = 'Paid';
                $invc = $transactionId;
                
            Order::where('client_id',Auth()->User()->id)
            ->update([
                'order_Status'=>$status,
                'invoice_id'=>$invc
            ]);
            if(BusinessInformation::where('client_id',Auth()->User()->id)->exists())
            {   
                $business_info = $this->get_order_invoice();
                foreach($business_info as $business)
                        {
                            $orderno = $business->ordernumber;
                            $orderstat = $business->order_status;
                            $invoice_no = $business->invoice_id;
                            $bname = $business->bname;
                            $bemail = $business->bemail;
                            $bphone = $business->bphone;
                            $baddress = $business->baddress;
                            $radius_address = $business->radius_address;
                            $radius = $business->radius;
                            $firstname = $business->first_name;
                            $lastname = $business->last_name;
                            $phone = $business->phone;
                            $email = $business->email;
                            $pname = $business->productname;
                            $pdesc = $business->productdescription;
                            $price = $business->price; 
                            $service = $business->services;
                        $closer = $business->closer_name;
    
                        }
    
                        $maildata = [
                           'ordernumber'=>$orderno,
                           'invoiceno' => $invoice_no,
                           'status'=> $orderstat,
                           'bname'=>$bname ,
                           'bemail'=>$bemail,
                           'bphone'=>  $bphone,
                           'baddress'=>  $baddress,
                           'radiusaddress'=>  $radius_address,
                           'radius'=>  $radius,
                           'first_name'=>$firstname,
                           'last_name'=>$lastname,
                           'phone'=>$phone,
                           'email'=>$email,
                           'pname'=>$pname,
                           'pdesc'=>$pdesc,
                           'price'=>$price,
                        ];
                        
                        $pdf = PDF::loadView('email', $maildata);

                        $useremail['to'] = $email; 
                        Mail::send('email',$maildata,function($messages) use ($useremail, $pdf,$maildata){
                            $messages->to($useremail['to']);
                            $messages->subject('MyAIO Order Invoice');
                            $messages->attachData($pdf->output(), "Order#".$maildata['ordernumber'].".pdf");
                        });
                        Mail::send('email',$maildata,function($messages) use ($useremail, $pdf, $maildata){
                            $messages->to('talhachughtai10@gmail.com');
                            $messages->subject('MyAIO - New Order Recieved');
                            $messages->attachData($pdf->output(), "Order#".$maildata['ordernumber'].".pdf");
                        });
                
                           // Find admin user(s) with role 1
                  $admins = User::where('roles', 1)->get();
                  
                  foreach ($admins as $admin) {
                      $admin->notify(new NewOrder($maildata->ordernumber));
                  }
    
                Session::flush('success', 'Payment successful!');
                return view('orderinvoice')->with(['order'=>$business_info]);
            }
            else{
                session()->put('infopending','please add your business information to complete your business profile');
                return view('home');
            }
            
            }else{
    
                $pid  = BusinessInformation::where('client_id',Auth()->User()->id)->get('pid');
                foreach($pid as $productid)
                {
                    $product_id = $productid->pid;
                }
                $order = [
                    'client_id'=>Auth()->User()->id,
                    'product_id'=>$product_id,
                    'ordernumber'=>Str::random(5),
                    'order_status' => 'Paid',
                    'invoice_id' => $transactionId,
                    'payment_method' => 'Card',
                ];
                // Order::create($order); 

                $orderData = Order::create($order); 
                // Find admin user(s) with role 1
                $admins = User::where('roles', 1)->get();
                
                foreach ($admins as $admin) {
                    $admin->notify(new NewOrder($orderData->ordernumber));
                  //   Notification::send($admin, new NewOrder($order));
                }

                if(BusinessInformation::where('client_id',Auth()->User()->id)->exists())
                {   
                    $business_info = $this->get_order_invoice();                  
                    foreach($business_info as $business)
                    {
                    $email = $business->email;
                    $newprice = $business->newprice;
                    $date = \Carbon\Carbon::parse($business->date)->format('d/m/Y');
                    }
                    // dd($business_info);
                    if($newprice == NULL)
                    {
                        $newprice2 = $business->price;
                        $maildata = [
                            'ordernumber'=>$business->ordernumber,
                            'status'=> $business->order_status,
                            'invoiceno' => $business->invoice_id,
                            'bname'=>$business->bname,
                            'bemail'=>$business->bemail,
                            'bphone'=>  $business->bphone,
                            'baddress'=>  $business->baddress,
                            'radiusaddress'=>  $business->radius_address,
                            'radius' =>  $business->bradius,
                            'first_name'=>$business->first_name,
                            'last_name'=>$business->last_name,
                            'phone'=>$business->phone,
                            'email'=>$business->email,
                            'address'=>$business->address,
                            'pname'=>$business->productname,
                            'pdesc'=>$business->productdescription,
                            'service'=>$business->services,
                            'closer' => $business->closer_name,
                            'date'=>$date,
                            'oldprice' => $newprice2,
                         ];
                         $useremail['to'] = $email; 
                         $pdf = PDF::loadView('email', $maildata);

                         Mail::send('clientemail',$maildata,function($messages) use ($useremail, $pdf,$maildata){
                            $messages->to($useremail['to']);
                            $messages->subject('MyAIO Order Invoice');
                            $messages->attachData($pdf->output(), "Order#".$maildata['ordernumber'].".pdf");
                        });
                        Mail::send('clientemail',$maildata,function($messages) use ($useremail, $pdf, $maildata){
                            $messages->to('talhachughtai10@gmail.com');
                            $messages->subject('MyAIO - New Order Recieved');
                            $messages->attachData($pdf->output(), "Order#".$maildata['ordernumber'].".pdf");
                        });
                            Session::flush('success', 'Payment successful!');
                            return view('orderinvoice')->with(['order'=>$business_info]);
                    }
                    else{
                        $newprice2 = $business->newprice;
                        $maildata = [
                            'ordernumber'=>$business->ordernumber,
                            'status'=> $business->order_status,
                            'invoiceno' => $business->invoice_id,
                            'bname'=>$business->bname,
                            'bemail'=>$business->bemail,
                            'bphone'=>  $business->bphone,
                            'baddress'=>  $business->baddress,
                            'radiusaddress'=>  $business->radius_address,
                            'radius' =>  $business->bradius,
                            'first_name'=>$business->first_name,
                            'last_name'=>$business->last_name,
                            'phone'=>$business->phone,
                            'email'=>$business->email,
                            'address'=>$business->address,
                            'pname'=>$business->productname,
                            'pdesc'=>$business->productdescription,
                            'service'=>$business->services,
                            'closer' => $business->closer_name,
                            'date'=>$date,
                            'discount_price' => $business->discount_price,
                            'code' => $business->code,
                            'newprice' => $newprice2,
                            'oldprice' => $business->price,
                         ];
                         $useremail['to'] = $email; 
                         
                         $pdf = PDF::loadView('email2', $maildata);

                         Mail::send('clientemail',$maildata,function($messages) use ($useremail, $pdf,$maildata){
                            $messages->to($useremail['to']);
                            $messages->subject('MyAIO Order Invoice');
                            $messages->attachData($pdf->output(), "Order#".$maildata['ordernumber'].".pdf");
                        });
                        Mail::send('clientemail',$maildata,function($messages) use ($useremail, $pdf, $maildata){
                            $messages->to('talhachughtai10@gmail.com');
                            $messages->subject('MyAIO - New Order Recieved');
                            $messages->attachData($pdf->output(), "Order#".$maildata['ordernumber'].".pdf");
                        });
                            Session::flush('success', 'Payment successful!');
                            return view('orderinvoice')->with(['order'=>$business_info]);
                    }   
                }
                else{
                    session()->put('infopending','please add your business information to complete your business profile');
                    dd('error');
                    return view('home');
                }
            }
                return view('ordersuccess');
                dd('Your payment was successfully. You can create success page here.');
            return redirect()
                ->route('paypal')
                ->with('success', 'Transaction complete.');
        }
        elseif($responseKey == 2){
            return redirect('checkout')->with('payment-error',"Payment not proceed. Please try later.");
            // return $response_string;
        }
         else {
            // return redirect('checkout')->with('payment-error',"Payment not proceed. Please try again.");
            return $response_string;
        }

              
       
    }
}


