<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\GeneralSetting;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Toastr;
use Image;
use File;
use DB;
class GeneralSettingController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:setting-list|setting-create|setting-edit|setting-delete', ['only' => ['index','store']]);
        $this->middleware('permission:setting-create', ['only' => ['create','store']]);
        $this->middleware('permission:setting-edit', ['only' => ['edit','update']]);
        $this->middleware('permission:setting-delete', ['only' => ['destroy']]);
    }

    public function index(Request $request)
    {
        // ✅ Single record pattern: redirect directly to edit/create without listing/loop
        $setting = GeneralSetting::orderBy('id', 'desc')->first();

        if ($setting) {
            return redirect()->route('settings.edit', $setting->id);
        }

        return redirect()->route('settings.create');
    }
    public function create()
    {
        return view('backEnd.settings.create');
    }
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',

			'fraud_api_key' => 'required',
			'copyright_color' => 'required',
			'primary_color' => 'required',
			'secodery_color' => 'required',
			'footer_color' => 'required',
			'facebook_page_username' => 'required',
			
            'white_logo' => 'required',
			'og_baner' => 'required',
            'favicon' => 'required',
            'status' => 'required',
        ]);

        // image with intervention 
        $image = $request->file('white_logo');
        $name =  time().'-'.$image->getClientOriginalName();
        $name = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',$name);
        $name = strtolower(preg_replace('/\s+/', '-', $name));
        $uploadpath = 'public/uploads/settings/';
        $imageUrl = $uploadpath.$name; 
        $img=Image::make($image->getRealPath());
        $img->encode('webp', 90);
        $width = '';
        $height = '';
        $img->height() > $img->width() ? $width=null : $height=null;
        $img->resize($width, $height);
        $img->save($imageUrl);

        // dark logo
        $image2 = $request->file('dark_logo');
        $name2 =  time().'-'.$image2->getClientOriginalName();
        $name2 = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',$name2);
        $name2 = strtolower(preg_replace('/\s+/', '-', $name2));
        $uploadpath2 = 'public/uploads/settings/';
        $image2Url = $uploadpath2.$name2; 
        $img2=Image::make($image2->getRealPath());
        $img2->encode('webp', 90);
        $width2 = '';
        $height2 = '';
        $img2->height() > $img2->width() ? $width2=null : $height2=null;
        $img2->resize($width2, $height2);
        $img2->save($image2Url);

        // OG Baner
        $image4 = $request->file('og_baner');
        $name4 =  time().'-'.$image4->getClientOriginalName();
        $name4 = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',$name4);
        $name4 = strtolower(preg_replace('/\s+/', '-', $name4));
        $uploadpath4 = 'public/uploads/settings/';
        $image4Url = $uploadpath4.$name4; 
        $img4=Image::make($image4->getRealPath());
        $img4->encode('webp', 90);
        $width4 = '';
        $height4 = '';
        $img4->height() > $img4->width() ? $width4=null : $height4=null;
        $img4->resize($width4, $height4);
        $img4->save($image4Url);


        // image with intervention 
        $image3 = $request->file('favicon');
        $name3 =  time().'-'.$image3->getClientOriginalName();
        $name3 = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.png',$name3);
        $name3 = strtolower(preg_replace('/\s+/', '-', $name3));
        $uploadpath3 = 'public/uploads/settings/';
        $image3Url = $uploadpath3.$name3; 
        $img3=Image::make($image3->getRealPath());
        //$img3->encode('webp', 90);
        $width3 = 256;
        $height3 = 256;
        //$img3->height() > $img3->width() ? $width3=null : $height3=null;
        //$img3->resize($width3, $height3);
        $img3->save($image3Url);

        $input = $request->all();
        $input['white_logo'] = $imageUrl;
        $input['dark_logo'] = $image2Url;
        $input['favicon'] = $image3Url;
		 $input['og_baner'] = $image4Url;
        
        $input['vendor_enabled'] = $request->has('vendor_enabled') ? 1 : 0;
        $input['reseller_enabled'] = $request->has('reseller_enabled') ? 1 : 0;
        
        GeneralSetting::create($input);
        Toastr::success('Success','Data insert successfully');
        return redirect()->route('settings.index');
    }
    
    public function edit($id)
    {
        $edit_data = GeneralSetting::find($id);
        return view('backEnd.settings.edit',compact('edit_data'));
    }
    
    public function update(Request $request)
    {
        $this->validate($request, [
            'name' => 'required'
        ]);
        $update_data = GeneralSetting::find($request->id);
        $input = $request->all();
        // new white logo
        $image = $request->file('white_logo');
        if($image){
            // image with intervention 
            $image = $request->file('white_logo');
            $name =  time().'-'.$image->getClientOriginalName();
            $name = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',$name);
            $name = strtolower(preg_replace('/\s+/', '-', $name));
            $uploadpath = 'public/uploads/settings/';
            $imageUrl = $uploadpath.$name; 
            $img=Image::make($image->getRealPath());
            $img->encode('webp', 90);
            $width = '';
            $height = '';
            $img->height() > $img->width() ? $width=null : $height=null;
            $img->resize($width, $height);
            $img->save($imageUrl);
            $input['white_logo'] = $imageUrl;
        }else{
            $input['white_logo'] = $update_data->white_logo;
        }
        // new dark logo
        $image2 = $request->file('dark_logo');
        if($image2){
            // image with intervention 
            $image2 = $request->file('dark_logo');
            $name2 =  time().'-'.$image2->getClientOriginalName();
            $name2 = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',$name2);
            $name2 = strtolower(preg_replace('/\s+/', '-', $name2));
            $uploadpath2 = 'public/uploads/settings/';
            $image2Url = $uploadpath2.$name2; 
            $img2=Image::make($image2->getRealPath());
            $img2->encode('webp', 90);
            $width2 = '';
            $height2 = '';
            $img2->height() > $img2->width() ? $width2=null : $height2=null;
            $img2->resize($width2, $height2);
            $img2->save($image2Url);
            $input['dark_logo'] = $image2Url;
        }else{
            $input['dark_logo'] = $update_data->dark_logo;
        }

			// new OG image
        $image4 = $request->file('og_baner');
        if($image4){
            $image4 = $request->file('og_baner');
            $name4 =  time().'-'.$image4->getClientOriginalName();
            $name4 = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',$name4);
            $name4 = strtolower(preg_replace('/\s+/', '-', $name4));
            $uploadpath4 = 'public/uploads/settings/';
            $image4Url = $uploadpath4.$name4; 
            $img4=Image::make($image4->getRealPath());
            $img4->encode('webp', 90);
            $width4 = 1440;
            $height4 = 793;
            $img4->height() > $img4->width() ? $width4=null : $height4=null;
            $img4->resize($width4, $height4);
            $img4->save($image4Url);
            $input['og_baner'] = $image4Url;
        }else{
            $input['og_baner'] = $update_data->og_baner;
        }




        // new favicon image
        $image3 = $request->file('favicon');
        if($image3){
            $image3 = $request->file('favicon');
            $name3 =  time().'-'.$image3->getClientOriginalName();
            $name3 = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',$name3);
            $name3 = strtolower(preg_replace('/\s+/', '-', $name3));
            $uploadpath3 = 'public/uploads/settings/';
            $image3Url = $uploadpath3.$name3; 
            $img3=Image::make($image3->getRealPath());
            $img3->encode('webp', 90);
            $width3 = 32;
            $height3 = 32;
            //$img3->height() > $img3->width() ? $width3=null : $height3=null;
            $img3->resize($width3, $height3);
            $img3->save($image3Url);
            $input['favicon'] = $image3Url;
        }else{
            $input['favicon'] = $update_data->favicon;
        }
        $input['status'] = 1;
        
        // Handle vendor_enabled and reseller_enabled (checkbox returns '1' if checked, null if unchecked)
        $input['vendor_enabled'] = $request->has('vendor_enabled') ? 1 : 0;
        $input['reseller_enabled'] = $request->has('reseller_enabled') ? 1 : 0;
        
        $update_data->update($input);

        Cache::forget('general_setting');
        Cache::forget('frontend_homepage_v1');
        Cache::forget('side_categories');
        Cache::forget('menu_categories');
        Cache::forget('brands_list');
        Cache::forget('pages_top');
        Cache::forget('pages_right');
        Cache::forget('common_menu');

        Toastr::success('Settings updated successfully!', 'Success');
        return redirect()->route('settings.edit', $update_data->id);
    }
 
    public function inactive(Request $request)
    {
        $inactive = GeneralSetting::find($request->hidden_id);
        $inactive->status = 0;
        $inactive->save();
        Toastr::success('Success','Data inactive successfully');
        return redirect()->back();
    }
    public function active(Request $request)
    {
        $active = GeneralSetting::find($request->hidden_id);
        $active->status = 1;
        $active->save();
        Toastr::success('Success','Data active successfully');
        return redirect()->back();
    }
    public function destroy(Request $request)
    {
        $delete_data = GeneralSetting::find($request->hidden_id);
        File::delete($delete_data->image);
        $delete_data->delete();
        Toastr::success('Success','Data delete successfully');
        return redirect()->back();
    }

    public function heroSection()
    {
        $gs = GeneralSetting::where('status', 1)->first();
        return view('backEnd.landing.hero-section', compact('gs'));
    }

    public function heroSectionUpdate(Request $request)
    {
        $request->validate([
            'hero_badge_text'   => 'nullable|string|max:255',
            'hero_heading_1'    => 'nullable|string|max:255',
            'hero_heading_2'    => 'nullable|string|max:255',
            'hero_description'  => 'nullable|string',
            'hero_image'        => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
            'hero_price_badge'  => 'nullable|string|max:255',
            'hero_feature_1'    => 'nullable|string|max:255',
            'hero_feature_2'    => 'nullable|string|max:255',
            'hero_feature_3'    => 'nullable|string|max:255',
            'hero_feature_4'    => 'nullable|string|max:255',
            'hero_product_tag_1'=> 'nullable|string|max:255',
            'hero_product_tag_2'=> 'nullable|string|max:255',
            'hero_delivery_1'   => 'nullable|string|max:255',
            'hero_delivery_2'   => 'nullable|string|max:255',
            'cta_heading'       => 'nullable|string|max:500',
            'cta_btn_text'      => 'nullable|string|max:255',
        ]);

        $setting = GeneralSetting::where('status', 1)->first();

        $data = $request->only([
            'hero_badge_text','hero_heading_1','hero_heading_2',
            'hero_description','hero_price_badge',
            'hero_feature_1','hero_feature_2','hero_feature_3','hero_feature_4',
            'hero_product_tag_1','hero_product_tag_2','hero_delivery_1','hero_delivery_2',
            'cta_heading','cta_btn_text',
        ]);

        if ($request->hasFile('hero_image')) {
            $image     = $request->file('hero_image');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $uploadDir = public_path('uploads/landing');
            if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);
            $image->move($uploadDir, $imageName);
            $data['hero_image'] = 'public/uploads/landing/' . $imageName;
        }

        $setting->update($data);

        Cache::forget('generalsetting_active');
        Toastr::success('Success', 'Hero section updated successfully');
        return redirect()->back();
    }

    public function whyUs()
    {
        $generalsetting = GeneralSetting::where('status', 1)->first();
        return view('backEnd.landing.why-us', compact('generalsetting'));
    }

    public function whyUsUpdate(Request $request)
    {
        $request->validate([
            'why_us_badge'        => 'nullable|string|max:255',
            'why_us_title'        => 'required|string|max:255',
            'why_us_description'  => 'nullable|string',
            'why_us_point_1'      => 'nullable|string|max:500',
            'why_us_point_2'      => 'nullable|string|max:500',
            'why_us_point_3'      => 'nullable|string|max:500',
            'why_us_video_thumbnail' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
            'why_us_video_url'    => 'nullable|string|max:500',
            'why_us_video_btn_text' => 'nullable|string|max:100',
        ]);

        $setting = GeneralSetting::where('status', 1)->first();

        $data = [
            'why_us_badge'         => $request->why_us_badge,
            'why_us_title'         => $request->why_us_title,
            'why_us_description'  => $request->why_us_description,
            'why_us_point_1'       => $request->why_us_point_1,
            'why_us_point_2'       => $request->why_us_point_2,
            'why_us_point_3'       => $request->why_us_point_3,
            'why_us_video_url'     => $request->why_us_video_url,
            'why_us_video_btn_text'=> $request->why_us_video_btn_text,
        ];

        if ($request->hasFile('why_us_video_thumbnail')) {
            $image     = $request->file('why_us_video_thumbnail');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $uploadDir = public_path('uploads/landing');
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            $image->move($uploadDir, $imageName);
            $data['why_us_video_thumbnail'] = 'public/uploads/landing/' . $imageName;
        }

        $setting->update($data);

        Cache::forget('generalsetting_active');
        Toastr::success('Success', 'Why Us section updated successfully');
        return redirect()->back();
    }

    public function warningOrderCta()
    {
        $gs = GeneralSetting::where('status', 1)->first();
        return view('backEnd.landing.warning-order-cta', compact('gs'));
    }

    public function warningOrderCtaUpdate(Request $request)
    {
        $request->validate([
            'warning_title'     => 'nullable|string|max:255',
            'warning_point_1'   => 'nullable|string|max:500',
            'warning_point_2'   => 'nullable|string|max:500',
            'warning_point_3'   => 'nullable|string|max:500',
            'order_cta_badge'   => 'nullable|string|max:255',
            'order_cta_title'   => 'nullable|string|max:255',
            'order_cta_subtitle'=> 'nullable|string|max:500',
            'order_cta_point_1' => 'nullable|string|max:500',
            'order_cta_point_2' => 'nullable|string|max:500',
        ]);

        $setting = GeneralSetting::where('status', 1)->first();
        $setting->update($request->only([
            'warning_title', 'warning_point_1', 'warning_point_2', 'warning_point_3',
            'order_cta_badge', 'order_cta_title', 'order_cta_subtitle',
            'order_cta_point_1', 'order_cta_point_2',
        ]));

        Cache::forget('generalsetting_active');
        Cache::forget('general_setting');
        \Artisan::call('cache:clear');
        Toastr::success('Success', 'Warning & Order CTA section updated successfully');
        return redirect()->back();
    }

    public function landingColors()
    {
        $gs = GeneralSetting::where('status', 1)->first();
        return view('backEnd.landing.colors', compact('gs'));
    }

    public function landingColorsUpdate(Request $request)
    {
        $request->validate([
            'landing_color_brand'          => 'nullable|string|max:20',
            'landing_color_brand_hover'    => 'nullable|string|max:20',
            'landing_color_secondary'      => 'nullable|string|max:20',
            'landing_bg_gradient'          => 'nullable|string|max:500',
            'landing_bg_gradient_1'        => 'nullable|string|max:20',
            'landing_bg_gradient_2'        => 'nullable|string|max:20',
            'landing_bg_gradient_3'        => 'nullable|string|max:20',
            'landing_card_gradient'        => 'nullable|string|max:500',
            'landing_card_gradient_1'      => 'nullable|string|max:20',
            'landing_card_gradient_2'      => 'nullable|string|max:20',
            'landing_card_gradient_3'      => 'nullable|string|max:20',
            'landing_card_border'          => 'nullable|string|max:50',
            'landing_card_inner_gradient'  => 'nullable|string|max:300',
            'landing_form_bg'              => 'nullable|string|max:20',
            'landing_form_border'           => 'nullable|string|max:20',
            'landing_form_placeholder'     => 'nullable|string|max:20',
            'landing_btn_submit'            => 'nullable|string|max:20',
            'landing_btn_yellow'           => 'nullable|string|max:20',
            'landing_badge_1'               => 'nullable|string|max:20',
            'landing_badge_2'               => 'nullable|string|max:20',
            'landing_swiper_bullet'         => 'nullable|string|max:20',
            'landing_order_section_gradient' => 'nullable|string|max:500',
        ]);

        $setting = GeneralSetting::where('status', 1)->first();
        $setting->update($request->only([
            'landing_color_brand', 'landing_color_brand_hover', 'landing_color_secondary',
            'landing_bg_gradient', 'landing_bg_gradient_1', 'landing_bg_gradient_2', 'landing_bg_gradient_3',
            'landing_card_gradient', 'landing_card_gradient_1', 'landing_card_gradient_2', 'landing_card_gradient_3',
            'landing_card_border', 'landing_card_inner_gradient',
            'landing_form_bg', 'landing_form_border', 'landing_form_placeholder',
            'landing_btn_submit', 'landing_btn_yellow',
            'landing_badge_1', 'landing_badge_2', 'landing_swiper_bullet',
            'landing_order_section_gradient'
        ]));

        Cache::forget('generalsetting_active');
        Cache::forget('general_setting');
        Toastr::success('Success', 'Landing page colors updated successfully');
        return redirect()->back();
    }
}
