<?php

namespace App\Http\Controllers\Frontend\Payment;

use App\Http\Controllers\Controller;
use App\Models\PaymentManagement\PaymentMethod;
use App\Models\PaymentManagement\PaymentTransaction;
use App\Models\UserManagement\Customer;
use App\Models\UserManagement\User;
use App\Models\UserManagement\UserType;
use App\Services\InteractWithCart;
use App\Services\MobileMoney\MakeAMobileMoney;
use App\Services\OnlinePayments\PayPalRest;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Throwable;


class PaymentController extends Controller{
    use MakeAMobileMoney, InteractWithCart;


    /** Pour initier une nouvelle transaction
     * @param Request $request
     * @return mixed
     * @throws GuzzleException
     */
    public function init(Request $request){
       // dd("ici");
        $datasTransaction = [
            "order" => [ 'items' => $this->items(), 'total' => $this->total(),],
        ];
        $payer = auth(activeGuard())->user();

        $customer = $request->customer ?? null;
        if ($customer){

            $is_new = $customer->is_new ?? false;

            if ($is_new or !isset($customer['id'])){

                $phone = $customer['phone'];

                $customer = Customer::firstOrCreate(
                        [
                            "phone" => $phone,
                        ],
                       [
                           "first_name" => $customer['first_name'],
                           "last_name" => $customer['last_name'],
                           "email" => $customer['email'],
                           "password" => bcrypt($phone),
                           //"email" => $customer['email'],
                       ]
                    );
            }else{
                $customer = Customer::firstWhere('id',$customer['id']);
            }

            $payer = $customer;
        }

        if ($request->filled("order")){
            $order = $request->order;
            $items = $this->items($order['items']);
            $order['customer'] = $payer;
            $total = $this->total($order);
            $datasTransaction = [
                "order" => [ 'items' => $items, 'total' => $total,],
            ];
        }
       // dd($payer,$datasTransaction);
        $paymentMethod = PaymentMethod::findOrFail($request->paymentMethodId);

        if (in_array($paymentMethod->code,['orange-momo-cmr',"mtn-momo-cmr"])){
            return $this->momoInitTransaction($request, $datasTransaction, $payer);
        }

        if (in_array($paymentMethod->code,['paypal-rest',"mada-rest"])){
            return $this->initTransaction($request, $datasTransaction, $payer);
        }

    }


    /** Check le status de la transaction
     * @param Request $request
     * @param PaymentTransaction|null $transaction
     * @return JsonResponse
     * @throws GuzzleException
     * @throws Throwable
     */
    public function check(Request $request, PaymentTransaction $transaction = null){
        if (!$transaction and $request->filled("reference")){
            $transaction = PaymentTransaction::where('reference',$request->reference)->firstOrFail();
        }

        //interroge l'api et retourne le statut de la transaction
        $responseStatus = $this->getTransactionStatus($transaction);

        //check le statut de la transaction
        $response = $this->checkTransactionStatus($responseStatus,$transaction);

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

    public function paypalSuccess(Request $request,PaymentMethod $paymentMethod){
        $paypal = new PayPalRest($paymentMethod);
        $paymentMethodCode = $paymentMethod->code;
        $transactionReference = $request->get("paymentId");
        $transaction = PaymentTransaction::where('reference',$transactionReference)->firstOrFail();

        $response = $paypal->complete([
                        "payer_id" => $request->get("PayerID"),
                        "transactionReference" => $transactionReference,
                    ]);
        $data = $response->getData() ?? [];

        //le client a payé correctement
        if ($response->isSuccessful()){
            $transaction->update(['payer_number' => $data['payer']['payer_info']['email'] ?? null]);
            $data["status"] = "SUCCESSFUL";
            $message = __("Payment received successfully with ID : [:id]",['id' => $data['id']]);

        }else{
            $message =  $response->getMessage();
            $data["status"] = "FAILED";
            $transaction->update(['payment_result' =>['error' => $message] ]);
        }
        $paypal->saveDataTofile($transaction,$data,$paymentMethodCode);

        return "<h3 style='margin-top: 100px;'>$message</h2>";
    }

    public function paypalCancel(){
        $message = __("Payment Canceled.");
        return "<h3 style='color:#e3342f;  margin-top: 200px;'>$message</h2>";
    }
}
