<?php

namespace App\Http\Controllers;

use App\Classes\EditLogHistory;
use App\Models\User;
use App\Models\PayButton;
use Illuminate\Http\Request;
use App\Jobs\LicenseCheckJob;
use App\Models\LicenseCheckModel;
use App\Models\CompanyInformation;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Artisan;
use Brian2694\Toastr\Toastr as ToastrToastr;
use Illuminate\Support\Facades\File;
use Dotenv\Dotenv;

class CompanyInfoController extends Controller
{

    public function __construct()
    {
        $this->middleware('permission:company_index|company_edit|company_update|company-info', ['only' => ['index', 'show']]);
        $this->middleware('permission:company_edit', ['only' => ['create', 'store']]);
        $this->middleware('permission:company_update', ['only' => ['edit', 'update']]);
    }


    public function index()
    {
        if (CompanyInformation::all()->count() == 0) {
            $setting = new CompanyInformation();
            $setting->name = "";
            $setting->email = "";
            $setting->mobile = "";
            $setting->address = "";
            $setting->sync_time_in_secconds = 300;
            $setting->max_extended_day = 30;
            $myObj[] = [
                'group_name' => "",
                'api' => "",
                'chat_id' => "",
            ];
            $setting->telegram = json_encode($myObj);
            $setting->save();
        }



        $company_info = CompanyInformation::latest()->first();

        if ($company_info->payment_button == null) {
            $image_array = [];

            if ($company_info->bkash_img != null) {

                $item = [
                    'type' => 'bkash_img',
                    'value' => $company_info->bkash_img
                ];

                array_push($image_array, $item);
            }

            if ($company_info->ssl_img != null) {

                $item = [
                    'type' => 'ssl_img',
                    'value' => $company_info->ssl_img
                ];

                array_push($image_array, $item);
            }
            if ($company_info->nagod_img != null) {

                $item = [
                    'type' => 'nagod_img',
                    'value' => $company_info->nagod_img
                ];

                array_push($image_array, $item);
            }

            // dd($image_array);
            $company_info->payment_button = json_encode($image_array);
            $company_info->save();
            $company_info = CompanyInformation::latest()->first();
        }

        $payment_button = collect(json_decode($company_info->payment_button));

        if (empty($company_info->payment_url)) {
            $company_info->payment_url = [
                'payment_url_enable' => false,
                'payment_url'           => ''
            ];
            $company_info->save();
            $company_info = CompanyInformation::latest()->first();
        }
        $customer_panel_api = '';
        if (isset($company_info->settings)) {
            $settings = json_decode($company_info->settings);
            $expire_time = explode(':', collect($settings)->where('type', 'expire_time')->first()->value);
            $billing_type = getBillingType();
            $expire_sms_send_time = $this->expire_sms_send_time($settings);
            $customer_panel_api = customer_panel_api();
        }


        // dd($billing_type);

        // dd($customer_panel_api);

        $data = [
            'data' => $company_info,
            'expire_sms_send_time' => $expire_sms_send_time ?? '11:30',
            'expire_time' => $expire_time ?? '00:00:00',
            'payment' => json_decode($company_info->payment_url),
            'users' => User::where('email', '!=', 'rokibulhasan.356@gmail.com')->where('email', '!=', 'soiket@outlook.com')->where('email', '!=', 'support@yetfix.com')->where('email', '!=', 'admin@billingfix.xyz')->get(),
            'payment_button' => $payment_button,
            'billing_type' => $billing_type ?? 'monthly',
            'customer_panel_api' => $customer_panel_api,
            'CLIENT_LICENSE_CHECK' => env('CLIENT_LICENSE_CHECK'),
            'CLIENT_LICENSE_CHECK_TIME' => env('CLIENT_LICENSE_CHECK_TIME'),
        ];


        return view('info.index', $data);
    }

    public function expire_sms_send_time($settings)
    {
        $info = collect($settings)->where('type', 'expire_sms_send_time')->first();
        if ($info) {
            return $info->value;
        } else {
            return '11:30';
        }
    }


