<?php

namespace App\Http\Controllers\Stocks;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Stocks\StockMomentType;
use Illuminate\Validation\Rule;

class StockMomentTypeController extends Controller
{
    protected  $mainFolderName = 'stocks';

    public function index(Request $request)
    {
        $data = StockMomentType::select(['id','name','code','calculation_type','status','description']);

        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('name', 'like', '%'.$search_query.'%');
                    })
                ->paginate($sort_by);

            return view($this->mainFolderName.'.stock-moment-types.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);
            return view($this->mainFolderName.'.stock-moment-types.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = StockMomentType::max('priority');
        $priority = $priority != '' ? $priority : 0;
        return view($this->mainFolderName.'.stock-moment-types.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',
                Rule::unique('stock_moment_types', 'name')->where(function ($query) {
                    $query->whereNull('deleted_at');
                }),
            ],
             'code'=>'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['status']=1;
        $stockMomentType = StockMomentType::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Stock Moment Type has been created successfully',
                'data'    => $stockMomentType
            ]);
        }
        return redirect()->back()
            ->with('success','Stock Moment Type 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)
    {
        $stockMomentType = StockMomentType::find($id);

        return view($this->mainFolderName.'.stock-moment-types.edit',compact('stockMomentType'));
    }

    /**
     * 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:stock_moment_types,name,'.$id,
        // ]);

        $validator = \Validator::make($request->all(), [
            'name' => [
                'required',
                Rule::unique('stock_moment_types', 'name')
                    ->ignore($id) // Ignore the current record's ID
                    ->where(function ($query) {
                        $query->whereNull('deleted_at');
                    }),
            ],
            'code'=>'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'
        ]);

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

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

        $cate->update($data);

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

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

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

}
