<?php

namespace App\Http\Controllers\Accounts;

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

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

        $data = MasterType::query()
            ->with('getAccountingCategory')
            ->with('getaccountgroup')
            ->paginate(10);

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $account_category = MasterCategory::select('id','category_name')->where('status',1)->get();
        $accounting_groups = AccountingGroup::select('id','name')->get();
        return view('master-types.create',compact('account_category','accounting_groups'));
    }

    /**
     * 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(), [
            'type_name'             => 'required|unique:account_types|max:30',
            'type_code'             => 'required|max:30',
            'accounting_group_id'   => 'required',
            'account_category_id'   => 'required',
            'prefix'                => 'required|max:15',
        ]);

        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['type_code'] = strtoupper($data['type_code']);
        $data['prefix']    = strtoupper($data['prefix']);

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

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

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

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

        return redirect()->route('account-types.index')
            ->with('success','Account Type 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)
    {
        $account_category = MasterCategory::select('id','category_name')->get();
        $accounting_groups = AccountingGroup::select('id','name')->get();
        $type = MasterType::find($id);

        return view('master-types.edit',compact('type','account_category','accounting_groups'));
    }

    /**
     * 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(), [
            'type_name'             => 'required|max:30|unique:account_types,type_name,'.$id,
            'type_code'             => 'required|max:30',
            'accounting_group_id'  => 'required',
            'account_category_id'   => 'required',
            'prefix'                => 'required|max:15',
        ]);

        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['type_code'] = strtoupper($data['type_code']);
        $data['prefix']    = strtoupper($data['prefix']);

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

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

        $type->update($data);

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

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

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

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

        $data->delete();

        $Redirect = 'account-types';

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

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

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

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Account Type Is Person successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change Is Person'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

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

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

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

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

    public function accountTypeGroups(Request $request)
    {
        if ($request->ajax()) {
            $id   = $request->selectedType ?? '';
            $type = MasterType::find($id);

            if ($type && $type->type_code != 'GENERAL') {
                $groups = AccountingGroup::where('id', $type->accounting_group_id)->get();
            } else {
                $groups = AccountingGroup::get();
            }

            return response()->json([
               'success' => true,
               'data'    => $groups,
               'name'    =>$type->type_code ?? ''
            ]);
        }
    }

    public function licenseTypesSettings(Request $request)
    {
        if ($request->ajax()) {
            $type = $request->type;

            $data = LicenseType::select([
                'license_types.id',
                'license_types.name',
                'account_type_license_settings.id as setting',
                'account_type_license_settings.is_mandatory'
            ])
            ->leftjoin('account_type_license_settings', function($query) use ($type) {
                $query->on('account_type_license_settings.license_id','license_types.id')
                    ->where('account_type_license_settings.account_type_id', $type);
            })
            ->get();

            return view('license-types.settings',compact('data','type'));
        }
    }

    public function licenseTypesSettingsPost(Request $request)
    {
        if ($request->ajax()) {
            $type     = !empty($request->type) ? $request->type : '';
            $settings = isset($request->setting) && is_array($request->setting) ? $request->setting : [];
            $licenses = [];

            foreach ($settings as $key => $value) {
                AccountTypeLicenseSetting::updateOrCreate([
                    'account_type_id' => $type,
                    'license_id'      => $key
                ],[
                    'is_mandatory' => !empty($request->is_mandatory[$key]) && $request->is_mandatory[$key] == 'on' ? '1' : '0'
                ]);
                $licenses[] = $key;
            }

            AccountTypeLicenseSetting::where('account_type_id', $type)
                ->whereNotIn('license_id', $licenses)
                ->delete();

            return response()->json([
               'success' => true,
               'message' => 'License settings updated successfully.'
            ]);
        }
    }
}
