<?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') || auth()->user()->hasRole('Reseller Technician')){
           $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();

        // Define default SMS types with their default values
        $default_sms_array = array(
            [
                'sms_type' => 'other_reseller_customer_recharge',
                'send_sms' => 'No',
                'sms_body' => 'Dear {c_name}. CID: {c_id}. Package: {BTRC_speed}MB. Month: {month}. MRC: {BTRC_rate}. Thanks for the payment.',
            ],[
                'sms_type' => 'other_reseller_customer_reminder',
                'send_sms' => 'No',
                'sms_body' => 'সম্মানিত গ্রাহক, আইডি  {c_id}. ইন্টারনেট বিল {BTRC_rate} পরিশোধের শেষ তারিখ {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} এ আপনাকে স্বাগতম। আপনার {c_id} সংরক্ষন করে রাখুন।',
            ],[
                'sms_type' => 'own_reseller_customer_create',
                'send_sms' => 'No',
                'sms_body' => 'আপনার User Id: {c_username} ও Password: {c_password} সংরক্ষন করে রাখুন।',
            ],[
                'sms_type' => 'own_reseller_customer_payment',
                'send_sms' => 'No',
                'sms_body' => 'Dear {c_name}. CID: {c_id}. Package: {BTRC_speed}MB. Month: {payment_description}. MRC: {PaymentAmount}. Thanks for the payment.',
            ],[
                'sms_type' => 'own_reseller_customer_reminder',
                'send_sms' => 'No',
                'sms_body' => 'সম্মানিত গ্রাহক, আইডি {c_id}. ইন্টারনেট বিল {BTRC_rate} পরিশোধের শেষ তারিখ {c_deadline} দয়া করে আপনার বিলটি পরিশোধ করুন।',
                'days_before' => '2',
            ],[
                'sms_type' => 'own_reseller_customer_expire',
                'send_sms' => 'No',
                'sms_body' => 'প্রিয় গ্রাহক {c_name} আপনার ইন্টারনেট বিল পরিশোধ করার সময়সীমা অতিক্রম করেছে। নিরবিচ্ছিন্ন সংযোগ পেতে বকেয়া টাকা পরিশোধ করুন।',
            ]
        );

        if($sms_getway){
            // If record exists, check and add missing SMS types
            $existing_sms_array = json_decode($sms_getway->sms_formate, true);
            $existing_types = array_column($existing_sms_array, 'sms_type');
            $needs_update = false;

            // Check each default type and add if missing
            foreach ($default_sms_array as $default_sms) {
                if (!in_array($default_sms['sms_type'], $existing_types)) {
                    $existing_sms_array[] = $default_sms;
                    $needs_update = true;
                }
            }

            // Update database if new types were added
            if ($needs_update) {
                $sms_getway->sms_formate = json_encode($existing_sms_array);
                $sms_getway->save();
            }
        }else{
            // Create new record with all default SMS types
            $sms_getway = new ResellerSmsGetway();
            $sms_getway->reseller_id = $id;
            $sms_getway->sms_formate = json_encode($default_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,
                'second_days_before' => $request->other_reseller_customer_second_reminder_day,
                'second_send_sms' => $request->other_reseller_customer_second_reminder_sms_setting,
                'second_sms_body' => $request->other_reseller_customer_second_reminder_sms_body,
            ],
            [
                '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,
                'second_days_before' => $request->customResellerSmsGatewaySetup_second_reminder_sms_day,
                'second_send_sms' => $request->customResellerSmsGatewaySetup_second_reminder_sms,
                'second_sms_body' => $request->customResellerSmsGatewaySetup_second_reminder_sms_body,
            ],[
                'type' => 'own_reseller_customer_expire',
                'setting' => $request->own_reseller_customer_expire_sms_setting,
                'body' => $request->own_reseller_customer_expire_sms_body,
            ],
        ];

        // 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'];
                }

                // Optional 2nd reminder fields for reseller reminders
                if (isset($data['second_days_before'])) {
                    $temp['second_days_before'] = $data['second_days_before'];
                }
                if (isset($data['second_send_sms'])) {
                    $temp['second_send_sms'] = $data['second_send_sms'];
                }
                if (isset($data['second_sms_body'])) {
                    $temp['second_sms_body'] = $data['second_sms_body'];
                }

                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') || auth()->user()->hasRole('Reseller Technician')){
            $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);
    }
}
