<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use App\Models\ProductAttributeType;
use Illuminate\Http\Request;
use App\Models\ProductAttribute;

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

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = ProductAttributeType::max('priority');
        $priority = $priority != '' ? $priority : 0;
        $pat      = ProductAttributeType::select('id','name')->where('status',1)->get();

        return view('product-attributes.create', compact('pat','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_attributes',

        ]);

        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'
        ]);

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

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

        $ProductAttribute = ProductAttribute::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product Attribute created successfully',
                'data'    => $ProductAttribute
            ]);
        }

        return redirect()->route('product-attributes.index')
            ->with('success', 'Product Attribute 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)
    {
        $product = ProductAttribute::find($id);
        $types   = ProductAttributeType::select('id','name')->where('status',1)->get();

        return view('product-attributes.edit', compact('product', 'types'));
    }

    /**
     * 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_attributes,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'
        ]);

        $sub = ProductAttribute::find($id);

        if (!$sub) {
            return redirect()->route('product-attributes.index')
                ->with('error','Product Attribute not found!');
        }

        $sub->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product Attribute updated successfully',
            ]);
        }

        return redirect()->route('product-attributes.index')
            ->with('success','Product Attribute updated successfully');
    }


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

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

        $data->delete();

        $Redirect = 'product-attributes-sub';

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

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Product Attribute Status successfully changed'],
                   'data'=>[
                       'redirect'=>'/buckets/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Product Attribute Status for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
    }
    public function changedefault(Request $request)
    {
        if ($request->ajax())
        {
             $data  = array('is_default' => $request->status );
             $count = ProductAttribute::where(['is_default' => $request->status])->count();

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

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

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