<?php



namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;

use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\Product;
use App\Models\Category;
use App\Models\ProductCategory;
use App\Models\ProductAttribute;
use App\Models\ProductImage;
use App\Models\ProductLiveStatus;
use App\Models\ProductRating;
use App\Models\PriceBrand;
use App\Models\CategoryBanner;
use App\Imports\BulkProductUploadImport;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

use File;

// use Excel;



class CategoryController extends Controller

{

	public function list(Request $request)
	{
        // if($this->checkPermission('category','list') == false  ){
        //     // dd("hello");
        //     $request->session()->flash('alert-danger', "You don't have permissions to access this page.");
        //     return redirect()->route('admin.orders');
        // }

        $where = $orWhere = [];
        $result = Category::orderBy('id', 'asc')->get();
        return view('admin.category.list', ['result' => $result, 'request' => $request]);
	}



	public function status(Request $request)

	{



        if($request->id == null || $request->status == null){

            return redirect()->route('admin.category.list');

        }

        $id = base64_decode($request->id);



        switch($request->status){

            case 'N':

                $block = 'Y';

                $blockText = 'Block';

                break;

            case 'Y':

                $block = 'N';

                $blockText = 'Unblock';

                break;

            default:

                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');

                return redirect()->back();

        }

        if(Category::where(['id' => $id])->update(['is_block' => $block])){

           

            $prompt = array('status' => 1, 'id' => $id, 'event' => $blockText);



            echo json_encode($prompt);

        }else{

            $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');

            return redirect()->back();

        }

    }

	

	public function add(Request $request)

	{

        $dataDetails  = Category::where(['is_block' => 'N', 'menu_head_only' => 'N'])->where('cat_section', '<>', 'P')->orderBy('name', 'asc')->select('name', 'id')->get();

        $obj = new Category;



        if($request->isMethod('POST')){

            

            $request->validate([

                'ctitle'=>'required | unique:mysql.categories,name',

                //'chead'=>'required',

                'cbannerhead'=>'required',

                //'ccontenttop'=>'required',

                //'ccontentbottom'=>'required',

                'cmeta_title'=>'required',

                'cmeta_description'=>'required',

                //'ctagline'=>'required',

                //'ctophead'=>'required'

            ]);



            $imageName = '';



            // $imagefile=$request->file("cimage");

            // if (isset($imagefile)){



            //     if(!is_dir(public_path() . '/uploads/banner/')){

            //         mkdir(public_path() . '/uploads/banner/', 0777, true);

            //     }



            //     $imageName = strtotime(now()).rand(11111,99999).'-banner.'.$imagefile->getClientOriginalExtension();

            //     $imagefile->move(public_path() . '/uploads/banner/', $imageName);

            // }



            if($cat = $obj->create([

                    'name' => $request->ctitle,

                    'page_head' => $request->chead, 

                    'image' => $imageName,

                    'banner_heading' => $request->cbannerhead,

                    'menu_head_only' => $request->cmenuhead,

                    'cat_section' => $request->ctype,

                    'content_top' => $request->ccontenttop,

                    'content_bottom' => $request->ccontentbottom,

                    'meta_title' => $request->cmeta_title, 

                    'meta_description' => $request->cmeta_description,

                    'tag_line' => $request->ctagline,

                    'tophead' => $request->ctophead,

                    'slug'=> str_replace(' ', '-', strtolower($request->ctitle))

            ]))

          

            {

                $id=$cat->id;

                if ($request->ctype=="P"){

                    $obj2 = new PriceBrand();

                    $obj2->category_id=$id;

                    $obj2->from_price=$request->from_price;

                    $obj2->to_price=$request->to_price;

                    $obj2->equation=$request->equation;

                    $obj2->save();

                }


                if ($request->ctype=="CP"){

                    $obj3 = new PriceBrand();
                    $obj3->category_id=$id;
                    $obj3->from_price=$request->cat_from_price;
                    $obj3->to_price=$request->cat_to_price;
                    $obj3->equation=$request->cat_equation;
                    $obj3->parent_category_id=$request->category_id;
                    $obj3->save();

                }



                $request->session()->flash('alert-success', 'Category successfully added.');

                return redirect()->route('admin.category.list');

            }else{

                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');

                return redirect()->back()->with($request->except(['_method', '_token']));

            }

            

        }

        return view('admin.category.add', ['dataDetails' => $dataDetails, 'request' => $request]);

    }



    public function edit($id = null, Request $request)

