<?php
  
namespace App\Http\Controllers;
use Session;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
// use Srmklive\PayPal\Services\ExpressCheckout;
use Srmklive\PayPal\Services\PayPal as PayPalClient;
// use Srmklive\PayPal\Facades\PayPal; 
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 PDF;

use Illuminate\Support\Facades\Log;

   
class PayPalController extends Controller
{
    use OrderTrait,BusinessInformationTrait;

    public function generateRandomString($length = 8) {
        $characters = 'OPNTPR5656';
        $randomString = '';
    
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
    
        return $randomString;
    }

    public function payment(Request $request)
    {   
        $business_info = $this->get_business_info();
        $provider = new PayPalClient;
        $provider->setApiCredentials(config('paypal'));
        $paypalToken = $provider->getAccessToken();
        foreach($business_info as $business)
                    {
                        $price = $business->newprice; 
                    }
        $data = [];
        $p = $price;

        $response = $provider->createOrder([
            "intent" => "CAPTURE",
            "application_context" => [
                "name" => $business->productname,
                "desc" => $business->productdescription,
                "return_url" => route('payment.success'),
                "cancel_url" => route('payment.cancel'),
            ],
            "purchase_units" => [
                0 => [
                    "amount" => [
                        "currency_code" => "USD",
                        "value" => $p
                    ]
                ]
            ]
        ]);
        if (isset($response['id']) && $response['id'] != null) {
            foreach ($response['links'] as $links) {
                if ($links['rel'] == 'approve') {
                    return redirect()->away($links['href']);
                }
            }
            return redirect()
                ->route('payment.cancel')
                ->with('error', 'Something went wrong.');
        } else {
            return redirect()
                ->route('paypal')
                ->with('error', $response['message'] ?? 'Something went wrong.');
        }
    }

    public function paymentCancel()
    {
        return redirect()
            ->route('paypal')
            ->with('error', $response['message'] ?? 'You have canceled the transaction.');
    }

    public function success(Request $request)
    {
        $provider = new PayPalClient;
        $provider->setApiCredentials(config('paypal'));
        $provider->getAccessToken();
        $response = $provider->capturePaymentOrder($request['token']);
        foreach ($response['purchase_units'] as $purchaseUnit) {
            foreach ($purchaseUnit['payments']['captures'] as $capture) {
                $captureId = $capture['id'];
                // dd($captureId);
            }
        }

        
        if (isset($response['status']) && $response['status'] == 'COMPLETED') {

            if(Order::where('client_id',Auth()->User()->id)->exists())
            
            {
                $status = 'Paid';
                $invc = $captureId;
                
            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('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");
                        });

                     // 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' => $captureId,
                    'payment_method' => 'PayPal'
                ];
                $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.');
        } else {
            return redirect()
                ->route('paypal')
                ->with('error', $response['message'] ?? 'Something went wrong.');
        }
    }

    public function paypal()
    {
        return view('paypal');
        }

}