<?php

namespace App\Http\Controllers\Api;

use App\Classes\AuthUser;
use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\PayBillLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Http\Controllers\PaymentController;
use App\Models\Billpayment;
use App\Models\ResellerClientBillPayment;
use App\Services\ResellerClientOlineRechargeService;
use Carbon\Carbon;

class PrepaidBillPaymentController extends Controller
{

    public function checkAuth($request)
    {
        if ($request->app_key == config('app.nagad_app') && $request->secret == config('app.nagad_secret')) {
            return true;
        } elseif ($request->app_key == config('app.bkash_app') && $request->secret == config('app.bkash_secret')) {
            return true;
        } elseif ($request->app_key == config('payment.UPAY_PAYBILL_APP_KEY') && $request->secret == config('payment.UPAY_PAYBILL_SECRET')) {
            return true;
        }elseif ($request->app_key == config('app.rocket_app_key') && $request->secret == config('app.rocket_app_secret')) {
            return true;
        } else {
            return false;
        }
    }

    public function checkPrepaidBill(Request $request)
    {

        $response = null;
        $payBillLog = new PayBillLog();
        $payBillLog->payment_method = $request->app_key;
        $payBillLog->request = json_encode($request->all());
        $payBillLog->client_id = $request->customer_id;

        if ($this->checkAuth($request)) {
            if (checkSettings('prepaid-bill-by-client-username') == 'disable' && checkSettings('prepaid-bill-by-client-code') == 'disable' && preg_match('/[a-zA-Z]/', $request->customer_id)) {
                $response = [
                    'ErrorCode' => 404,
                    'ErrorMessage' => 'Customer Id invalid',
                ];
            } else {


                if (checkSettings('prepaid-bill-by-client-username') == 'enable' && checkSettings('prepaid-bill-by-client-code') == 'disable') {
                    $client = Client::with('pop', 'clientsinfo', 'customerAccount')->where('userid', $request->customer_id)->withTrashed()->first();
                } else if (checkSettings('prepaid-bill-by-client-code') == 'enable' && checkSettings('prepaid-bill-by-client-username') == 'disable') {
                    $client = Client::with('pop', 'clientsinfo', 'customerAccount')->where('customer_code', $request->customer_id)->withTrashed()->first();
                } else {
                    $client = Client::with('pop', 'clientsinfo', 'customerAccount')->where('id', (int)$request->customer_id)->withTrashed()->first();
                }


                if ($client && $client->pop->bill_generate == 'yes') {
                    $token = Hash::make(Str::random(60) . now()->timestamp . $client->id);
                    $client->payment_token = $token;
                    $client->app_key_type = $request->app_key;
                    $client->save();

                    $response = [
                        'name' => $client->clientsinfo->clients_name,
                        'contact' => $client->clientsinfo->contact_no,
                        'bill_amount' => $client->customerAccount->dueAmount > 0 ? $client->customerAccount->dueAmount : 0,
                        'ErrorCode' => 200,
                        'ErrorMessage' => 'Success'
                    ];
                } else {

                    if($client && globalPermission('ResellerClientOnlineRecharge')){
                        $response = [
                            'name' => $client->clientsinfo->clients_name,
                            'contact' => $client->clientsinfo->contact_no,
                            'bill_amount' => 0,
                            'ErrorCode' => 200,
                            'ErrorMessage' => 'Success'
                        ];
                    }else{

                        $response = [
                            'ErrorCode' => 404,
                            'ErrorMessage' => 'Customer Id invalid',
                        ];
                    }

                }


            }
        } else {
            $response = [
                'ErrorCode' => 401,
                'ErrorMessage' => 'Unauthorized'
            ];
        }

        $payBillLog->response = json_encode($response);
        $payBillLog->request_url = "bill-check";
        $payBillLog->save();
        return response()->json($response, $response['ErrorCode']);
    }

    public function prePayment(Request $request)
    {
        $response = null;
        $error_message = null;
        $payBillLog = new PayBillLog();
        $payBillLog->payment_method = $request->app_key;
        $payBillLog->request = json_encode($request->all());
        $payBillLog->client_id = $request->customer_id;
        $payBillLog->trxn_id = $request->trx_id;
        $payBillLog->request_url = "pre-payment";

        if ($this->checkAuth($request)) {

            if($request->amount <= 0){
                $response = [
                    'ErrorCode' => 408,
                    'ErrorMessage' => 'Minimum Amount not paid'
                ];
                $error_message = 'Minimum Amount not paid';
            }else{


                if (checkSettings('prepaid-bill-by-client-username') == 'enable' && checkSettings('prepaid-bill-by-client-code') == 'disable') {
                    $client = Client::with('pop', 'clientsinfo', 'customerAccount')->where('userid', $request->customer_id)->withTrashed()->first();
                } else if (checkSettings('prepaid-bill-by-client-code') == 'enable' && checkSettings('prepaid-bill-by-client-username') == 'disable') {
                    $client = Client::with('pop', 'clientsinfo', 'customerAccount')->where('customer_code', $request->customer_id)->withTrashed()->first();
                } else {
                    $client = Client::with('pop', 'clientsinfo', 'customerAccount')->where('id', $request->customer_id)->withTrashed()->first();
                }

                if ($client) {

                    if($client->pop->bill_generate == "yes"){
                        // dd($client);
                        $result = (new PaymentController)->billPayPayment($request->trx_id, $client->id, $request->amount, $request->mobile_no, $request->datetime, $client->app_key_type, 'prepaidBillPay');
                    }else{
                        if(globalPermission('ResellerClientOnlineRecharge')){
                            // dd("comes");
                            $user = (new AuthUser)->check('user@' . $request->app_key . '.com', $request->app_key);
                            $result = (new ResellerClientOlineRechargeService)->resellerClientPayBillPaymentProcess($client->id,$request->amount,$request->trx_id,$user->id,"Bkash-Pay-Bill");
                        }
                    }




                    if ($result['status'] == 'success') {

                        if($client->deleted_at != null){
                            $client->restore();
                        }
                        
                        $response = [
                            'result' => $result['status'],
                            'paymentAmount' => $request->amount,
                            'ErrorCode' => 200,
                            'ErrorMessage' => 'Success'
                        ];
                    } else {
                        $response = [
                            'ErrorCode' => 409,
                            'ErrorMessage' => $result['status']
                        ];
                        $error_message = $result['message'];
                    }
                } else {
                    $response = [
                        'ErrorCode' => 404,
                        'ErrorMessage' => 'Customer Id not found'
                    ];
                    $error_message = 'Customer Id not found';
                }
            }

        } else {
            $response = [
                'ErrorCode' => 400,
                'ErrorMessage' => 'Bad Request'
            ];
            $error_message = 'Bad Request';
        }

        $payBillLog->response = json_encode($response);
        $payBillLog->error_message = $error_message;
        $payBillLog->save();
        return response()->json($response, $response['ErrorCode']);
    }

