<?php

namespace App\Http\Controllers\Frontend\Payment;

use App\Http\Controllers\Controller;
use App\Models\OrderManagement\Coupon;
use App\Models\OrderManagement\Order;
use App\Models\OrderManagement\OrderTransaction;
use App\Models\PaymentManagement\Payment;
use App\Models\PaymentManagement\PaymentMethod;
use App\Models\ProductManagement\Product;
use App\Models\SettingManagement\Status;
use App\Models\UserManagement\User;
use App\Notifications\Backend\User\OrderCreatedNotification;
use App\Notifications\Frontend\User\OrderThanksNotification;
use App\Services\InteractWithCart;
use App\Services\OmnipayService;
use App\Services\OrderService;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Meneses\LaravelMpdf\Facades\LaravelMpdf as PDF;

class PaypalController extends Controller{

    use InteractWithCart;

    public function store(Request $request){
        $payer = auth(activeGuard())->user();
        $datas = [
            'items' => $this->items(), 'order' => $this->total(),
        ];
        //essaie d'enregistrer la commande
        $order = (new OrderService)->saveOrder($datas , $payer);
        $omniPay = new OmnipayService('PayPal_Express');
        $response = $omniPay->purchase([
                        'amount' => $datas['total'],
                        'transactionId' => $order->id,
                        'currency' => $order->currency,
                        'cancelUrl' => $omniPay->getCancelUrl($order->id),
                        'returnUrl' => $omniPay->getReturnUrl($order->id)
                    ]);

        if ($response->isRedirect()) {
            $response->redirect();
        }

        toast($response->getMessage(), 'error');
        return redirect()->route('home');
    }

    public function cancelled($orderId){
        $order = Order::findOrFail($orderId);

        $order->update(['status_code' => Status::CANCELED]);


        toast('You have canceled your order payment!', 'error');
        return redirect()->route('home');
    }

    public function completed($orderId): RedirectResponse{
        $order = Order::with('products', 'user', 'paymentMethod')->find($orderId);
        $orderId = $order->id;
        $payer = $order->customer; // App\Models\User

        $omniPay = new OmnipayService('PayPal_Express');
        $response = $omniPay->complete([
                        'amount' => $order->total,
                        'transactionId' => $order->id,
                        'currency' => $order->currency,
                        'cancelUrl' => $omniPay->getCancelUrl($orderId),
                        'returnUrl' => $omniPay->getReturnUrl($orderId),
                        'notifyUrl' => $omniPay->getNotifyUrl($orderId)
                    ]);

        if ($response->isSuccessful()) {
            $data = $response->getData();

            $paymentMethod = PaymentMethod::firstWhere('code',PaymentMethod::PAYPAL_REST);

            //ajoute le payment dans le compte du client
            $payer->addPayment([
                'provider_reference' => $response->getTransactionReference(),
                'created_by_api' => true,
                'payment_method_id' => $paymentMethod->id ?? null,
                'paid_amount' => $data["transactions"][0]['amount']['total'],
                'payer_number' => $data['payer']['payer_info']['payer_id'],
            ]);
            $order->update(['status_code' => Status::PAID]);
        }

        if (session()->has('coupon')) {
            $coupon = Coupon::whereCode(session()->get('coupon')['code'])->first();
            $coupon->increment('used_times');
        }

        Cart::instance('default')->destroy();

        session()->forget([
            'coupon',
            'saved_user_address_id',
            'saved_shipping_company_id',
            'saved_payment_method_id',
            'shipping'
        ]);

        toast('You have recent payment is successful with reference code: ' . $response->getTransactionReference(), 'success');
        return redirect()->route('home');
    }

    public function webhook($order, $env){
        // feature..
    }
}
