<?php

namespace App\Http\Controllers;

use App\Models\Reseller;
use App\Models\ResellerSmsGetway;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ResellerSmsGetwayController extends Controller
{
    public function smsGateway($id){

        if (!auth()->user()->hasPermissionTo('reseller-sms-getway')) {
            return redirect()->back()->with('error_message', 'Permission Error!');
        }

        if(auth()->user()->hasRole('Reseller') || auth()->user()->hasRole('Reseller Admin')){
           $reseller = Reseller::list()->pluck('id')->toArray();
              if(in_array($id,$reseller)){
              }else{
                  return redirect()->route('resellers.index')->with('error_message', 'Permission Error!');
              }
        }

        $sms_getway = ResellerSmsGetway::where('reseller_id',$id)->first();
        if($sms_getway){

        }else{
            $sms_getway = new ResellerSmsGetway();

            $sms_array =  array(
                [
                    'sms_type' => 'other_reseller_customer_recharge',
                    'send_sms' => 'No',
                    'sms_body' => 'প্রিয় গ্রাহক ({c_name}), আপনার {month} মাস পর্যন্ত বিল সঠিক ভাবে সংগৃহিত হয়েছে। {reseller_name} এর সাথে থাকার জন্য ধন্যবাদ।  যেকোনো তথ্যের জন্য যোগাযোগ {reseller_mobile} এই নাম্বারে|',
                ],[
                    'sms_type' => 'other_reseller_customer_reminder',
                    'send_sms' => 'No',
                    'sms_body' => 'সম্মানিত গ্রাহক  আপনার {c_name}। ইন্টারনেট বিল পরিশোধের শেষ তারিখ {c_expire_date} দয়া করে আপনার বিলটি পরিশোধ করুন। ',
                    'days_before' => '2',
                ],[
                    'sms_type' => 'other_reseller_customer_expire',
                    'send_sms' => 'No',
                    'sms_body' => 'প্রিয় গ্রাহক {c_name} আপনার ইন্টারনেট বিল পরিশোধ করার সময়সীমা অতিক্রম করেছে। নিরবিচ্ছিন্ন সংযোগ পেতে বকেয়া টাকা পরিশোধ করুন।',
                ],[
                    'sms_type' => 'other_reseller_customer_create',
                    'send_sms' => 'No',
                    'sms_body' => '{reseller_name} এ আপনাকে স্বাগতম। আপনার User Id: {c_username} ও Password: {c_password} সংরক্ষন করে রাখোন।',
                ],[
                    'sms_type' => 'own_reseller_customer_create',
                    'send_sms' => 'No',
                    'sms_body' => '{reseller_name} এ আপনাকে স্বাগতম। আপনার User Id: {c_username} ও Password: {c_password} সংরক্ষন করে রাখোন।',
                ],[
                    'sms_type' => 'own_reseller_customer_payment',
                    'send_sms' => 'No',
                    'sms_body' => 'প্রিয় গ্রাহক ({c_name}), CID-{c_id} আপনার বিল সঠিক ভাবে সংগৃহিত হয়েছে। সংগৃহিত টাকার পরিমান- TK {PaymentAmount} | ',
                ],[
                    'sms_type' => 'own_reseller_customer_reminder',
                    'send_sms' => 'No',
                    'sms_body' => 'সম্মানিত গ্রাহক আইডি - {c_id}. ইন্টারনেট বিল {TotalDue} পরিশোধের শেষ তারিখ {c_deadline} দয়া করে আপনার বিলটি পরিশোধ করুন। ',
                    'days_before' => '2',
                ]
            );

            $sms_getway->reseller_id = $id;
            $sms_getway->sms_formate = json_encode($sms_array);
            $sms_getway->save();
            $sms_getway = ResellerSmsGetway::where('reseller_id',$id)->first();

        }

        $sms_data = collect(json_decode($sms_getway->sms_formate));



        $data = [
            'reseller_sms_getway' => $sms_getway,
            'reseller' => Reseller::find($id),
            'sms_data' => $sms_data,
        ];

        // dd($data);

        return view('reseller.resellerSmsGetway',$data);
    }


    public function resellerSmsGatewaySave(Request $request){
        // dd($request->all());

        $sms_getway = ResellerSmsGetway::where('reseller_id',$request->reseller_id)->first();


        $newArray = [];

        // Define all possible SMS types and their corresponding request fields
        $smsSettings = [
            [
                'type' => 'other_reseller_customer_recharge',
                'setting' => $request->other_reseller_customer_recharge_sms_setting,
                'body' => $request->other_reseller_customer_recharge_sms_body,
            ],
            [
                'type' => 'other_reseller_customer_reminder',
                'setting' => $request->other_reseller_customer_reminder_sms_setting,
                'body' => $request->other_reseller_customer_reminder_sms_body,
                'days_before' => $request->other_reseller_customer_reminder_day,
            ],
            [
                'type' => 'other_reseller_customer_expire',
                'setting' => $request->other_reseller_customer_expire_sms_setting,
                'body' => $request->other_reseller_customer_expire_sms_body,
            ],
            [
                'type' => 'other_reseller_customer_create',
                'setting' => $request->other_reseller_customer_create_sms_setting,
                'body' => $request->other_reseller_customer_create_sms_body,
            ],[
                'type' => 'own_reseller_customer_create',
                'setting' => $request->customResellerSmsGatewaySetup_welcome_sms,
                'body' => $request->customResellerSmsGatewaySetup_welcome_sms_body,
            ],[
                'type' => 'own_reseller_customer_payment',
                'setting' => $request->customResellerSmsGatewaySetup_payment_sms,
                'body' => $request->customResellerSmsGatewaySetup_payment_body,
            ],[
                'type' => 'own_reseller_customer_reminder',
                'setting' => $request->customResellerSmsGatewaySetup_reminder_sms,
                'body' => $request->customResellerSmsGatewaySetup_reminder_sms_body,
                'days_before' => $request->customResellerSmsGatewaySetup_reminder_sms_day,
            ]
        ];

        // Iterate through each SMS setting and build the array if the setting is not empty
        foreach ($smsSettings as $data) {
            if (!empty($data['setting'])) {
                // Build the array for the valid SMS settings
                $temp = [
                    'sms_type' => $data['type'],
                    'send_sms' => $data['setting'],
                    'sms_body' => $data['body']
                ];

                // Add 'days_before' only for reminder SMS type
                if (isset($data['days_before'])) {
                    $temp['days_before'] = $data['days_before'];
                }

                array_push($newArray, $temp);
            }
        }

        // Retrieve old SMS format array
        $oldArray = json_decode($sms_getway->sms_formate, true);

        // Merge old and new array without duplicating existing SMS types
        foreach ($newArray as $newItem) {
            $exists = false;

            // Check if the SMS type already exists in the old array
            foreach ($oldArray as &$oldItem) {
                if ($oldItem['sms_type'] === $newItem['sms_type']) {
                    // Update the existing record with new data
                    $oldItem = array_merge($oldItem, $newItem);
                    $exists = true;
                    break;
                }
            }

            // If the SMS type does not exist, add it to the old array
            if (!$exists) {
                array_push($oldArray, $newItem);
            }
        }



        // Update the SMS format in the database
        $sms_getway->sms_formate = json_encode($oldArray);
        $sms_getway->sms_gateway = $request->gatway;
        $sms_getway->sms_balance_url = $request->sms_balance_url;

        $sms_getway->save();
        // dd($sms_getway);

        Cache::forget('getResellerSmsGateway');

        Toastr::success('Reseller SMS Getway Update Successfully');
        return redirect()->back();

    }

    public function resellerSmsBalance($id)
    {
        // dd('dkf');
        if(auth()->user()->hasRole('Reseller') || auth()->user()->hasRole('Reseller Admin')){
            $reseller = Reseller::list()->pluck('id')->toArray();
               if(in_array($id,$reseller)){
               }else{
                   return redirect()->route('resellers.index')->with('error_message', 'Permission Error!');
               }
         }
        //  dd("comes");
        $data = [

            'reseller' => Reseller::find($id),

        ];

        return view('reseller.resellerSmsBalance',$data);
    }
}
