<?php

namespace App\Classes\SMS;

use App\Jobs\ExpireCustomerNotification;
use App\Jobs\ResellerSendSms;
use App\Models\Client;
use App\Models\CustomerAccount;
use App\Models\CustomerBillingCycleInfo;
use App\Models\CustomerPackageChangeInfo;
use App\Models\Packages;
use Carbon\Carbon;


class PaymentSms
{

    public function getSmsBody($type)
    {

        if ($type == 1) {
            $body = getSmsMessage()->where('tamplate_name', 'new_customer_payment_sms')->first()->tamplate_body;
        } elseif ($type == 2) {
            $body = getSmsMessage()->where('tamplate_name', 'otc_payment_sms')->first()->tamplate_body;
        } elseif ($type == 3) {
            $body = getSmsMessage()->where('tamplate_name', 'billing_cycle_change_payment_sms')->first()->tamplate_body;
        } elseif ($type == 4) {
            $body = getSmsMessage()->where('tamplate_name', 'package_change_payment_sms')->first()->tamplate_body;
        } elseif ($type == 5) {
            $body = getSmsMessage()->where('tamplate_name', 'bill_payment')->first()->tamplate_body;
        } elseif ($type == 6) {
            $body = getSmsMessage()->where('tamplate_name', 'advanced_payment_sms')->first()->tamplate_body;
        }
        return $body;
    }



    public function billPaymentSms($client, $amount, $receipt_id, $payment_id, $type = null, $discount = null, $totalDue = 0, $payment_description = '', $payment_type = 5)
    {

        if(globalPermission('customResellerSmsGatewaySetup')){


            $reseller_sms_gateway = getResellerSmsGateway($client);
            if ($reseller_sms_gateway && optional($client->pop)->sms_send == 'yes') {
                $paymentSms = collect(json_decode($reseller_sms_gateway->sms_formate))->where('sms_type', 'own_reseller_customer_payment')->first();
                if ($paymentSms->send_sms == "Yes") {
                    $message = $paymentSms->sms_body;

                    $expire_date = $this->calculateExpireDate($client);

                    $message = $this->replacePlaceholders($paymentSms->sms_body, $client, $amount, $discount, $receipt_id, $payment_id, $totalDue, $payment_description, $expire_date, $type);

                    $contact = $client->clientsinfo->contact_no;

                        $data = [
                            'reseller_id' => $reseller_sms_gateway->reseller_id,
                            'contact' => $contact,
                            'message' => $message,
                            'type' => "Payment",
                            'api' => $reseller_sms_gateway->sms_gateway,

                        ];
                        ResellerSendSms::dispatch($data);
                    }
                }

        }else{

            if (useResellerSmsGatewayForOwnWhenMainEnabled($client) && optional($client->pop)->sms_send == 'yes') {
                $reseller_sms_gateway = getResellerSmsGateway($client);
                if ($reseller_sms_gateway) {
                    $paymentSms = collect(json_decode($reseller_sms_gateway->sms_formate))->where('sms_type', 'own_reseller_customer_payment')->first();
                    if ($paymentSms && $paymentSms->send_sms == "Yes") {
                        $expire_date = $this->calculateExpireDate($client);
                        $message = $this->replacePlaceholders($paymentSms->sms_body, $client, $amount, $discount, $receipt_id, $payment_id, $totalDue, $payment_description, $expire_date, $type);
                        $contact = $client->clientsinfo->contact_no;
                        if (!empty($contact)) {
                            $data = [
                                'reseller_id' => $reseller_sms_gateway->reseller_id,
                                'contact' => $contact,
                                'message' => $message,
                                'type' => "Payment",
                                'api' => $reseller_sms_gateway->sms_gateway,
                            ];
                            ResellerSendSms::dispatch($data);
                        }
                    }
                }
                return;
            }

            if ($client->pop->bill_generate == 'yes' && optional($client->pop)->sms_send == 'yes') {

                if (checkSettings('bill-payment-sms') == 'enable') {
                    $package_change_info = null;
                    $billing_change_info = null;

                    $expire_date = $this->calculateExpireDate($client);

                    if ($payment_type > 6) {
                        $payment_type = 5;
                    }
                    $message = json_decode($this->getSmsBody($payment_type))->sms_body;

                    if ($payment_type != 5) {
                        $data = json_decode($this->getSmsBody($payment_type));
                        if ($data->sendsms == 'Yes') {
                        $message = $data->sms_body;
                        } else {
                            $message = json_decode($this->getSmsBody(5))->sms_body;
                        }
                        if ($payment_type == 4) {
                            $package_change_info = CustomerPackageChangeInfo::where('client_id', $client->id)->orderBy('id', 'DESC')->first();
                        }
                        if ($payment_type == 3) {
                            $billing_change_info = CustomerBillingCycleInfo::where('client_id', $client->id)->orderBy('id', 'DESC')->first();
                        }
                    }


                    $message = $this->replacePlaceholders(
                        $message,
                        $client,
                        $amount,
                        $discount,
                        $receipt_id,
                        $payment_id,
                        $totalDue,
                        $payment_description,
                        $expire_date,
                        $type,
                        $package_change_info,
                        $billing_change_info
                    );


                    $contact = $client->clientsinfo->contact_no;

                    $data = [
                        'contact_no' => $contact,
                        'message'    => $message,
                        'type'        => 'payment'
                    ];

                    if (!empty($contact)) {

                        ExpireCustomerNotification::dispatch($data);
                    }
                }
            }
        }

    }




