<?php

namespace App\Http\Controllers;

use App\Models\Event;
use App\Jobs\SendSmsJob;
use App\Models\Donation;
use App\Models\PaymentInfo;
use Illuminate\Http\Request;
use ShurjopayPlugin\Shurjopay;
use ShurjopayPlugin\PaymentRequest;

class ShurjopayControllers extends Controller
{
   public $sp_instance;
    /* Shurjopay injected in a constructor */
    public function __construct(Shurjopay $sp)
    {
        $this->sp_instance = $sp;
    }


    public function generateOderToken()
    {
        // Get the current token from the database
        $tokenCounter = PaymentInfo::where('order_token','desc')->first()->order_token ?? 1000;
        $currentToken = $tokenCounter + 1;
        return $currentToken;
    }


   public function send_payment_request_to_shurjopay(Request $request){

    $validated = $request->validate([
        'first_name' => 'required|string|max:100',
        'last_name' => 'required|string|max:100',
        'email' => 'required|string|max:100',
        'phone' => 'required|string||regex:/^\d{5}-\d{6}$/|max:18',
        'hotel_name' => 'nullable|string|max:250',
        'amount' => 'required|integer|max:1000000',
        'event_id' => 'required|integer',
        'city' => 'required|string|max:50',
        'address' => 'required|string|max:100',
    ]);
    // Cast the 'amount' to an integer
    $validated['amount'] = intval($validated['amount']);
    $validated['event_id'] = intval($validated['event_id']);
    // If the event_id doesn't exist, validation will fail with a custom message
    $event = Event::find($request->event_id);
    if (!$event) {
        return back()->withErrors(['event_id' => 'Event not found.'])->withInput();
    }

    $first_name = $request->first_name;
    $last_name = $request->last_name;
    $email = $request->email;
    $phone = str_replace('-', '', $request->phone);
    $hotel_name = $request->hotel_name;
    $city = $request->city;
    $address = $request->address;
    $amount = Event::find($request->event_id)->price;
    $event_id = $request->event_id;


       $payment_request = new PaymentRequest();

       $payment_request->currency = 'BDT';
       $payment_request->amount = $amount;
       $payment_request->discountAmount = '0';
       $payment_request->discPercent = '0';
       $payment_request->customerName = $first_name;
       $payment_request->customerPhone = $phone;
       $payment_request->customerEmail = $email;
       $payment_request->customerAddress = $address;
       $payment_request->customerCity = $city;
       $payment_request->customerState = 'N/A';
       $payment_request->customerPostcode = 'N/A';
       $payment_request->customerCountry = 'N/A';
       $payment_request->shippingAddress = 'N/A';
       $payment_request->shippingCity = 'N/A';
       $payment_request->shippingCountry = 'N/A';
       $payment_request->receivedPersonName = 'N/A';
       $payment_request->shippingPhoneNumber = 'N/A';
       $payment_request->value1 = $first_name;
       $payment_request->value2 = $last_name;
       $payment_request->value3 = $hotel_name;
       $payment_request->value4 = $event_id;

    //    dd($payment_request );

       $url_payment=$this->sp_instance->makePayment($payment_request);
       $url_payment=$url_payment->checkout_url;
       return view('payment.checkout', compact('url_payment'));
    }