    public function billSearch(Request $request)
    {
        $response = null;
        $error_message = null;
        $payBillLog = new PayBillLog();
        $payBillLog->payment_method = $request->app_key;
        $payBillLog->request = json_encode($request->all());
        $payBillLog->client_id = $request->customer_id;
        $payBillLog->trxn_id = $request->trx_id;
        $payBillLog->request_url = "bill-search";

        if ($this->checkAuth($request)) {


            $payment = $payment = Billpayment::with('clients', 'clientsinfo')
                ->where('money_receipt_number', $request->app_key . '_' . $request->trx_id)
                ->where('trx_id', $request->trx_id)->first();

            if ($payment) {
                $customer_id_info = '';
                if (checkSettings('prepaid-bill-by-client-username') == 'enable' && checkSettings('prepaid-bill-by-client-code') == 'disable') {
                    $customer_id_info = $payment->clients->userid;
                } else if (checkSettings('prepaid-bill-by-client-code') == 'enable' && checkSettings('prepaid-bill-by-client-username') == 'disable') {
                    $customer_id_info = $payment->clients->customer_code;
                } else {
                    $customer_id_info = $payment->clients->id;
                }

                $data = [
                    'name' => $payment->clientsinfo->clients_name,
                    'customer_id' => $customer_id_info,  // $payment->clients->id,
                    'paid_amount' => $payment->paid_amount,
                    'trxId' => $payment->trx_id,
                    'datetime' => $payment->paymentCreateTime,
                    'ErrorCode' => 200,
                    'ErrorMessage' => 'Success'
                ];

                $response = $data;
            } else {
                if (globalPermission('ResellerClientOnlineRecharge')) {
                    // Fetch the Reseller Client Online Recharge record based on trx_id
                    $resellerClientOnlineRecharge = ResellerClientBillPayment::with('client.clientsinfo')
                        ->where('trx_id', $request->trx_id)
                        ->first();

                    if ($resellerClientOnlineRecharge) {
                        // Determine customer ID information based on settings
                        $customer_id_info = '';
                        if (checkSettings('prepaid-bill-by-client-username') === 'enable' &&
                            checkSettings('prepaid-bill-by-client-code') === 'disable') {
                            $customer_id_info = $resellerClientOnlineRecharge->client->userid;
                        } elseif (checkSettings('prepaid-bill-by-client-code') === 'enable' &&
                                  checkSettings('prepaid-bill-by-client-username') === 'disable') {
                            $customer_id_info = $resellerClientOnlineRecharge->client->customer_code;
                        } else {
                            $customer_id_info = $resellerClientOnlineRecharge->client->id;
                        }

                        // Prepare the response data
                        $response = [
                            'name' => $resellerClientOnlineRecharge->client->clientsinfo->clients_name ?? "",
                            'customer_id' => $customer_id_info,
                            'paid_amount' => $resellerClientOnlineRecharge->amount,
                            'trxId' => $resellerClientOnlineRecharge->trx_id,
                            'datetime' => Carbon::parse($resellerClientOnlineRecharge->created_at)->format('Y-m-d H:i:s'),
                            'ErrorCode' => 200,
                            'ErrorMessage' => 'Success',
                        ];
                    } else {
                        // Response for when no record is found
                        $response = [
                            'ErrorCode' => 404,
                            'ErrorMessage' => 'Not Found',
                        ];
                        $error_message = 'Not Found';
                    }
                } else {
                    // Response when the user lacks necessary permissions
                    $response = [
                        'ErrorCode' => 404,
                        'ErrorMessage' => 'Not Found',
                    ];
                    $error_message = 'Not Found';
                }

            }


        } else {
            $response = [
                'ErrorCode' => 401,
                'ErrorMessage' => 'Unauthorized'
            ];

            $error_message = 'Unauthorized';
        }

        $payBillLog->response = json_encode($response);
        $payBillLog->error_message = $error_message;
        $payBillLog->save();
        return response()->json($response, $response['ErrorCode']);
    }
}
