<?php

namespace App\Http\Controllers\Accounts;

use App\Http\Controllers\Controller;
use App\Models\MasterType;
use Illuminate\Http\Request;
use App\Models\MasterCategory;

class MasterCategoriesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:account-master-category-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (!$this->modulePermissionCheck('ACCOUNT_CATEGORY')) {
            abort(404);
        }

        $data = MasterCategory::query()->paginate(10);

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $types = MasterType::select(['id','type_name'])->get();

        return view('master-categories.create', compact('types'));
    }

    /**
     * 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(), [
            'category_name'   => 'required|unique:account_categories|max:30',
            'category_code'   => 'required|max:30',
            'category_code'   => 'required|max:30',
            'prefix'          => 'required|max:15',
            'account_type_id' => '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['category_code'] = strtoupper($data['category_code']);
        $data['prefix']        = strtoupper($data['prefix']);

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

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

        $type = MasterCategory::create($data);

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

        return redirect()->route('account-categories.index')
            ->with('success','Account 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)
    {
        $type = MasterCategory::find($id);
        $types = MasterType::select(['id','type_name'])->get();

        return view('master-categories.edit',compact('type', '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(), [
            'category_name'   => 'required|max:30|unique:account_categories,category_name,'.$id,
            'category_code'   => 'required|max:30',
            'prefix'          => 'required|max:15',
            'account_type_id' => '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['category_code'] = strtoupper($data['category_code']);
        $data['prefix']        = strtoupper($data['prefix']);

        $type = MasterCategory::find($id);

        if (!$type) {
            return redirect()->route('account-categories.index')
                ->with('error','Account Category not found!');
        }

        $type->update($data);

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

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

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

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

        $data->delete();

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

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

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

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

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