<?php

namespace App\Http\Controllers\Payment\Course;

use App\Course;
use App\CoursePurchase;
use App\Http\Controllers\Controller;
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)
    {
        /************************************
         * Course Enrolment Info start
         *************************************/

        $course = Course::findOrFail($request->course_id);
        $total = $course->current_price;
        if (!Auth::user()) {
            Session::put('link', route('course_details', ['slug' => $course->slug]));
            return redirect()->route('user.login');
        }

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

        $bse = $currentLang->basic_extra;


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

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

        $title = "Course Purchase";
        $success_url = route('course.payment.nowpayment.success');
        $cancel_url = route('course.payment.nowpayment.cancel');
        $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'])) {

            // storing course purchase information in database
            $course_purchase = new CoursePurchase();
            $course_purchase->user_id = Auth::user()->id;
            $course_purchase->order_number = rand(100, 500) . time();
            $course_purchase->first_name = Auth::user()->fname;
            $course_purchase->last_name = Auth::user()->lname;
            $course_purchase->email = Auth::user()->email;
            $course_purchase->course_id = $course->id;
            $course_purchase->currency_code = $bse->base_currency_text;
            $course_purchase->current_price = $course->current_price;
            $course_purchase->previous_price = $course->previous_price;
            $course_purchase->payment_method = 'NOWPayments';
            $course_purchase->payment_status = 'Pending';
            $course_purchase->nowpayment_invoice_id = $invoice['id'];
            $course_purchase->save();

            // it will be needed for further execution
            $course_purchase_id = $course_purchase->id;
            Session::put('purchaseId', $course_purchase_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 = [];

        $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'];

            $course_purchase = CoursePurchase::where('nowpayment_invoice_id', $invoice_id)->first();
            if (!$course_purchase) {
                Log::error('Course Purchase not found for invoice: ' . $invoice_id);
                abort(404);
            }

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

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

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


    public function nowPaymentCronJob($course_purchase)
    {


        $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);
    }
}
