<?php

namespace App\Http\Controllers\Accounts;

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

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

        $data = LicenseType::orderBy('priority', 'ASC')->with('country')->paginate(10);

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

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

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

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

        $countries = \DB::table('countries')->select(['id','name'])->where('status', '1')->get();
        $company_id      = \Auth::user()->company_id ?? '';
        $company_address = CompanyAddress::select([
                                'companies_addresses.country_id',
                            ])
                            ->leftjoin('companies', 'companies.id', 'companies_addresses.company_id')
                            ->where('company_id', $company_id)
                            ->orWhere('companies.is_default', '1')
                            ->first();

        $country_id = $company_address->country_id ?? '';

        return view('license-types.create', compact('priority','country_id','countries'));
    }

    /**
     * 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:license_types',
            'code'     => 'required|unique:license_types',
            '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'
        ]);

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

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

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

        return redirect()->route('license-types.index')
            ->with('success','License 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)
    {
        $type      = LicenseType::find($id);
        $countries = \DB::table('countries')->select(['id','name'])->where('status', '1')->get();

        return view('license-types.edit',compact('type','countries'));
    }

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

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

        if (!$type) {
            return redirect()->route('license-types.index')
                ->with('error','License Type not found!');
        }
        $data['code'] = strtoupper($data['code']);

        $type->update($data);

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

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

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

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

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

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

            if($Update){
                return response()->json([
                    'success' =>true,
                    'message' =>['License Type is mandatory status successfully change'],
                    'data'    =>[
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success' =>false,
                   'message' =>['Error for change status'],
                   'data'    =>[
                   ]
                ]);
            }
        }
    }
    public function changeShowPrint(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('show_in_print' => $request->status );
            $Update = LicenseType::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success' =>true,
                    'message' =>['License Type Show In Print status successfully change'],
                    'data'    =>[
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success' =>false,
                   'message' =>['Error for change status'],
                   'data'    =>[
                   ]
                ]);
            }
        }
    }

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

            $data = MasterType::select([
                'account_types.id',
                'account_types.type_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.account_type_id','account_types.id')
                    ->where('account_type_license_settings.license_id', $type);
            })
            ->get();

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