    private function calculateExpireDate($client)
    {
        $clientAccount = CustomerAccount::where('client_id', $client->id)->first();
        $client_package = Packages::find($client->package_id);

        if ((getBillingType() == 'day_to_day' || siteinfo()->day_to_day_after_10_days == 'Yes') && ($clientAccount->dueAmount < 0) && (abs($clientAccount->dueAmount) >= $client_package->package_rate)) {
            if(checkSettings('d2d_extend_ExpireDate_By_Month') == 'enable'){
                $total_day_of_this_month = now()->lastOfMonth()->format('d');
                return Carbon::parse($client->expire_date)->addDay($total_day_of_this_month)->format('d-m-Y');

            }else{
                return Carbon::parse($client->expire_date)->addDay(30)->format('d-m-Y');
            }

        }

        $latestClient = Client::select('expire_date')->find($client->id);

        return Carbon::parse($latestClient->expire_date)->format('d-m-Y');

    }




    private function replacePlaceholders($message, $client, $amount, $discount, $receipt_id, $payment_id, $totalDue, $payment_description, $expire_date, $type, $package_change_info = null, $billing_change_info = null)
    {
        return str_replace(
            [
                '{c_id}', '{c_code}', '{c_password}', '{c_name}', '{c_username}', '{c_expire_date}', '{c_package}', '{BTRC_speed}', '{BTRC_rate}',
                '{PaymentAmount}', '{PaymentDiscount}', '{PaymentMethod}', '{TotalDue}', '{MoneyreciptNo}',
                '{TrxId}', '{company_name}', '{company_cell}', '{payment_date}', '{payment_description}',
                '{old_package_name}', '{new_package_name}', '{old_billing_cycle}', '{new_billing_cycle}', '{current_month}', '{current_year}'
            ],
            [
                $client->id, $client->customer_code, $client->password, $client->clientsinfo->clients_name,
                $client->userid, $expire_date, $client->packages->package_name, $client->packages->package_bandwidth, $client->packages->btrc_package_price,
                $amount, $discount, $type, $totalDue, $receipt_id,
                $payment_id, siteinfo()->name, siteinfo()->mobile, Carbon::now()->format('d-m-Y'),
                $payment_description ?: Carbon::now()->format('M'),
                isset($package_change_info->previous_package_name) ? $package_change_info->previous_package_name ?? " " :  '',
                isset($package_change_info->new_package_name) ? $package_change_info->new_package_name ?? " " :  '',
                isset($billing_change_info->previous_billing_cycle) ? $billing_change_info->previous_billing_cycle ?? " " :  '',
                isset($billing_change_info->current_billing_cycle) ? $billing_change_info->current_billing_cycle ?? " " :  '',
                Carbon::now()->format('M'),
                Carbon::now()->format('Y')
            ],
            $message
        );
    }






}
