<?php

namespace App\Http\Controllers\Payment\causes;

use App\Course;
use App\CoursePurchase;
use App\DonationDetail;
use App\EventDetail;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Front\CausesController;
use App\Http\Controllers\Front\EventController;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Language;

class NowpaymentController extends Controller
{
    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, $amount, $success_url, $cancel_url)
    {
        /************************************
         * Course Enrolment Info start
         *************************************/

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

        $be = $currentLang->basic_extended;
        $bex = $currentLang->basic_extra;


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

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

        $title = "Donation";


        $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'])) {
            $paymentFor = Session::get('paymentFor');
            $transaction_id = uniqid('nowpay-');
            $transaction_details = null;
            $amount = $requestData["amount"];
            if ($paymentFor == "Cause") {
                $cause = new CausesController;
                $donation = $cause->store($requestData, $transaction_id, $transaction_details, $amount, $bex);

                if ($donation) {
                    $donation->nowpayment_invoice_id = $invoice['id'];
                    $donation->save();

                    Session::put('purchaseId', $donation->id);

                    return redirect($invoice['invoice_url']);
                }
            } elseif ($paymentFor == "Event") {
                $amount = $request["total_cost"];
                $event = new EventController;
                $event_details = $event->store($request, $transaction_id, $transaction_details, $amount, $bex);
                $file_name = $event->makeInvoice($event_details);
                $event->sendMailPHPMailer($request, $file_name, $be);


                return redirect()->route('front.event_details', [$request["event_slug"]]);
            }
        } 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 = [];

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

        if (is_array($responseData) && array_key_exists('invoice_id', $responseData)) {
            $paymentFor = Session::get('paymentFor');


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

            if ($paymentFor == "Cause") {

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

                $donation->nowpayment_payment_id =  $payment_id;
                $donation->save();
            } elseif ($paymentFor == "Event") {
                $eventBooking = EventDetail::where('nowpayment_invoice_id', $invoice_id)->first();

                if (!$eventBooking) {
                    Log::error('Donation not found for invoice: ' . $invoice_id);
                    abort(404);
                }

                $eventBooking->nowpayment_payment_id =  $payment_id;
                $eventBooking->save();
            }

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

            return redirect()->route('course.paypal.complete');
        }
        return redirect()->route('nowpayment.payment.cancel');
    }


    public function nowPaymentCronJobevent($course_purchase)
    {
        $course_purchase->status = 1;
        $course_purchase->save();
    }
    public function nowPaymentCronJobcause($course_purchase)
    {
        $course_purchase->status = 1;
        $course_purchase->save();
    }
}
