<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\DocumentType;

class DocumentTypesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:document-types-list', ['only' => ['index']]);
    }
    public function index(Request $request)
    {
        $CompanyLicenceType = DocumentType::select([
              'document_types.id',
              'document_types.country_id',
              'document_types.license_type_name',
              'document_types.license_code',
              'document_types.license_status',
              'countries.name as country'
            ])
            ->leftjoin('countries', 'countries.id', 'document_types.country_id')
            ->paginate(10);

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

            $CompanyLicenceType = DocumentType::select([
                'document_types.id',
                'document_types.country_id',
                'document_types.license_type_name',
                'document_types.license_code',
                'document_types.license_status',
                'countries.name as country'
            ])
            ->leftjoin('countries', 'countries.id', 'document_types.country_id')
            ->when(!empty($search_query), function ($query) use ($search_query)
            {
                return $query->where('document_types.license_type_name', 'like', '%'.$search_query.'%')
                    ->orWhere('document_types.license_code', 'like', '%'.$search_query.'%')
                    ->orWhere('countries.name', 'like', '%'.$search_query.'%');
            })
            ->groupBy('document_types.id')
            ->paginate($sort_by);

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

    public function create()
    {
        $countries = \DB::table('countries')->select(['id','name'])->get();

        return view('document-types.create',compact('countries'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'country_id'        =>'required',
            'license_type_name' =>'required|unique:document_types,license_type_name,NULL,id,country_id,' . $request->input('country_id'),
            'license_code'      =>'required|unique:document_types,license_code,NULL,id,country_id,' . $request->input('license_code'),
        ]);

        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();

        $type = DocumentType::create($input);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Documents Type created successfully',
                'data'    => $type
            ]);
        }
        return redirect('document-types')->with('success','Documents Type created successfully.');
    }

    public function edit($id,Request $request)
    {
        $license   = DocumentType::find($id);
        $countries = \DB::table('countries')->select(['id','name'])->get();

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

    public function update($id,Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'country_id'        =>'required',
            'license_type_name' =>'required|unique:document_types,license_type_name,'.$id.',id,country_id,' . $request->input('country_id'),
            'license_code'      =>'required|unique:document_types,license_code,'.$id.',id,country_id,' . $request->input('license_code'),
        ]);

        if ($validator->fails()) {
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

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

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

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

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

    public function delete(Request $request)
    {
       $about    = DocumentType::find($request->id);
       $about->delete();
       $Redirect = 'document-types';

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