<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ProductAlternativeUnit;
use App\Models\PrimaryUnit;

class ProductAlternativeUnitsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:product-alternative-units-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = ProductAlternativeUnit::select([
                    'product_alternative_units.id',
                    'product_alternative_units.name',
                    'product_alternative_units.code',
                    'product_alternative_units.unit_type',
                    'product_alternative_units.description',
                    'product_alternative_units.priority',
                    'product_alternative_units.is_default',
                    'product_alternative_units.status',
                    'primary_units.name as primary_unit',
                    'primary_units.unit_type as unit_type',
                ])
                ->leftjoin('primary_units', function ($join) {
                    $join->on('primary_units.id', '=', 'product_alternative_units.primary_unit_id')
                    ->whereNull('primary_units.deleted_at');
                });

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

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

            return view('product-alternative-units.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);

            return view('product-alternative-units.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $primary_unit = PrimaryUnit::whereNull('deleted_at')->where('status',1)->get();

        $priority = ProductAlternativeUnit::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('product-alternative-units.create', compact('primary_unit','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_alternative_units,name,NULL,id,primary_unit_id,' . $request->primary_unit_id,
            'code'            => 'required|unique:product_alternative_units,code,NULL,id,primary_unit_id,' . $request->primary_unit_id,
            'primary_unit_id' => 'required',
            'priority'        => 'required',
        ]);

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

        $data['company_id'] = \Auth::user()->company_id ?? '';
        $default_check = ProductAlternativeUnit::where(['is_default' => 1,'status' => 1])->first();

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

        $unit = ProductAlternativeUnit::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product Alternative Unit has been created successfully',
                'data' => $unit,
            ]);
        }

        return redirect()->back()
            ->with('success','Product Alternative Unit 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)
    {
        $primary_unit = PrimaryUnit::whereNull('deleted_at')->where('status',1)->get();

        $alternative_unit = ProductAlternativeUnit::find($id);

        return view('product-alternative-units.edit', compact('primary_unit','alternative_unit'));
    }

    /**
     * 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_alternative_units,name,' . $id . ',id,primary_unit_id,' . $request->primary_unit_id,
            'code'            => 'required|unique:product_alternative_units,code,' . $id . ',id,primary_unit_id,' . $request->primary_unit_id,
            'primary_unit_id' => 'required',
            'priority'        => 'required',
        ]);

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

        $alternative_unit = ProductAlternativeUnit::find($id);

        if (!$alternative_unit) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => "Alternative Unit not found!",
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', "Alternative Unit not found!");
        }

        $alternative_unit->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product Alternative Unit has been created successfully',
            ]);
        }

        return redirect()->back()
            ->with('success','Product Alternative Unit has been created successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = ProductAlternativeUnit::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 = ProductAlternativeUnit::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Product Alternative Unit 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 = ProductAlternativeUnit::where(['is_default' => $request->status])->count();

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

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

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