<?php

namespace App\Classes\SMS;

use App\Http\Controllers\CompanyInfoController;
use App\Jobs\SendSmsJob;
use App\Models\Client;
use App\Models\CompanyInformation;
use Illuminate\Support\Facades\DB;


class DueCustomerSms
{
    public function sendSms($client , $message)
    {
        $company_info = siteinfo();

        $message = $message;
        // $client = Client::with('clientsinfo','pop','customerAccount')->where('id',$client_id)->first();
        $link = CompanyInfoController::baseUrl();
        $message = str_replace(
            [
                '{c_id}',
                '{c_code}',
                '{c_password}',
                '{c_username}',
                '{c_name}',
                '{c_deadline}',
                '{MonthlyBill}',
                '{TotalDue}',
                '{company_name}',
                '{company_cell}',
                '{payment_url}'
            ],
            [
                $client->id,
                $client->customer_code,
                $client->password,
                $client->userid ,
                $client->clientsinfo->clients_name,
                $client->expire_date,
                optional($client->packages)->package_rate ?? 0,
                $client->customerAccount->dueAmount ?? 0,
                $company_info->name,
                $company_info->mobile,
                $link.$client->slug
            ],
            $message
        );

        if (optional($client->pop)->sms_send == 'yes') {
            $data = [
                'message' => $message,
                'contact_no' => $client->clientsinfo->contact_no,
                'type' => 'due_customer'
            ];

            SendSmsJob::dispatch($data);
        }

    }

    public function update($client_id)
    {
        $client = Client::with('generatedBill','paymentBill')->find($client_id);

        $tatal_paid_amount = $client->paymentBill->sum('paid_amount') + $client->paymentBill->sum('discount_amount') ?? 0;
        foreach($client->generatedBill as $bill){

           DB::beginTransaction();
           try{
                if($tatal_paid_amount >= $bill->bill_amount){
                    $bill->paid_amount = $bill->bill_amount;
                    $bill->save();
                    $tatal_paid_amount = $tatal_paid_amount - $bill->bill_amount;

                }else if ($tatal_paid_amount < $bill->bill_amount && $tatal_paid_amount > 0){
                    $bill->paid_amount = $tatal_paid_amount;
                    $bill->save();
                    $tatal_paid_amount = $tatal_paid_amount - $tatal_paid_amount;
                }else{
                    $bill->paid_amount = 0;
                    $bill->save();

                }
           }catch(\Exception $e){
               DB::rollback();
               return false;
           }

        }
    }
}

