<?php

namespace App\Http\Controllers\Payment\product;

use App\Http\Controllers\Payment\product\PaymentController;
use App\CoursePurchase;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Language;
use App\ProductOrder;

class NowpaymentController  extends PaymentController
{
    public  $base_url;
    public  $api_key;
    public  $public_key;

    public function __construct()
    {
        $this->base_url = env("NOWPAYMENT_URL");
        $this->api_key = env("NOWPAYMENT_API_KEY");
        $this->public_key = env("NOWPAYMENT_PUBLIC_KEY");
    }

    public function createNowPayment(Request $request)
    {
        /************************************
         * Course Enrolment Info start
         *************************************/

        if (!Session::has('cart')) {
            return view('errors.404');
        }

        if (session()->has('lang')) {
            $currentLang = Language::where('code', session()->get('lang'))->first();
        } else {
            $currentLang = Language::where('is_default', 1)->first();
        }

        $bex = $currentLang->basic_extra;
        $bs = $currentLang->basic_setting;

        $total = $this->orderTotal($request->shipping_charge);

        if ($this->orderValidation($request)) {
            return $this->orderValidation($request);
        }


        /************************************
         * Course Enrolment Info End
         *************************************/

        /********************************************************
         * send payment request to nowpayment for create a payment url
         ********************************************************/

        $title = "product Purchase";
        $success_url = route('Payment\product\PaymentController@payreturn');
        $cancel_url = route('product.payment.cancle');
        $ipn_url = route('course.payment.nowpayment.ipn');
        $amount = round($total, 2);


        $order_id = Str::random(8); // 8 length unique ID
        $requestData = $request->except('_token');
        $requestData['title'] = $title;
        $requestData['order_id'] = $order_id;
        $requestData['status'] = 0;
        $requestData['nowpayment_request_data'] = json_encode($requestData);


        $response = Http::withHeaders([
            'x-api-key' => $this->api_key,
            'Content-Type' => 'application/json',
        ])->post($this->base_url . '/invoice', [
            'price_amount' => $amount,
            'price_currency' => 'USD',
            'order_id' => $order_id,
            'order_description' => $title,
            'ipn_callback_url' => null,
            'success_url' => $success_url,
            'cancel_url' => $cancel_url
        ]);

        $invoice = $response->json();

        // dd($invoice);

        if ($response->successful() && isset($invoice['invoice_url'])) {

            $txnId = 'txn_' . Str::random(8) . time();
            $chargeId = 'ch_' . Str::random(9) . time();
            $order = $this->saveOrder($request, $txnId, $chargeId);
            $order->nowpayment_invoice_id = $invoice['id'];
            $order->save();
            $order_id = $order->id;

            $this->saveOrderedItems($order_id);

            $orderData['item_name'] = $bs->website_title . " Order";
            $orderData['item_number'] = Str::random(4) . time();
            $orderData['item_amount'] = $total;
            $orderData['order_id'] = $order_id;

            // it will be needed for further execution
            $order_id = $order_id;
            Session::put('purchaseId', $order_id);

            return redirect($invoice['invoice_url']);
        } else {
            Session::flash('warning', 'Failed to create invoice.');
            return back();
        }
    }

    public function paymentCancel(Request $request)
    {
        return redirect()->back()->with('unsuccess', 'Payment Unsuccess');
    }

    public function currentPaymentActivity($paymentId)
    {
        $response = Http::withHeaders([
            'x-api-key' => env('NOWPAYMENT_API_KEY'),
        ])->get('https://api.nowpayments.io/v1/payment/' . $paymentId);
        return $response->json();
    }

    public function paymentSuccess(Request $request)
    {
        $information = [];
        $success_url = action('Payment\product\PaymentController@payreturn');

        $responseData = $this->currentPaymentActivity($request['NP_id']);

        if (is_array($responseData) && array_key_exists('invoice_id', $responseData)) {

            $invoice_id = $responseData['invoice_id'];
            $payment_id = $responseData['payment_id'];

            $order = ProductOrder::where('nowpayment_invoice_id', $invoice_id)->first();
            if (!$order) {
                Log::error('Order not found for invoice: ' . $invoice_id);
                abort(404);
            }

            $order->nowpayment_payment_id =  $payment_id;
            $order->save();

            Session::forget('courseData');
            Session::forget('currency');
            Session::forget('paymentId');

            return redirect()->route($success_url);
        }
        return redirect()->route('nowpayment.payment.cancel');
    }


    public function nowPaymentCronJob(Request $request)
    {
        try {
            $nowPaymentCoursePurchases = CoursePurchase::where([
                'payment_method' => 'NOWPayments',
                'payment_status' => 'Pending',
            ])->whereNotNull('nowpayment_payment_id')->get();
            foreach ($nowPaymentCoursePurchases as $course_purchase) {

                $nowpayment_payment_id = (int) $course_purchase->nowpayment_payment_id;
                $responseData = $this->currentPaymentActivity($nowpayment_payment_id);

                if (array_key_exists('payment_status', $responseData) && $responseData['payment_status'] == 'waiting') {

                    $course_purchase->payment_status = 'Completed';
                    $course_purchase->save();

                    // generate an invoice in pdf format
                    $fileName = $course_purchase->order_number . '.pdf';
                    $directory = 'assets/front/invoices/course/';
                    @mkdir($directory, 0775, true);
                    $fileLocated = $directory . $fileName;
                    $order_info = $course_purchase;
                    Pdf::loadView('pdf.course', compact('order_info', 'logo', 'bse'))
                        ->setPaper('a4', 'landscape')->save($fileLocated);

                    // store invoice in database
                    $course_purchase->update([
                        'invoice' => $fileName
                    ]);

                    // send a mail to the buyer with an invoice
                    MailController::sendMail($course_purchase);
                }
            }
        } catch (\Exception $e) {
            Log::info($e->getMessage());
        }
    }
}
