<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\CompanyLicenceType;
use App\Models\CompanyAddress;
use Illuminate\Http\Request;

class CompanyLicenseController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:company-licenses-list', ['only' => ['index']]);
    }
    public function index(Request $request)
    {
        if (!$this->modulePermissionCheck('COMPANY_LICENSES')) {
            abort(404);
        }

        $CompanyLicenceType = CompanyLicenceType::select([
              'companies_license_type.id',
              'companies_license_type.company_id',
              'companies_license_type.license_type_name',
              'companies_license_type.license_code',
              'companies_license_type.license_status',
              'companies_license_type.is_mandatory',
              'companies_license_type.priority',
              'companies_license_type.show_in_print',
              'countries.name as country'
            ])
            ->leftjoin('countries', 'countries.id', 'companies_license_type.country_id');

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

            $CompanyLicenceType = $CompanyLicenceType->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('license_type_name', 'like', '%'.$search_query.'%');
                })
                ->paginate($sort_by);

            return view('company-license.table', compact('CompanyLicenceType'));
        }
        else
        {
            $CompanyLicenceType = $CompanyLicenceType->paginate(10);

            return view('company-license.index',compact('CompanyLicenceType'));
        }
    }

    public function create()
    {
        $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 ?? '';
        $priority   = CompanyLicenceType::max('priority');
        $priority   = $priority != '' ? $priority : 0;

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

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'country_id'        =>'required',
            'license_type_name' => 'required|unique:companies_license_type,license_type_name,NULL,id,country_id,' . $request->country_id,
            'license_code'      => 'required|unique:companies_license_type,license_code,NULL,id,country_id,' . $request->country_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());
        }

        $input               = $request->all();
        $input['company_id'] = \Auth::user()->company_id ?? '';
        $input['page_position'] = 'Header';
        $input['view_priority'] = 'Top';

        CompanyLicenceType::create($input);

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

        return redirect('license')->with('success','Business Documents Type created successfully.');
    }

    public function edit($id,Request $request)
    {
        $license     = CompanyLicenceType::find($id);
        $CompanyData = Company::select(['id','name'])->latest('id')->get();

        $countries = \DB::table('countries')->select(['id','name'])->where('status', '1')->get();

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

    public function update($id,Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'country_id'        =>'required',
            'license_type_name' => 'required|unique:companies_license_type,license_type_name,'.$id.',id,country_id,' . $request->country_id,
            'license_code'      => 'required|unique:companies_license_type,license_code,'.$id.',id,country_id,' . $request->country_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());
        }

        $license    = CompanyLicenceType::find($id);
        $updateData = $request->all();
        $license->update($updateData);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Business Documents Type Update successfully',
            ]);
        }

        return redirect('license')->with('success','Business Documents Type Update successfully.');
    }

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

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

    public function delete(Request $request)
    {
       $about    = CompanyLicenceType::find($request->id);
       $about->delete();
       $Redirect = 'license';

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

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

            if($Update){
                return response()->json([
                    'success' =>true,
                    'message' =>['Company Document 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 = CompanyLicenceType::where('id', '=', $request->id)->update($data);

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