<?php

namespace App\Http\Controllers\TaxMaster;

use App\Http\Controllers\Controller;
use App\Models\Scopes\GlobalStatusScope;
use App\Models\TaxCategory;
use App\Models\TaxMaster;
use Illuminate\Http\Request;


class TaxCategoryController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:tax-category-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = TaxCategory::select([
                    'tax_categories.id',
                    'tax_categories.name',
                    'tax_categories.code',
                    'tax_categories.description',
                    'tax_categories.priority',
                    'tax_categories.default',
                    'tax_categories.status',
                ]);

        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(  'tax_categories.name', 'like', '%'.$search_query.'%')
                                ->orWhere('tax_categories.description', 'like', '%'.$search_query.'%');
                        })
                        ->withoutGlobalScope(new GlobalStatusScope)->paginate($sort_by);

            return view('tax-category.table', compact('data'));
        }
        else
        {
            $data = $data->withoutGlobalScope(new GlobalStatusScope)->paginate(10);

            return view('tax-category.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = TaxCategory::max('priority');
        $priority = $priority != '' ? $priority : 0;
        return view('tax-category.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:tax_categories',
            // 'enquiry_source_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 = TaxCategory::where(['default' => 1,'status' => 1])->first();

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

        $source = TaxCategory::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Tax Category Created successfully',
                'data'    => $source
            ]);
        }
        return redirect()->route('tax-categories.index')
            ->with('success','Tax Category 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 = TaxCategory::find($id);

        return view('tax-category.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:tax_categories,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'
        ]);

        $source = TaxCategory::find($id);

        if (!$source) {
            return redirect()->route('tax-categories.index')
                ->with('error','Tax Category not found!');
        }

        $source->update($data);

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

        return redirect()->route('tax-categories.index')
            ->with('success','Tax Category updated successfully');
    }


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

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

        $data->delete();

        $Redirect = 'tax-categories';

        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 = TaxCategory::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Tax Category 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('default' => $request->status );
            $count  = TaxCategory::where(['default' => $request->status])->count();

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

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

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