    {

        $pricedtl = $imageName = '';



        $id = decrypt($id);

        // $dataDetails  = Category::where('id',$id)->first();
        $dataDetails  = Category::where(['is_block' => 'N', 'menu_head_only' => 'N'])->where('id',$id)->first();
        $catDetails = Category::where(['is_block' => 'N', 'menu_head_only' => 'N'])->where('cat_section', '<>', 'P')->orderBy('name', 'asc')->select('name', 'id')->get();


        $dataPriceBrand = PriceBrand::where('category_id', $id)->first();



        if($dataPriceBrand){

            $pricedtl = $dataPriceBrand;

        }else{

            $pricedtl = '';

        }

        

        $obj = new Category;



        if($request->isMethod('POST')){


            //dd($request);
            $request->validate([

                'ctitle'=>'required',

                //'chead'=>'required',

                'cbannerhead'=>'required',

                //'ccontenttop'=>'required',

                //'ccontentbottom'=>'required',

                'cmeta_title'=>'required',

                'cmeta_description'=>'required',

                //'ctagline'=>'required',

                //'ctophead'=>'required',

                'cslug'=>'required'

            ]);

            

            // $imagefile=$request->file("cimage");

            // if (isset($imagefile)){

            //     unlink(public_path() . '/uploads/banner/'.$dataDetails->image);

            //     $imageName = strtotime(now()).rand(11111,99999).'-banner.'.$imagefile->getClientOriginalExtension();

            //     $imagefile->move(public_path() . '/uploads/banner/', $imageName);

            // }

            



            $formid=$request->formid;



            $update_arr['name'] = $request->ctitle;

            $update_arr['page_head'] = $request->chead;

            // if(isset($imagefile)){

            //     $update_arr['image'] = $imageName;

            // }

            $update_arr['slug'] = $request->cslug;

            $update_arr['banner_heading'] = $request->cbannerhead;

            $update_arr['menu_head_only'] = $request->cmenuhead;

            $update_arr['cat_section'] = $request->ctype;

            $update_arr['content_top'] = $request->ccontenttop;

            $update_arr['content_bottom'] = $request->ccontentbottom;

            $update_arr['meta_title'] = $request->cmeta_title;

            $update_arr['meta_description'] = $request->cmeta_description;

            $update_arr['tag_line'] = $request->ctagline;

            $update_arr['tophead'] = $request->ctophead;  

            

            $dataPriceBrandUpd= PriceBrand::where('category_id', $formid)->first();



            if ($request->ctype=="P"){

                if($dataPriceBrandUpd){

                    $dataPriceBrandUpd->from_price=$request->from_price;
                    $dataPriceBrandUpd->to_price=$request->to_price;
                    $dataPriceBrandUpd->equation=$request->equation;
                    $dataPriceBrandUpd->parent_category_id=0;
                    $dataPriceBrandUpd->update();
                }
                else{

                    $obj2 = new PriceBrand();
                    $obj2->category_id=$formid;
                    $obj2->from_price=$request->from_price;
                    $obj2->to_price=$request->to_price;
                    $obj2->equation=$request->equation;
                    $obj2->save();

                }

            }else if($request->ctype=="CP"){
                if($dataPriceBrandUpd){
                    $dataPriceBrandUpd->from_price=$request->cat_from_price;
                    $dataPriceBrandUpd->to_price=$request->cat_to_price;
                    $dataPriceBrandUpd->equation=$request->cat_equation;
                    $dataPriceBrandUpd->parent_category_id=$request->category_id;
                    $dataPriceBrandUpd->update();
                }else{

                    $obj3 = new PriceBrand();
                    $obj3->category_id=$formid;
                    $obj3->from_price=$request->cat_from_price;
                    $obj3->to_price=$request->cat_to_price;
                    $obj3->equation=$request->cat_equation;
                    $obj3->parent_category_id=$request->category_id;
                    $obj3->save();
                }
            }
            else{

                if($dataPriceBrandUpd){

                   $object=PriceBrand::where('id', $dataPriceBrandUpd->id)->delete();

                }

            }

            

            if(Category::where(['id' => $request->formid])->update($update_arr)){

                   

                $request->session()->flash('alert-success', 'Catgory successfully updated.');

                return redirect()->route('admin.category.list');

            }else{

                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');

                return redirect()->back()->with($request->except(['_method', '_token']));

            }

        }

         return view('admin.category.edit', ['dataDetails' => $dataDetails, 'request' => $request, 'pricedtl' => $pricedtl, 'catDetails' => $catDetails]);

    }



    public function delete($id = null, Request $request){

        

        if($id == null){

            return redirect()->route('admin.category.list');

        }

        $id = decrypt($id);

        $delobject=Category::where(['id'=>$id])->first();

        if($delobject->image != ''){

            unlink(public_path() . '/uploads/banner/'.$delobject->image);

        }

        

        if($delobject->cat_section == "P"){

            $priceobj = PriceBrand::where(['category_id'=>$id])->first();

            $priceobj->delete();

        }



        if( Category::where(['id' => $id])->delete()){

            CategoryBanner::where(['category_id' => $id])->delete();

            $request->session()->flash('alert-success', 'Category deleted successfully.');

            return redirect()->back();

        }else{

            $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');

            return redirect()->back();

        }

    }



