<?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', '!=', 'limitedyetfix@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;
        }

        if ($request->multirouter_yes_message) {
            $r->multirouter_yes_message = $request->multirouter_yes_message;
        }

        if ($request->max_free_day) {
            $r->max_free_day = $request->max_free_day;
        }

        if ($request->not_coverage_message) {
            $r->not_coverage_message = $request->not_coverage_message;
        }

        if($request->new_line_save_message) {
            $r->new_line_save_message = $request->new_line_save_message;
        }

        $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 = [];

        // Payment button images (stored in CompanyInformation.payment_button JSON)
        // NOTE: We keep filename stable per gateway so it overwrites old one.
        $uploaded = [];
        $gatewayUploads = [
            // request_field => [type_in_json, filename_prefix]
            'bkash_img' => ['bkash_img', 'bkashImg'],
            'ssl_img' => ['ssl_img', 'sslImg'],
            'nagod_img' => ['nagod_img', 'nagodImg'],
            'upay_image' => ['upay_img', 'upayImg'],
            'eps_img' => ['eps_img', 'epsImg'],
            'paystation_img' => ['paystation_img', 'paystationImg'],
            'surjopay_img' => ['surjopay_img', 'surjopayImg'],
            'uddokta_img' => ['uddokta_img', 'uddoktaImg'],
        ];

        foreach ($gatewayUploads as $field => [$type, $prefix]) {
            if ($request->hasFile($field) && $request->file($field) !== null) {
                $temp = str_pad($prefix, 6, '0', STR_PAD_LEFT);
                $uploaded[$type] = $temp . '.' . $request->file($field)->extension();
                $request->file($field)->move(storage_path('app/public/company'), $uploaded[$type]);
            }
        }


        $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);

        foreach ($gatewayUploads as $field => [$type, $prefix]) {
            $prev = $previous_images->where('type', $type)->first();
            $newVal = $uploaded[$type] ?? ($prev->value ?? null);
            if ($newVal !== null) {
                $image_array[] = [
                    'type' => $type,
                    'value' => $newVal,
                ];
            }
        }

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


        $r->captive_page_title = $request->captive_page_title;
        $r->captive_page_description = $request->captive_page_description;
        $r->captive_page_technical_phone = $request->captive_page_technical_phone;
        $r->captive_page_whatsapp_phone = $request->captive_page_whatsapp_phone;

        $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 setCaptivePort(Request $request)
    {
        $company_info = CompanyInformation::latest()->first();
        $company_info->captive_page_port = $request->captive_page_port;
        $company_info->save();

        return response()->json(['message' => 'Captive page port updated successfully']);
    }

    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;
    }
}
