<?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::orderBy('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.' '.$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 = $hotel_name;
       $payment_request->value4 = $event_id;

 

       $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;
        try {
            $response = $this->sp_instance->verifyPayment($order_id);

            foreach($response as $key => $resp){
    
                //sms 
                $phone_no = $resp->phone_no; 
                $payable_amount = $resp->payable_amount;
                $payable_amount_int = (int) $payable_amount ?? $resp->payable_amount; // 50
                $eventName = Event::find($resp->value4)->headline;
                $orderToken = $this->generateOderToken();
                // $smsBody = "Thanks for your Registration at ".$eventName.".\nYour token no is ".$orderToken.", Registration fee Tk. ".$payable_amount_int." has been received successfully.";
                // $smsBody = "HOTELIERS!\nThanks for your Registration at ".$eventName.".\nYour token no # ".$orderToken.",\nRegistration fee Tk. ".$payable_amount_int." has been received successfully.";
                $smsBody = "Dear HOTELIERS!\nThanks for your Registration at ".$eventName.".\nYour token no # ".$orderToken.",\nRegistration fee Tk. ".$payable_amount_int." has been received successfully.\n\n-regards\nBANGLADESH HOTELIERS";
                //sms end
                
                if($resp->sp_code == 1000){
                    
                    // Check if the transaction ID already exists in the database
                    // $existingPaymentInfo = PaymentInfo::where('shurjopay_id', $resp->id)->first();
                    // if ($existingPaymentInfo) {
                    //     // If $existingPaymentInfo with the same ID exists, return an error message
                    //     return redirect()->route('frontend')->with('error', 'Payment information already exists');
                    // }
                    
                    if($key == 0){
                        PaymentInfo::create([
                            'order_token' => $orderToken,
                            'first_name' => $resp->value1,
                            'last_name' => $resp->value2,
                            'email' => $resp->email,
                            'phone' => $phone_no,
                            'hotel_name' => $resp->value3,
                            'payment_info' => 'null',
                            'amount' => $resp->amount,
                            'order_id' => $resp->order_id,
                            'event_id' => $resp->value4,
                            'shurjopay_id' => $resp->id,
                            'currency' => $resp->currency,
                            'payable_amount' => $resp->payable_amount,
                            'discsount_amount' => $resp->discount_amount,
                            'disc_percent' => $resp->disc_percent,
                            'received_amount' => $resp->recived_amount,
                            'usd_amt' => $resp->usd_amt,
                            'usd_rate' => $resp->usd_rate,
                            'is_verify' => $resp->is_verify,
                            'card_holder_name' => $resp->card_holder_name,
                            'card_number' => $resp->card_number,
                            'bank_trx_id' => $resp->bank_trx_id,
                            'invoice_no' => $resp->invoice_no,
                            'bank_status' => $resp->bank_status,
                            'customer_order_id' => $resp->customer_order_id,
                            'sp_code' => $resp->sp_code,
                            'sp_message' => $resp->sp_message,
                            'name' => $resp->name,
                            'address' => $resp->address,
                            'city' => $resp->city,
                            'transaction_status' => $resp->transaction_status,
                            'method' => $resp->method,
                            'date_time' => $resp->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{
                    
                    PaymentInfo::create([
                        'order_token' => $orderToken,
                        'first_name' => $resp->value1,
                        'last_name' => $resp->value2,
                        'email' => $resp->email,
                        'phone' => $phone_no,
                        'hotel_name' => $resp->value3,
                        'payment_info' => 'null',
                        'amount' => $resp->amount,
                        'order_id' => $resp->order_id,
                        'event_id' => $resp->value4,
                        'shurjopay_id' => $resp->id,
                        'currency' => $resp->currency,
                        'payable_amount' => $resp->payable_amount,
                        'discsount_amount' => $resp->discount_amount,
                        'disc_percent' => $resp->disc_percent,
                        'received_amount' => $resp->recived_amount,
                        'usd_amt' => $resp->usd_amt,
                        'usd_rate' => $resp->usd_rate,
                        'is_verify' => $resp->is_verify,
                        'card_holder_name' => $resp->card_holder_name,
                        'card_number' => $resp->card_number,
                        'bank_trx_id' => $resp->bank_trx_id,
                        'invoice_no' => $resp->invoice_no,
                        'bank_status' => $resp->bank_status,
                        'customer_order_id' => $resp->customer_order_id,
                        'sp_code' => $resp->sp_code,
                        'sp_message' => $resp->sp_message,
                        'name' => $resp->name,
                        'address' => $resp->address,
                        'city' => $resp->city,
                        'transaction_status' => $resp->transaction_status,
                        'method' => $resp->method,
                        'date_time' => $resp->date_time,
                    ]);
                        
                    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.');
            
        }catch (\Exception $e) {
            // Catch any exceptions and handle them
            // You can log the error or handle it as per your needs
            \Log::error('Payment verification failed: ' . $e->getMessage());
    
            return redirect()->route('frontend')->with('error', 'An error occurred while processing your donation. 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;
        
        try {
            $response=$this->sp_instance->verifyPayment($order_id);
            // print_r($response);exit;
            // dd($response);
            
            foreach($response as $key => $resp){
                
                if($resp->sp_code == 1000){
                    // dd('Payment Success',$resp);
                    // Check if the transaction ID already exists in the database
                    $existingDonation = Donation::where('shurjopay_id', $resp->id)->first();
                    if ($existingDonation) {
                        // If donation with the same ID exists, return an error message
                        return redirect()->route('donate');
                    }
                    
                    if($key == 0){
                        Donation::create([
                            'first_name' => $resp->value1,
                            'last_name' => $resp->value2,
                            'email' => $resp->email,
                            'phone' => $resp->phone_no,
                            'payment_info' => 'null',
                            'amount' => $resp->amount,
                            'order_id' => $resp->order_id,
                            'shurjopay_id' => $resp->id,
                            'currency' => $resp->currency,
                            'payable_amount' => $resp->payable_amount,
                            'discsount_amount' => $resp->discount_amount,
                            'disc_percent' => $resp->disc_percent,
                            'received_amount' => $resp->recived_amount,
                            'usd_amt' => $resp->usd_amt,
                            'usd_rate' => $resp->usd_rate,
                            'is_verify' => $resp->is_verify,
                            'card_holder_name' => $resp->card_holder_name,
                            'card_number' => $resp->card_number,
                            'bank_trx_id' => $resp->bank_trx_id,
                            'invoice_no' => $resp->invoice_no,
                            'bank_status' => $resp->bank_status,
                            'customer_order_id' => $resp->customer_order_id,
                            'sp_code' => $resp->sp_code,
                            'sp_message' => $resp->sp_message,
                            'name' => $resp->name,
                            'address' => $resp->address,
                            'city' => $resp->city,
                            'transaction_status' => $resp->transaction_status,
                            'method' => $resp->method,
                            'date_time' => $resp->date_time,
                        ]);
                    }
                    
                    return redirect()->route('donate')->with('success','Success! Your donation has been successfully processed. We are incredibly grateful for your support.');
                }else{
                    
                    Donation::create([
                        'first_name' => $resp->value1,
                        'last_name' => $resp->value2,
                        'email' => $resp->email,
                        'phone' => $resp->phone_no,
                        'payment_info' => 'null',
                        'amount' => $resp->amount,
                        'order_id' => $resp->order_id,
                        'shurjopay_id' => $resp->id,
                        'currency' => $resp->currency,
                        'payable_amount' => $resp->payable_amount,
                        'discsount_amount' => $resp->discount_amount,
                        'disc_percent' => $resp->disc_percent,
                        'received_amount' => $resp->recived_amount,
                        'usd_amt' => $resp->usd_amt,
                        'usd_rate' => $resp->usd_rate,
                        'is_verify' => $resp->is_verify,
                        'card_holder_name' => $resp->card_holder_name,
                        'card_number' => $resp->card_number,
                        'bank_trx_id' => $resp->bank_trx_id,
                        'invoice_no' => $resp->invoice_no,
                        'bank_status' => $resp->bank_status,
                        'customer_order_id' => $resp->customer_order_id,
                        'sp_code' => $resp->sp_code,
                        'sp_message' => $resp->sp_message,
                        'name' => $resp->name,
                        'address' => $resp->address,
                        'city' => $resp->city,
                        'transaction_status' => $resp->transaction_status,
                        'method' => $resp->method,
                        'date_time' => $resp->date_time,
                    ]);
                    
                    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.');
            
        }catch (\Exception $e) {
            // Catch any exceptions and handle them
            // You can log the error or handle it as per your needs
            \Log::error('Payment verification failed: ' . $e->getMessage());
    
            return redirect()->route('donate')->with('error', 'An error occurred while processing your donation. Please try again.');
        }
        
    }
    
    
    public function verify_payment_donation2(Request $request)
    {
        $order_id = $request->order_id;
    
        try {
            // Verify the payment using the order ID
            $response = $this->sp_instance->verifyPayment($order_id);
    
            // Loop through each response
            foreach ($response as $key => $resp) {
                // Check if the payment was successful
                if ($resp->sp_code == 1000) {
                    // Attempt to store the payment information in the database
                    Donation::create([
                        'first_name' => $resp->value1,
                        'last_name' => $resp->value2,
                        'email' => $resp->email,
                        'phone' => $resp->phone_no,
                        'payment_info' => 'null',
                        'amount' => $resp->amount,
                        'order_id' => $resp->order_id,
                        'shurjopay_id' => $resp->id,
                        'currency' => $resp->currency,
                        'payable_amount' => $resp->payable_amount,
                        'discsount_amount' => $resp->discount_amount,
                        'disc_percent' => $resp->disc_percent,
                        'received_amount' => $resp->recived_amount,
                        'usd_amt' => $resp->usd_amt,
                        'usd_rate' => $resp->usd_rate,
                        'is_verify' => $resp->is_verify,
                        'card_holder_name' => $resp->card_holder_name,
                        'card_number' => $resp->card_number,
                        'bank_trx_id' => $resp->bank_trx_id,
                        'invoice_no' => $resp->invoice_no,
                        'bank_status' => $resp->bank_status,
                        'customer_order_id' => $resp->customer_order_id,
                        'sp_code' => $resp->sp_code,
                        'sp_message' => $resp->sp_message,
                        'name' => $resp->name,
                        'address' => $resp->address,
                        'city' => $resp->city,
                        'transaction_status' => $resp->transaction_status,
                        'method' => $resp->method,
                        'date_time' => $resp->date_time,
                    ]);
    
                    // Redirect after success and break out of the loop
                    return redirect()->route('donate')->with('success', 'Success! Your donation has been successfully processed. We are incredibly grateful for your support.');
                } else {
                    // If payment fails, return an error message
                    return redirect()->route('donate')->with('error', 'Your donation has been cancelled. Please try again.');
                }
            }
    
            // If no response matched, handle failure
            return redirect()->route('donate')->with('error', 'Your donation has been cancelled. Please try again.');
        } catch (\Exception $e) {
            // Catch any exceptions and handle them
            // You can log the error or handle it as per your needs
            \Log::error('Payment verification failed: ' . $e->getMessage());
    
            return redirect()->route('donate')->with('error', 'An error occurred while processing your donation. Please try again.');
        }
    }




    
}
