<?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_rating'       => 'nullable|string|max:100',
            'hero_customers'    => 'nullable|string|max:100',
            '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_rating','hero_customers',
            '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);

        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_title'        => 'required|string|max:255',
            '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_title'         => $request->why_us_title,
            '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);

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