    public function list_banners($id = null, Request $request){

        // if($id == null){
        //     return redirect()->route('admin.category.list');
        // }
        $id = decrypt($id);
        if ($id>0){
            $list_banners = DB:: table('sites')
                            ->join('category_banners','sites.id','=','category_banners.site_id')
                            ->where(['category_banners.category_id'=>$id])
                            ->orderBy('category_banners.site_id','asc')
                            ->get();
            // dd($list_banners);
        }

        return view('admin.category.category_banner', ['category_id' => $id, 'list_banners' => $list_banners, 'request' => $request]);
    }



    public function list_banners_add($id = null, Request $request)
    {
        $category_id = decrypt($id);
        $sites = DB::table('sites')->where('id', 8)->get();
        $obj = new CategoryBanner;

        if($request->isMethod('POST')){

            $site_id=$request->site_id;

            // dd($site_id);

            $data  = DB::table('category_banners')
                    ->where(['category_id'=>$category_id])
                    ->where(['site_id'=>$site_id])
                    ->first();
            // dd($data);
            if($data){        
                $cat_ban_id = $data->id;
                // dd($cat_ban_id);
            }else{
                $cat_ban_id = 0;
            }  

            // if ($request->post('image')) {
            //     $image_validation = "mimes:jpeg,jpg,png,webp";
            // } else {
            //     $image_validation = "required|mimes:jpeg,jpg,png,webp";
            // }

            $request->validate([
                // 'image'=>$image_validation,
                'cbannerhead'=>'required',
                'cbmeta_title'=>'required',
                'cbmeta_description'=>'required',
            ]);

            // if ($request->hasFile('image')) {
            //     if ($cat_ban_id) {
            //         $categoryImage = DB::table('category_banners')->where(['id' => $cat_ban_id])->get();

            //         $image_path = public_path('upload/category_banners/'.$categoryImage[0]->image);

            //         if(file_exists($image_path)){
            //             File::delete( $image_path);
            //         }

            //     }

            //     $image = $request->file('image');
            //     $ext = $image->extension();
            //     $image_name = time() . '.' . $ext;
            //     $request->image->move(public_path('upload/category_banners'), $image_name);
            // }


            if($cat_ban_id!=0){

                // $update_arr['image'] = $image_name;
                $update_arr['ban_head'] = $request->cbhead;
                $update_arr['banner_heading'] = $request->cbannerhead;
                $update_arr['content_top'] = $request->cbcontenttop;
                $update_arr['content_bottom'] = $request->cbcontentbottom;
                $update_arr['meta_title'] = $request->cbmeta_title;
                $update_arr['meta_description'] = $request->cbmeta_description;
                $update_arr['tag_line'] = $request->cbtagline;
                $update_arr['tophead'] = $request->cbtophead;

                // $update_arr[''] = $image_name;
                // $update_arr[''] = $image_name;

                CategoryBanner::where(['id' => $cat_ban_id])->update($update_arr);

                $request->session()->flash('alert-success', 'Category Banner successfully updated.');

                return redirect()->route('admin.category.list');

            }else{



            if($cat_ban = $obj->create([

                'category_id' => $request->category_id,
                'site_id' => $request->site_id,
                // 'image' => $image_name,
                'ban_head' => $request->cbhead, 
                'banner_heading' => $request->cbannerhead,
                'content_top' => $request->cbcontenttop,
                'content_bottom' => $request->cbcontentbottom,
                'meta_title' => $request->cbmeta_title, 
                'meta_description' => $request->cbmeta_description,
                'tag_line' => $request->cbtagline,
                'tophead' => $request->cbtophead,

            ]))

            {

                $request->session()->flash('alert-success', 'Category Banner successfully added.');
                return redirect()->route('admin.category.list');

            }else{

                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');
                return redirect()->back()->with($request->except(['_method', '_token']));
            }

        }

        }

        return view('admin.category.category_banner_add', ['category_id' => $category_id, 'sites' => $sites]);

    }



