<?php

namespace App\Http\Controllers\Product;

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

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

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

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

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

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

        return view('business-divisions.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',
            'code'            => 'required|unique:business_divisions,code',
            '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'
        ]);

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

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

        $division = BusinessDivision::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Business Division has been created successfully',
                'data' => $division,
            ]);
        }

        return redirect()->back()
            ->with('success','Business Division has been created successfully');
    }

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

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

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

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

    public function changeStatus(Request $request)
    {
       if ($request->ajax())
       {
           $data = array('status' => $request->status );
           $Update = BusinessDivision::where('id', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Business Division Status status successfully change'],
                   'data'=>[
                       'redirect'=>'/buckets/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Tax Status for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
    }
}
