<?php

namespace App\Http\Controllers;

use App\CentralLogics\Helpers;
use Illuminate\Http\Request;
use App\Models\GeneralStore;
use App\Models\Region;
use App\Models\Zone;
use App\Models\Module;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Config;
use Rap2hpoutre\FastExcel\FastExcel;

class GeneralStoreController extends Controller
{

    public function getAll(Request $request){

        if (!$request->hasHeader('zoneId')) {
            $errors = [];
            array_push($errors, ['code' => 'zoneId', 'message' => translate('messages.zone_id_required')]);
            return response()->json([
                'errors' => $errors
            ], 403);
        }
        //if (!$request->hasHeader('moduleId')) {
        //    $errors = [];
        //    array_push($errors, ['code' => 'moduleId', 'message' => translate('messages.module_id_required')]);
        //    return response()->json([
        //        'errors' => $errors
        //    ], 403);
        //}

        //$module_id = $request->header('moduleId') ?? null;
        $zone_id = $request->header('zoneId');
        $limit = $request['limit'] ?? 10;
        $offset = $request['offset'] ?? 1;

        if($zone_id){

            $data = GeneralStore::whereIn('zone_id', json_decode($zone_id,true));
            //if(isset($module_id) && !empty($module_id)){
            //    $data = $data->where('module_id', $module_id);
            //}
            if(!empty($request->category_id) and $request->category_id != 0){
                $data = $data->where('general_store_category_id', $request->category_id);
            }
            if(!empty($request->search)){
                $data = $data->where(function($q) use ($request){
                    $q->where('name', 'LIKE', '%' . $request->search . '%')->orWhere('title', 'LIKE', '%' . $request->search . '%');
                });
            }
            $data = $data->where('is_approved', 1)->orderBy('name', 'ASC');

            if(isset($request['limit']) && isset($request['offset'])){
                $data = $data->paginate($limit, ['*'], 'page', $offset);
            }else{
                $data = $data->get();
            }

            //$data = GeneralStore::where('module_id', $module_id)
            //    ->whereIn('zone_id', json_decode($zone_id,true))
            //    //->where('zone_id', $zone_id)
            //    ->get();
            return response()->json($data);
        }else{
            return response()->json([], 401);
        }
    }

    public function getData(Request $request) {
        $module_id = $request->session()->get('dash_params')['module_id'];
        $data = GeneralStore::where('module_id',$module_id)->latest()->paginate(15);
        $module_type = 'food';
        return view('admin-views.general_store.general_stores_list', compact('data', 'module_type'));
    }

    public function export(Request $request) {
        //$module_id = $request->session()->get('dash_params')['module_id'];
        $data = GeneralStore::latest()->get(); //where('module_id',$module_id)->
        //$module_type = 'food';
        if ($request->type == 'excel') {
            return (new FastExcel(Helpers::exportGeneralStores($data)))->download('GeneralStores.xlsx');
        }elseif($request->type == 'csv') {
            return (new FastExcel(Helpers::exportGeneralStores($data)))->download('GeneralStores.csv');
        }
    }