    public function list_banners_edit($id = null, Request $request){

        $id = decrypt($id);

        if ($request->post('formid')) {

            $image_validation = "mimes:jpeg,jpg,png,webp";

        } else {

            $image_validation = "required|mimes:jpeg,jpg,png,webp";

        }



        $dataDetails  = CategoryBanner::where('id',$id)->first();

        $site=DB::table('sites')->where(['id' => $dataDetails->site_id])->first();

        // dd($site);

        // dd($dataDetails);

        if($request->isMethod('POST')){



            $request->validate([

                'image'=>$image_validation,

                'images.*' => "mimes:jpeg,jpg,png,webp",

                'cbannerhead'=>'required',

                'cbmeta_title'=>'required',

                'cbmeta_description'=>'required',

            ]);

            

            $formid=$request->formid;



            // if ($formid) {

            //     $model = CategoryBanner::find($formid);

            //     // $msg = "product updated successfully";

            // } 

            // else {

            //     $model = new Product();

            //     $msg = "product created successfully";

            // }

            if ($request->hasFile('image')) {



                if ($formid) {

                    $categoryImage = DB::table('category_banners')->where(['id' => $formid])->get();

                    //dd($catImage[0]->category_image);

                    // if (Storage::exists('public/upload/category_banners/' . $categoryImage[0]->image)) {

                    //     //dd($catImage[0]->category_image);

                    //     Storage::delete('public/upload/category_banners/' . $categoryImage[0]->image);

                    // }

                    $image_path = public_path('upload/category_banners/'.$categoryImage[0]->image);



                    if(file_exists($image_path)){

                        //File::delete($image_path);

                        File::delete( $image_path);

                    }

                }

                $image = $request->file('image');

                $ext = $image->extension();

                $image_name = time() . '.' . $ext;

                // $image->storeAs('/public/upload/category_banners/', $image_name);

                $request->image->move(public_path('upload/category_banners'), $image_name);

                // $model->image = $image_name;

                $update_arr['image'] = $image_name;

            }

            // dd("hello");

            // $update_arr['image'] = $image_name;

            $update_arr['ban_head'] = $request->cbhead;

            $update_arr['banner_heading'] = $request->cbannerhead;

            $update_arr['content_top'] = $request->cbcontenttop;

            $update_arr['content_bottom'] = $request->cbcontentbottom;

            $update_arr['meta_title'] = $request->cbmeta_title;

            $update_arr['meta_description'] = $request->cbmeta_description;

            $update_arr['tag_line'] = $request->cbtagline;

            $update_arr['tophead'] = $request->cbtophead;

            

            if(CategoryBanner::where(['id' => $request->formid])->update($update_arr)){

                   

                $request->session()->flash('alert-success', 'Catgory Banner successfully updated.');

                // return redirect()->route('admin.category.list');

                return redirect()->back();

            }else{

                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');

                return redirect()->back()->with($request->except(['_method', '_token']));

            }

        }

         return view('admin.category.category_banner_edit', ['dataDetails' => $dataDetails, 'request' => $request, 'site' => $site]);

    }



    public function catbanstatus(Request $request)

    {



        if($request->id == null || $request->status == null){

            return redirect()->route('admin.category.list');

        }

        $id = base64_decode($request->id);



        switch($request->status){

            case 'N':

                $block = 'Y';

                $blockText = 'Block';

                break;

            case 'Y':

                $block = 'N';

                $blockText = 'Unblock';

                break;

            default:

                $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');

                return redirect()->back();

        }

        if(CategoryBanner::where(['id' => $id])->update(['is_block' => $block])){

           

            $prompt = array('status' => 1, 'id' => $id, 'event' => $blockText);



            echo json_encode($prompt);

        }else{

            $request->session()->flash('alert-danger', 'Sorry! There was an unexpected error. Try again!');

            return redirect()->back();

        }

    }

    public function bulkcategoryupload(Request $request)

    {
        if($request->isMethod('POST')){
            $data = $request->all();
            $value = json_decode($data['all'], true); // Convert JSON string to associative array
            
            foreach ($value as $datas) {

                $key_slug = Str::slug($datas['Name']);
                $keyword_exist = Category::where('slug', $key_slug)->first();

                if(!$keyword_exist){
                    $keyword_data = new Category;
                    $keyword_data->name = $datas['Name'];
                    $keyword_data->slug = $key_slug; //$datas['Slug'];
                    $keyword_data->image = $datas['Image'];
                    $keyword_data->image_alt = $datas['Image Alt'];
                    $keyword_data->page_head = $datas['Page Head'];
                    $keyword_data->banner_heading = $datas['Banner Heading'];
                    $keyword_data->content_top = $datas['Content Top'];
                    $keyword_data->content_bottom = $datas['Content Bottom'];
                    $keyword_data->tag_line = $datas['Tag Line'];
                    $keyword_data->tophead = $datas['Tophead'];
                    $keyword_data->sort = $datas['Sort'];
                    $keyword_data->meta_title = $datas['Meta Title'];
                    $keyword_data->meta_keyword = $datas['Meta Keyword'];
                    $keyword_data->meta_description = $datas['Meta Description'];
                    $keyword_data->save();
                }
            }
            return back()->withSuccess('Excel Imported Successfully');
        }
        return view('admin.category.bulkcategoryupload');
    }





}