<?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\Site;
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\HomeFeatureManagement;
use App\Models\HomePageProduct;
use App\Imports\BulkProductUploadImport;

// use Excel;



class HomeFeatureManagementController extends Controller

{
	public function list($id=null, Request $request)
	{
        $site_id = $id;
        $category = DB::table('categories')->where('is_block','N')->get();
        $result = HomeFeatureManagement::where('site_id', $site_id)->orderBy('sort', 'asc')->get();
        $site = Site::all();
        return view('admin.homefeaturemanagement.list', ['site' => $site, 'result' => $result, 'category' => $category, 'request' => $request, 'site_id' => $site_id]);
	}

    public function add($id=null, Request $request)
    {
        $site_id = $id;
        $obj = new HomeFeatureManagement;
        $category = DB::table('categories')->where('is_block','N')->get();

        if($request->isMethod('POST')){
            
            $request->validate([
                'title'=>'required',
                // 'description'=>'required',
                'category'=>'required',
                'data_limit'=>'required',
                // 'sort'=>'required'
            ]);
            
            $homepage = $obj->create([
                    'title' => $request->title, 
                    'description' => $request->description, 
                    'slug' => $request->slug,
                    'site_id' => $site_id, 
                    'category_id' => $request->category, 
                    'data_limit' => $request->data_limit,
                    'sort' => $request->sort
            ]);
            if($homepage)
            {
                if((isset($request->product_id) && count($request->product_id)>0) && $homepage){
                    foreach($request->product_id as $pid){
                        $home_page_categories['cat_id'] = $request->category;
                        $home_page_categories['site_id'] = $request->site_id;
                        $home_page_categories['product_id'] = $pid;
                        HomePageProduct::create($home_page_categories);
                    }
                }
                $request->session()->flash('alert-success', 'HomePageFeatureProduct successfully added.');
                // return redirect()->route('admin.gbg.homefeaturemanagement.list');
                return redirect()->route('admin.homefeaturemanagement.list', ['id' => $site_id]);
            }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.homefeaturemanagement.add', ['request' => $request, 'category' => $category, 'site_id' => $site_id]);
    }

    public function categoryproduct(Request $request){
        if($request->catid){
            $html = '';
            $catid = $request->catid;
            $site_id = $request->site_id;

            $getproductidfromCategory = ProductCategory::where('category_id',$catid)->get();
          

            foreach($getproductidfromCategory as $key => $getproduct){
                // $getProducts = Product::wherein('id',[$getproduct->product_id])->where(['is_block'=>'N'])->get();
                $getProducts = DB::table('products')
                               ->join('product_live_status', 'product_live_status.product_id', '=', 'products.id')
                               ->wherein('products.id',[$getproduct->product_id])
                               ->when($site_id, function($query, $site_id){
                                      if($site_id == 1){
                                            return $query->where('product_live_status.aof_is_block', 'N');
                                      } elseif($site_id == 2){
                                            return $query->where('product_live_status.bof_is_block', 'N');
                                      } elseif($site_id == 3){
                                            return $query->where('product_live_status.cof_is_block', 'N');
                                      } elseif($site_id == 4){
                                            return $query->where('product_live_status.dof_is_block', 'N');
                                      } elseif($site_id == 5){
                                            return $query->where('product_live_status.hof_is_block', 'N');
                                      } elseif($site_id == 6){
                                            return $query->where('product_live_status.kof_is_block', 'N');
                                      } elseif($site_id == 7){
                                            return $query->where('product_live_status.mof_is_block', 'N');
                                      } elseif($site_id == 8){
                                            return $query->where('product_live_status.pof_is_block', 'N');
                                      }

                                    })
                               ->select('products.id as product_id','products.product_name as product_name','products.fnid as product_fnid')
                               ->get();
                             
                foreach($getProducts as $key => $product){
                    $html .= '<option value="'.$product->product_id.'">'.$product->product_name .'('.$product->product_fnid.')'.'</option>';
                }
            }

            return json_encode(['type' => 'json', 'status' => 'success', 'data' => $html]);
            }else{
                return json_encode(['type' => 'json', 'status' => 'error']);
            }
    }

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

        $home_feature_id = $id;
        $dataDetails  = HomeFeatureManagement::where('id',$home_feature_id)->first();
        $site_id = $dataDetails->site_id;

        $product_selected = HomePageProduct::where(['cat_id' => $dataDetails->category_id, 'site_id'=>$site_id])->pluck('product_id');
        $product_selected = $product_selected->toarray();
        //dd($product_selected);
        $category = DB::table('categories')->where('is_block','N')->get();



        if($request->isMethod('POST')){
            
            $request->validate([
                'title'=>'required',
                // 'description'=>'required',
                'category'=>'required',
                'data_limit'=>'required',
                // 'sort'=>'required'
            ]);

            $category_id = HomeFeatureManagement::where('id',$home_feature_id)
                           ->get(['category_id','site_id']);
            // dd($category_id);               
            foreach($category_id as $key => $cat_id){

                $deletecategoryproduct = HomePageProduct::where(['cat_id' => $cat_id->category_id, 'site_id'=>$cat_id->site_id])
                                         ->delete();
            }
            

            $update_arr['title'] = $request->title;
            $update_arr['description'] = $request->description;
            $update_arr['slug'] = $request->slug;
            $update_arr['category_id'] = $request->category;
            // $update_arr['site_id'] = $request->site_id;
            $update_arr['data_limit'] = $request->data_limit;
            $update_arr['sort'] = $request->sort;

            if((isset($request->product_id) && count($request->product_id)>0) && $update_arr){
                foreach($request->product_id as $pid){
                    $home_page_categories['cat_id'] = $request->category;
                    $home_page_categories['site_id'] = $request->site_id;
                    $home_page_categories['product_id'] = $pid;
                    HomePageProduct::create($home_page_categories);
                }
            }
            
            if(HomeFeatureManagement::where(['id' => $request->formid])->update($update_arr)){
                   
                $request->session()->flash('alert-success', 'HomeFeatureManagement successfully updated.');

                // return redirect()->route('admin.gbg.homefeaturemanagement.list');
                return redirect()->route('admin.homefeaturemanagement.list', ['id' => $site_id]);
            }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.homefeaturemanagement.edit', ['product_selected' => $product_selected, 'dataDetails' => $dataDetails, 'category' => $category, 'request' => $request]);
    }

    public function status(Request $request)
    {
        if($request->id == null || $request->status == null){
            return redirect()->route('admin.orders');
        }
        $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(HomeFeatureManagement::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 dragproduct(Request $request){
       
        $category_id = $request->category_id;
        $site_id = $request->site_id;
        $product_id=HomePageProduct::orderBy('sort','asc')->where(['cat_id'=>$category_id, 'site_id'=>$site_id])->get();
        $html = '';
        foreach($product_id as $pid){
            $productid = $pid->product_id;
            $product_name = Product::where('id',$productid)->get(['product_name','fnid']);
            foreach($product_name as $pname){
              
                $html .= '<li class="ui-state-default homeproduct" data-id='.$productid.' data-catid = '.$category_id.' data-siteid = '.$site_id.'><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>'.$pname->product_name.'('.$pname->fnid.')</li>';
            }
        }  
       return $html;
    }

    public function sorthomepageproduct(Request $request){
        $response = json_decode($request->data);
        foreach($response as $value){
            HomePageProduct::where(['product_id' => $value->id, 'cat_id' => $value->catid, 'site_id'=>$value->siteid ])->update(['sort' => $value->position]);
        }
        return json_encode(['status' => 'success', 'msg' => 'Updated Successfully']);
    }
	

}