    public function store(Request $request)
    {

        $customMessages = [
            'landing_image.image' => 'The :attribute must be an image.',
            'landing_image.mimes' => 'The :attribute must be a file of type: jpeg, png, jpg, gif.',
            'landing_image.min' => 'The image  must be at least 612kb.',
            'landing_image.max' => 'The image may not be greater than 3mb.',
        ];


        $this->validate($request, [
            'name' => 'required',
            'email' => 'required',
            'mobile' => 'required',
            'address' => 'nullable',
            'landing_image' => 'image|mimes:jpeg,png,jpg,gif|min:612|max:5120',
            'hyper_host' => 'nullable',
            'hyper_port' => 'nullable|integer|min:1|max:65535',
        ], $customMessages);





        $pattern = '/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/';

        if (!preg_match($pattern, $request->expire_sms_send_time)) {
            Toastr::error('Invalid expire sms send time format', 'Error');
            return redirect()->back();
        }

        $r = CompanyInformation::latest()->first();
        $type = 'CompanyInfo';
        $old_info = CompanyInformation::where('id', 1)->first();
        $r->fill($request->all());
        if ($request->img_url != null) {
            $fileName = $request->img_url->getClientOriginalName();
            $request->img_url->move(storage_path('app/public/company'), $fileName);
            $r->img_url = $fileName;
        }

        if ($request->qrcode != null) {
            $qrcode_file_name = time() . '.' . $request->qrcode->extension();
            $request->qrcode->move(storage_path('app/public/company'), $qrcode_file_name);
            $r->qrcode = $qrcode_file_name;
        }
        if ($request->signature != null) {
            $signature_file_name = time() . '.' . $request->signature->extension();
            $request->signature->move(storage_path('app/public/company'), $signature_file_name);
            $r->signature = $signature_file_name;
        }
        /*landing image start*/
        if ($request->landing_image != null) {
            $landingimg_file_name = time() . '.' . $request->landing_image->extension();
            $request->landing_image->move(storage_path('app/public/company'), $landingimg_file_name);
            $r->landing_image = $landingimg_file_name;
        }
        /*landing image end*/

        if (isset($request->d2dactiveday)) {
            $r->d2dactiveday = $request->d2dactiveday;
        }
        if ($request->day_to_day_after_10_days) {
            $r->day_to_day_after_10_days = $request->day_to_day_after_10_days;
        }

        $myObj = [];
        $myObj[] = [
            'group_name' => $request->telegram_group_name,
            'api' => $request->telegram_api,
            'chat_id' => $request->telegram_chat_id,
        ];
        $telegram_support = [];
        $telegram_support[] = [
            'group_name' => $request->telegram_group_name_support,
            'api' => $request->telegram_api_support,
            'chat_id' => $request->telegram_chat_id_support,
        ];
        if ($request->support_notification_telegram == 1) {
            $r->same_for_support = true;
        } else {
            $r->same_for_support = false;
        }
        $r->telegram = json_encode($myObj);
        $r->telegram_for_support = json_encode($telegram_support);
        $r->invoice_terms = $request->invoice_terms;
        $r->notification = $request->notification;
        $r->bill_by_payment_start_time = $request->bill_by_payment_start_time;

        $image_array = [];

        if ($request->bkash_img != null) {
            $temp_SN_id1 = str_pad('bkashImg', 6, '0', STR_PAD_LEFT);
            $fileName1 = $temp_SN_id1 . '.' . $request->bkash_img->extension();
            $request->bkash_img->move(storage_path('app/public/company'), $fileName1);
        }
        if ($request->ssl_img != null) {
            $temp_SN_id2 = str_pad('sslImg', 6, '0', STR_PAD_LEFT);
            $fileName2 = $temp_SN_id2 . '.' . $request->ssl_img->extension();
            $request->ssl_img->move(storage_path('app/public/company'), $fileName2);
        }
        if ($request->nagod_img != null) {
            $temp_SN_id3 = str_pad('nagodImg', 6, '0', STR_PAD_LEFT);
            $fileName3 = $temp_SN_id3 . '.' . $request->nagod_img->extension();
            $request->nagod_img->move(storage_path('app/public/company'), $fileName3);
        }


        if ($request->upay_image != null) {
            $fileName = time() . '.' . $request->upay_image->extension();
            $request->upay_image->move(storage_path('app/public/company'), $fileName);
            // dd($request->all());
        }


        $r->payment_url = json_encode([
            'payment_url_enable' => $request->payment_url_enable,
            'payment_url'       => $request->payment_url
        ]);
        // dd('coems');

        $r->online_offline_topbar = $request->online_offline_topbar;
        $r->deactive_after = $request->deactive_after;
        $r->expire_profile = $request->expire_profile;

        $r->settings = $this->settings($request, $r);

        if ($request->stock_reminder_sms_reciver_numbers != null) {
            $r->stock_reminder_contact_numbers = implode(',', $request->stock_reminder_sms_reciver_numbers);
        }



        $previous_images = collect(json_decode($r->payment_button));

        // dd($previous_images);

        if ($request->bkash_img != null || $previous_images->where('type', 'bkash_img')->first() != null) {
            $item = [
                'type' => 'bkash_img',
                'value' => $fileName1 ?? $previous_images->where('type', 'bkash_img')->first()->value
            ];

            array_push($image_array, $item);
        }

        if ($request->ssl_img != null || $previous_images->where('type', 'ssl_img')->first() != null) {
            $item = [
                'type' => 'ssl_img',
                'value' => $fileName2 ?? $previous_images->where('type', 'ssl_img')->first()->value
            ];

            array_push($image_array, $item);
        }

        if ($request->nagod_img != null || $previous_images->where('type', 'nagod_img')->first() != null) {
            $item = [
                'type' => 'nagod_img',
                'value' => $fileName3 ?? $previous_images->where('type', 'nagod_img')->first()->value
            ];

            array_push($image_array, $item);
        }

        // dd("comes");

        if ($request->upay_image != null || $previous_images->where('type', 'upay_img')->first() != null) {
            $item = [
                'type' => 'upay_img',
                'value' => $fileName ?? $previous_images->where('type', 'upay_img')->first()->value
            ];
            array_push($image_array, $item);
        }

        $r->payment_button = json_encode($image_array);
        $r->min_recharge_amount = $request->min_recharge_amount;
        $r->remote_router_port = $request->remote_router_port;
        $r->save();

        $new_info = CompanyInformation::latest()->first();
        (new EditLogHistory)->editLogSave($r, $type, $old_info, $new_info);

        Artisan::call('optimize:clear');
        // Artisan::call('optimize');

        Toastr::success('Information inserted Successfully!.', '', ["closeButton" => "true", "progressBar" => "true"]);
        return redirect()->back();
    }