    public function verify_payment(Request $request){
        $order_id = $request->order_id;
        $response=$this->sp_instance->verifyPayment($order_id);

        foreach($response as $response){

            //sms 
            $phone_no = $response->phone_no; 
            $payable_amount = $response->payable_amount;
            $payable_amount_int = (int) $payable_amount ?? $response->payable_amount; // 50
            $eventName = Event::find($response->value4)->headline;
            $orderToken = $this->generateOderToken();
            $smsBody = "Thanks for your your Registration at ".$eventName.".\nYour token no is ".$orderToken.", Registration fee Tk. ".$payable_amount_int." has been received successfully.";
            //sms end
            if($response->sp_code == 1001){

                
               
    // dd($orderToken, $smsBody);

                // dd('Payment Success');
                PaymentInfo::create([
                    'order_token' => $orderToken,
                    'first_name' => $response->value1,
                    'last_name' => $response->value2,
                    'email' => $response->email,
                    'phone' => $phone_no,
                    'hotel_name' => $response->value3,
                    'payment_info' => 'null',
                    'amount' => $response->amount,
                    'order_id' => $response->order_id,
                    'event_id' => $response->value4,
                    'shurjopay_id' => $response->id,
                    'currency' => $response->currency,
                    'payable_amount' => $response->payable_amount,
                    'discsount_amount' => $response->discount_amount,
                    'disc_percent' => $response->disc_percent,
                    'received_amount' => $response->recived_amount,
                    'usd_amt' => $response->usd_amt,
                    'usd_rate' => $response->usd_rate,
                    'is_verify' => $response->is_verify,
                    'card_holder_name' => $response->card_holder_name,
                    'card_number' => $response->card_number,
                    'bank_trx_id' => $response->bank_trx_id,
                    'invoice_no' => $response->invoice_no,
                    'bank_status' => $response->bank_status,
                    'customer_order_id' => $response->customer_order_id,
                    'sp_code' => $response->sp_code,
                    'sp_message' => $response->sp_message,
                    'name' => $response->name,
                    'address' => $response->address,
                    'city' => $response->city,
                    'transaction_status' => $response->transaction_status,
                    'method' => $response->method,
                    'date_time' => $response->date_time,
                ]);

                
                if (isValidBangladeshiNumber($phone_no)) {
                    SendSmsJob::dispatch($phone_no, $smsBody, 'event');
                }

                return redirect()->route('frontend')->with('success','Your payment was successfully completed. We appreciate your transaction!');

            }else{
                return redirect()->route('frontend')->with('error','Your payment has been cancelled. Please try again.');
            }
            return redirect()->route('frontend')->with('error','Your payment has been cancelled. Please try again.');
        }
        return redirect()->route('frontend')->with('error','Your payment has been cancelled. Please try again.');
        // print_r($response);exit;
    }

    
    public function donation(Request $request){
        $validated = $request->validate([
            'first_name' => 'required|string|max:100',
            'last_name' => 'required|string|max:100',
            'email' => 'required|string|max:100',
            'phone' => 'required|string||regex:/^\d{5}-\d{6}$/|max:18',
            'amount' => 'required|integer|max:1000000',
            'city' => 'required|string|max:50',
            'address' => 'required|string|max:100',
        ]);
        $validated['amount'] = intval($validated['amount']);
        
        $first_name = $request->first_name;
        $last_name = $request->last_name;
        $email = $request->email;
        $phone = str_replace('-', '', $request->phone);
        $city = $request->city;
        $address = $request->address;
        $amount = $validated['amount'];

       

        $payment_request = new PaymentRequest();

       $payment_request->currency = 'BDT';
       $payment_request->amount = $amount;
       $payment_request->discountAmount = '0';
       $payment_request->discPercent = '0';
       $payment_request->customerName = $first_name.' '.$last_name;
       $payment_request->customerPhone = $phone;
       $payment_request->customerEmail = $email;
       $payment_request->customerAddress = $address;
       $payment_request->customerCity = $city;
       $payment_request->customerState = 'N/A';
       $payment_request->customerPostcode = 'N/A';
       $payment_request->customerCountry = 'N/A';
       $payment_request->shippingAddress = 'N/A';
       $payment_request->shippingCity = 'N/A';
       $payment_request->shippingCountry = 'N/A';
       $payment_request->receivedPersonName = 'N/A';
       $payment_request->shippingPhoneNumber = 'N/A';
       $payment_request->value1 = $first_name;
       $payment_request->value2 = $last_name;
       $payment_request->value3 = 'donation';
       $payment_request->value4 = 'value4';

    //    dd($payment_request );

       $url_payment=$this->sp_instance->makeDonation($payment_request);
       $url_payment=$url_payment->checkout_url;
       return view('payment.checkout', compact('url_payment'));

    }

    public function verify_payment_donation(Request $request){
        $order_id = $request->order_id;
        $response=$this->sp_instance->verifyPayment($order_id);
        // print_r($response);exit;
        foreach($response as $response){
            // dd($response);
            if($response->sp_code == 1001){
                // dd('Payment Success');

                $PaymentInfo = Donation::create([
                    'first_name' => $response->value1,
                    'last_name' => $response->value2,
                    'email' => $response->email,
                    'phone' => $response->phone_no,
                    'payment_info' => 'null',
                    'amount' => $response->amount,
                    'order_id' => $response->order_id,
                    'shurjopay_id' => $response->id,
                    'currency' => $response->currency,
                    'payable_amount' => $response->payable_amount,
                    'discsount_amount' => $response->discount_amount,
                    'disc_percent' => $response->disc_percent,
                    'received_amount' => $response->recived_amount,
                    'usd_amt' => $response->usd_amt,
                    'usd_rate' => $response->usd_rate,
                    'is_verify' => $response->is_verify,
                    'card_holder_name' => $response->card_holder_name,
                    'card_number' => $response->card_number,
                    'bank_trx_id' => $response->bank_trx_id,
                    'invoice_no' => $response->invoice_no,
                    'bank_status' => $response->bank_status,
                    'customer_order_id' => $response->customer_order_id,
                    'sp_code' => $response->sp_code,
                    'sp_message' => $response->sp_message,
                    'name' => $response->name,
                    'address' => $response->address,
                    'city' => $response->city,
                    'transaction_status' => $response->transaction_status,
                    'method' => $response->method,
                    'date_time' => $response->date_time,
                ]);

                
                return redirect()->route('donate')->with('success','Success! Your donation has been successfully processed. We are incredibly grateful for your support.');
            }else{
                return redirect()->route('donate')->with('error','Your donation has been cancelled. Please try again.');
            }
            return redirect()->route('donate')->with('error','Your donation has been cancelled. Please try again.');
        }
        return redirect()->route('donate')->with('error','Your donation has been cancelled. Please try again.');
        // print_r($response);exit;
    }


    
}
