<?php

namespace App\Http\Controllers;

use App\Classes\SMS\PaymentSms;
use App\Jobs\ClientSyncJobForSingle;
use App\Jobs\SendPaymentMailJob;
use App\Models\Billpayment;
use App\Models\Client;
use App\Models\CustomerAccount;
use App\Models\Employee;
use App\Models\Income;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CheckPaymentIntegrationController extends Controller
{
    public function processPendingPayment()
    {
        $ssl_info = config('sslcommerz');
        $ssl_store_id = $ssl_info["apiCredentials"]["store_id"];
        $ssl_store_password = $ssl_info["apiCredentials"]["store_password"];
        $base_url = "https://securepay.sslcommerz.com/validator/api/validationserverAPI.php?store_id=".$ssl_store_id."&store_passwd=".$ssl_store_password."&&val_id=";


        if (checkSettings('ssl-commerz-show') == 'enable'){
            $start = Carbon::parse(today()->subDay(1))->format('Y-m-d 00:00:00');
            $end = Carbon::parse(today())->format('Y-m-d 23:59:59');

            $orders  = DB::table('orders')->whereBetween('created_at', [$start, $end])
                            ->where('software_integration_status', 'pending')
                            ->where('val_id', '!=', null)
                            ->get();

            foreach ($orders as $order) {
                $checkPayment = Billpayment::where('trx_id', $order->transaction_id)->first();
                if($checkPayment != null){
                    DB::table('orders')
                    ->where('id', $order->id)
                    ->update(['software_integration_status' => 'completed','software_integration_comment' => "completed with out any schedule"]);

                }else{
                    try{
                        if($order->val_id != null){

                            $url = $base_url.$order->val_id;
                            $curl = curl_init();

                            curl_setopt_array($curl, array(
                                CURLOPT_URL => $url,
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_ENCODING => '',
                                CURLOPT_MAXREDIRS => 10,
                                CURLOPT_TIMEOUT => 0,
                                CURLOPT_FOLLOWLOCATION => true,
                                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                                CURLOPT_CUSTOMREQUEST => 'GET',
                                CURLOPT_HTTPHEADER => array(
                                        'Cookie: f5avraaaaaaaaaaaaaaaa_session_=EMBGMHAKLNOKBPJNJBBMJAFOELOEGOBECMGKNKJNBDDCFLDILNPFHMPHLIHIEIGHEGODGLEBNNJMGKEBODGADBGIFGOFJIKJANOOHILILOKAJNHPMHEDEELPMCHBLNMG; TS01d00da5=016ef4e8326a95917eb982cebff0fa61e7cccb819bce96555de07b8d16d156ce3ba34d2a7f39a319dad73abe6c6319624343c81f78e5f9ef2c9a5f361136711250e2af2797'
                                    ),
                            ));

                            $response = curl_exec($curl);

                            // dd($response);

                            curl_close($curl);
                            $result = json_decode($response);
                            // dd($result);
                            if($result->status == "VALIDATED"){
                                DB::beginTransaction();
                                try{
                                    $this->sslpayment($order->customer_id,$order->amount,$order->transaction_id);

                                    DB::commit();

                                    DB::table('orders')
                                    ->where('id', $order->id)
                                    ->update([
                                        'software_integration_status' => 'completed',
                                        'software_integration_comment' => "completed with schedule".$order->software_integration_try++." try",
                                        'software_integration_try' => $order->software_integration_try + 1,
                                    ]);

                                }catch(\Exception $e){
                                    DB::rollBack();
                                }

                            }


                        }

                    }catch(\Exception $e){
                        DB::table('orders')
                        ->where('id', $order->id)
                        ->update([
                            'software_integration_status' => 'pending',
                            'software_integration_comment' => $e->getMessage(),
                            'software_integration_try' => $order->software_integration_try + 1,
                        ]);
                    }
                }
            }
        }



    }



    public function sslpayment($customer_id,$amount,$tran_id)
    {

        $gateway = 'SSL-Commerz';


        $info = array(
            'customer_id'    => $customer_id,
            'amount'         => $amount,
            'transaction_id' => $tran_id,
            'description'    => 'Online Bill Payment: ' . $gateway
        );

        (new PaymentController())->billGenerateIfNotExist($customer_id);

        $client = Client::with('clientsinfo', 'pop', 'pop.reseller', 'customerAccount', 'generatedBill')->withCount('generatedBill')->find($info['customer_id']);

        $payment = Billpayment::create([
            'description'           =>  $info['description'],
            'paid_amount'           =>  $info['amount'] ?? 0,
            'discount_amount'       =>  0,
            'client_id'             =>  $info['customer_id'],
            'user_id'               =>  User::onlinePaymentUser($gateway)->id,
            'created_at'            =>  now(),
            'collected_by'          =>  Employee::onlinePaymentEmployee($gateway)->id,
            'money_receipt_number'  =>  'SSL_' . $info['transaction_id'],
            'trx_id'                =>  $info['transaction_id'],
            'payment_method'        =>  'Online Payment',
            'client_id_time'        =>  $info['customer_id'] . '_' . now()->format('Y-m-d H:i')
        ]);

        $income =   Income::create([
            'name' => 'Online Payment by ' . $gateway,
            'date' => now(),
            'amount' => $info['amount'] ?? 0,
            'description' => 'Online Bill Payment (' . $gateway . ')  for customer : ' . $client->userid,
            'incomeHead' => 11
        ]);
        $payment->income_id = $income->id;
        $payment->save();

        CustomerAccount::updateCustomrAccount($info['customer_id'], (-$info['amount']), $info['amount'], 0);
        $cac = CustomerAccount::where('client_id', $client->id)->first();



        $current_due_amount = $client->customerAccount->dueAmount ?? 0;

        $status =  (new PaymentController())->performeExpireDateExtend($client, $payment, $cac, $info['amount'], $client->pop, $current_due_amount, 'billpay', 0);

        if (checkAPI()) {
            ClientSyncJobForSingle::dispatch($client->id);
        }


        if ($status == 'balance_error') {
            return 'error';
        } else {
            if (checkSettings('auto-payment-sms-send') == 'enable') {
                try{
                    (new PaymentSms)->billPaymentSms($client, $info['amount'], $info['transaction_id'], $payment->id);
                }catch(\Exception $e){

                }
            }

            $emailSetting = json_decode(emailSetting()->where('tamplate_name', 'customer_payment_eamil')->first()->email_body);
            if ($emailSetting->sendemail == 'Yes') {
                try{
                    SendPaymentMailJob::dispatch($client, $payment, $emailSetting);
                }catch(\Exception $e){

                }

            }

            $info = array(
                'id' => $customer_id,
                'login_status' => 'success'
            );
            return 'success';
        }
    }

    public function store(Request $request)
    {

        $request->session()->put('weslkrfj', 3);
        dd("jflk");
        // session()->forget('reseller_id');
        return redirect()->route('get');

    }

    public function get(){
        dd(session()->all());
    }
}
