<?php

namespace App\Http\Controllers\Payment;

use App\BasicExtra;
use App\Http\Controllers\Payment\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\Package;
use App\PackageOrder;
use App\ProductOrder;
use App\Subscription;

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)
    {

        // Validation Starts

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

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


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

        $package_inputs = $currentLang->package_inputs;

        $this->orderValidation($request, $package_inputs);
        // Validation Ends


        // saving datas in database
        $po = $this->saveOrder($request, $package_inputs, 0);

        $package = Package::findOrFail($request->package_id);

        $cancel_url = route('front.payment.cancle', $package->id);

        $title = "product Purchase";
        $success_url = route('front.now.payment.success');
        $cancel_url = route('product.payment.cancle');
        $amount = round($package->price, 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();

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

            $po->nowpayment_invoice_id = $invoice['id'];
            $po->save();

            $order_id = $po->id;
            Session::put('purchaseId', $order_id);
            Session::put('package_id', $request->package_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 = [];
        $package_id = Session::get('package_id');

        $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 = Subscription::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('front.packageorder.confirmation', [$package_id, $order->id]);
        }
        return redirect()->route('nowpayment.payment.cancel');
    }


    public function nowPaymentCronJobcause($order)
    {
        $order->status = 1;
        $order->save();

        $bex = BasicExtra::first();
        if (session()->has('lang')) {
            $currentLang = Language::where('code', session()->get('lang'))->first();
        } else {
            $currentLang = Language::where('is_default', 1)->first();
        }
        $be = $currentLang->basic_extended;
        $packageid = $order->package_id;
        
        if ($bex->recurring_billing == 1) {
            $sub = Subscription::find($order->id);
            $package = Package::find($packageid);
            $po = $this->subFinalize($sub, $package);
        } else {
            $po = PackageOrder::findOrFail($order->id);
            $po->payment_status = 1;
            $po->save();
        }

        // send mails
        $this->sendMails($po, $be, $bex);
    }
}