    public function index(Request $request)
    {
        $module_id = $request->session()->get('dash_params')['module_id'];
        $module = Module::where('id',$module_id)->get();
        $general_stores = GeneralStore::where('module_id',$module_id)->latest()->paginate(15);
        $zones = Zone::all();
        $module_type = 'food';
        return view('admin-views.general_store.general_stores', compact('general_stores', 'module_type', 'zones','module'));
    }
    public function create(Request $request)
    {
        $zones = Zone::all();
        $module_id = $request->session()->get('dash_params')['module_id'];
        $module = Module::where('id',$module_id)->first();

        return view('admin-views.general_store.create_general_stores', compact('zones','module'));
    }
    public function store(Request $request)
    {
        $general_stores = $request->validate([
            'name' => 'required',
            'title' => 'required',
            'personal_picture' => 'required|image',
            'cover_photo' => 'required|image',
            'module_id' => 'required',
            'general_store_category_id' => 'required',
            'zone_id' => 'sometimes',
            'latitude' => 'sometimes',
            'longitude' => 'sometimes',
        ]);
        $general_stores = new GeneralStore();
        $general_stores->name = $request->name;
        $general_stores->title = $request->title;
        $general_stores->module_id = $request->module_id;
        $general_stores->general_store_category_id = $request->general_store_category_id;
        $general_stores->zone_id = $request->zone_id;
        $general_stores->latitude = $request->latitude;
        $general_stores->longitude = $request->longitude;
        $general_stores->is_approved = $request->is_approved;
        $general_stores->menu_updated_at = $request->menu_updated_at;
        if ($request->hasFile('personal_picture')) {
            $ext = $request->file('personal_picture')->getClientOriginalExtension();
            $path = 'images/users/';
            $name = time() . '_personal_picture.' . $ext;
            $request->file('personal_picture')->move($path, $name);
            $general_stores->personal_picture = $name;
        }
        if ($request->hasFile('cover_photo')) {
            $ext2 = $request->file('cover_photo')->getClientOriginalExtension();
            $path2 = 'images/users/';
            $name2 = time() . '_cover_photo.' . $ext2;
            $request->file('cover_photo')->move($path2, $name2);
            $general_stores->cover_photo = $name2;
        }
        if ($request->hasFile('menu_photo')) {
            $ext3 = $request->file('menu_photo')->getClientOriginalExtension();
            $path3 = 'images/users/';
            $name3 = time() . '_menu_photo.' . $ext3;
            $request->file('menu_photo')->move($path3, $name3);
            $general_stores->menu_photo = $name3;
        }
        $general_stores->save();
        if ($general_stores) {
            return back();
        } else {
            return 'error';
        }
    }
    public function edit($id)
    {
        $data = GeneralStore::where('id', $id)->first();
        $module = Module::where('id',$data->module_id)->get();
        $zones = Zone::where('id',$data->zone_id)->first();
        $module_type = 'food';
        return view('admin-views.general_store.edit_general_stores', compact('data', 'module_type','module','zones'));
    }
    public function update(Request $request, $id)
    {
        $general_stores = $request->validate([
            'name' => 'required',
            'title' => 'required',
            'personal_picture' => 'nullable|image',
            'cover_photo' => 'nullable|image',
            'module_id' => 'required',
            'general_store_category_id' => 'required',
            'zone_id' => 'sometimes',
            'latitude' => 'sometimes',
            'longitude' => 'sometimes',
        ]);
        $general_stores = GeneralStore::where(['id' => $id])->first();
        $general_stores->name = $request->name;
        $general_stores->title = $request->title;
        $general_stores->module_id = $request->module_id;
        $general_stores->general_store_category_id = $request->general_store_category_id;
        $general_stores->zone_id = $request->zone_id;
        $general_stores->latitude = $request->latitude;
        $general_stores->longitude = $request->longitude;
        $general_stores->is_approved = $request->is_approved;
        $general_stores->menu_updated_at = $request->menu_updated_at;
        if ($request->hasFile('personal_picture')) {
            $ext = $request->file('personal_picture')->getClientOriginalExtension();
            $path = 'images/users/';
            $name = time() . '_personal_picture.' . $ext;
            $request->file('personal_picture')->move($path, $name);
            $general_stores->personal_picture = $name;
        }
        if ($request->hasFile('cover_photo')) {
            $ext2 = $request->file('cover_photo')->getClientOriginalExtension();
            $path2 = 'images/users/';
            $name2 = time() . '_cover_photo.' . $ext2;
            $request->file('cover_photo')->move($path2, $name2);
            $general_stores->cover_photo = $name2;
        }
        if ($request->hasFile('menu_photo')) {
            $ext3 = $request->file('menu_photo')->getClientOriginalExtension();
            $path3 = 'images/users/';
            $name3 = time() . '_menu_photo.' . $ext3;
            $request->file('menu_photo')->move($path3, $name3);
            $general_stores->menu_photo = $name3;
        }
        $general_stores->save();
        if ($general_stores) {
            return redirect()->route('general_stores_data');
        } else {
            return 'error';
        }
    }
    public function destroy($id)
    {
        $data = GeneralStore::where('id', $id)->delete();
        return redirect()->back();
    }

    public function search(Request $request){
        //$module_id = $request->session()->get('dash_params')['module_id'];
        $key = explode(' ', $request['search']);
        $GeneralStore = GeneralStore::where(function ($q) use ($key) {
            foreach ($key as $value) {
                $q->orWhere('name', 'like', "%". $value ."%")
                    ->orWhere('title', 'like', "%". $value ."%");
            }
        })
        ->get();
        return response()->json([
            'view'=>view('admin-views.general_store.partials._table',compact('GeneralStore'))->render(),
            'count'=>$GeneralStore->count()
        ]);
    }

}

