<?php

namespace App\Http\Controllers\Accounts;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\AccountingType;
use App\Models\AccountingGroup;

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

        $data = AccountingGroup::select([
                'accounting_groups.id',
                'accounting_groups.name',
                'accounting_groups.code',
                'accounting_groups.is_payment_mode',
                'accounting_groups.prefix',
                'accounting_types.name as account_type',
                'accounting_groups.priority as priority',
            ])
            ->leftjoin('accounting_types','accounting_types.id','accounting_groups.accounting_type_id');

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

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

            return view('accounting-groups.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // $types = AccountingType::all();
        $types = AccountingType::select('id', 'name')->where('status', '1')->get();
        $priority = AccountingGroup::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('accounting-groups.create', compact('types','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:accounting_groups,name,NULL,id,deleted_at,NULL',
            'code'               => 'required|unique:accounting_groups,code,NULL,id,deleted_at,NULL',
            'prefix'             => 'required|max:3',
            'accounting_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['code']   = strtoupper($data['code']);
        $data['prefix'] = strtoupper($data['prefix']);

        $quality = AccountingGroup::create($data);

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

        return redirect()->route('accounting-groups.index')
            ->with('success','Accounting Group 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)
    {
        $types   = AccountingType::all();
        $subtype = AccountingGroup::find($id);

        return view('accounting-groups.edit',compact('types', 'subtype'));
    }

    /**
     * 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:accounting_groups,name,'.$id,
            'code'               => 'required|unique:accounting_groups,code,'.$id,
            'prefix'             => 'required|max:3',
            'accounting_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'
        ]);

        $subtype = AccountingGroup::find($id);

        if (!$subtype) {
            return redirect()->route('accounting-groups.index')
                ->with('error','Accounting Group not found!');
        }

        $data['code']   = strtoupper($data['code']);
        $data['prefix'] = strtoupper($data['prefix']);

        $subtype->update($data);

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

        return redirect()->route('accounting-groups.index')
            ->with('success','Accounting Group created successfully');
    }

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

        $Redirect = 'accounting-groups';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function changePaymentModeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_payment_mode' => $request->status );

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

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