    public function settings($request, $r)
    {
        // Get existing settings to preserve settings not being updated
        $existingSettings = [];
        if ($r->settings) {
            $existingSettings = json_decode($r->settings, true);
            if (!is_array($existingSettings)) {
                $existingSettings = [];
            }
        }

        // Settings to update from the form
        $updatedSettings = [
            [
                'type' => 'expire_time',
                'value' => $request->expire_hour . ':' . $request->expire_minute . ':00'
            ],
            [
                'type' => 'deactive_after',
                'value' => $request->deactive_after ?? $r->deactive_after
            ],
            [
                'type' => 'billing_type',
                'value' => $request->billing_type
            ],
            [
                'type' => 'expire_sms_send_time',
                'value' => $request->expire_sms_send_time ?? '11:30'
            ],
            [
                'type' => 'customer_panel_api',
                'value' => [
                    'customer_panel_url' => $request->customer_panel_url,
                    'customer_panel_secret' => $request->customer_panel_secret,
                    'client_license_check' => $request->client_license_check
                ]
            ]
        ];

        // Get types that are being updated
        $updatedTypes = array_column($updatedSettings, 'type');

        // Preserve existing settings that are not being updated (like voice_reminder_schedule)
        $preservedSettings = array_filter($existingSettings, function ($setting) use ($updatedTypes) {
            return isset($setting['type']) && !in_array($setting['type'], $updatedTypes);
        });

        // Merge preserved settings with updated settings
        $finalSettings = array_merge($preservedSettings, $updatedSettings);

        return json_encode(array_values($finalSettings));
    }


    public function licenseReset()
    {

        LicenseCheckModel::truncate();
        // Artisan::call('cache:clear');
        LicenseCheckJob::dispatch();

        return view('_message.licesne');
    }


    // public function paumentBtnSave(Request $request)
    // {
    //     $this->validate($request, [
    //         'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
    //         'name' => 'required'
    //     ]);

    //     $template = PayButton::where('name', $request->name)->first();
    //     if ($template) {
    //         if ($request->image != null) {
    //             $fileName = time() . '.' . $request->image->extension();
    //             $request->image->move(storage_path('app/public/payButton'), $fileName);
    //             $template->image = $fileName;
    //         }
    //         $obj[]=[
    //             'name' => 'ssl',
    //             'image' => $template->image
    //         ];
    //         dd(json_encode($obj));
    //         $template->save();
    //     } else {
    //         $new_template = new PayButton();
    //         $new_template->name = $request->name;
    //         if ($request->image != null) {
    //             $fileName = time() . '.' . $request->image->extension();
    //             $request->image->move(storage_path('app/public/payButton'), $fileName);
    //             $new_template->image = $fileName;
    //         }
    //         $new_template->save();
    //     }

    //     Toastr::success('Information inserted Successfully!.', '', ["closeButton" => "true", "progressBar" => "true"]);
    //     return redirect()->back();
    // }

    public static function baseUrl()
    {
        $base = config('app.url');
        $link = "https://$base" . '/client-payment/';

        return $link;
    }
}
