<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use App\Models\ProductGroup;
use Illuminate\Http\Request;

class ProductGroupsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:product-groups-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = ProductGroup::paginate(10);

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = ProductGroup::when(!empty($search_query), function ($query) use ($search_query) {
                        return $query->where('name', 'like', '%'.$search_query.'%');
                    })
                    ->paginate($sort_by);

            return view('product-groups.table', compact('data'));
        }
        else
        {
            return view('product-groups.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = ProductGroup::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('product-groups.create',compact('priority'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:product_groups,name',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        // Thumbnail Images 
        if ($request->hasFile('thumbnail_image')) {
            $path     = "products-groups";
            $response = uploadImage($path,$request->thumbnail_image);

            if ($response['status'] == true) {
                $data['thumbnail_image'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }
        }

        // Banner Images 
        if ($request->hasFile('banner_image')) {
            $path     = "products-groups";
            $response = uploadImage($path,$request->banner_image);

            if ($response['status'] == true) {
                $data['banner_image'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }
        }

        $default_check = ProductGroup::where(['is_default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['is_default'] = 1;
        }

        $category = ProductGroup::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product Category has been created successfully',
                'data'    => $category
            ]);
        }
        return redirect()->back()
            ->with('success','Product Category has been created successfully');
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $category = ProductGroup::find($id);

        return view('product-groups.edit',compact('category'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:product_groups,name,'.$id,
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        // Thumbnail Images 
        if ($request->hasFile('thumbnail_image')) {
            $path     = "products-groups";
            $response = uploadImage($path,$request->thumbnail_image);

            if ($response['status'] == true) {
                $data['thumbnail_image'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }
        }

        // Banner Images 
        if ($request->hasFile('banner_image')) {
            $path     = "products-groups";
            $response = uploadImage($path,$request->banner_image);

            if ($response['status'] == true) {
                $data['banner_image'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }
        }

        $cate = ProductGroup::find($id);

        if (!$cate) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => "Product Category Type not found!",
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', "Product Category Type not found!");
        }

        $cate->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product Category Type has been created successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Product Category Type has been created successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = ProductGroup::find($request->id);

        if ($data->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $data->delete();

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
            ]
        ]);
    }
    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = ProductGroup::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Product Attribute Type status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

   public function changedefault(Request $request)
   {
       if ($request->ajax())
       {
            $data  = array('is_default' => $request->status );
            $count = ProductGroup::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Product Category!'],
                    'data'    => []
                ]);
            }

           $Update = ProductGroup::where('id', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Product Category default status successfully change'],
                   'data'=>[
                       'redirect'=>'/financialyear/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
   }
}

