<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\CompanyLicenceType;
use Illuminate\Http\Request;
use App\Models\DocumentType;
use App\Models\CompanyLicence;
use Illuminate\Support\Facades\Storage;

class CompanyDocumentsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:company-documents-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //CompanyLicence
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        $types = CompanyLicenceType::select(['id','license_type_name'])
            ->where('license_status', 1)
            ->orWhere('country_id', \Auth::user()->company_id)
            ->get();

        return view('company-documents.create', compact('id','types'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // dd($request->all());
        $validator = \Validator::make($request->all(), [
            'license_type_id' => 'required',
            'company_id'      => 'required',
            // 'attachment'      => 'required',
            'license_number'  => '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',
            'attachment',
        ]);

        if ($request->hasFile('attachment')) {
            $path     = "company-documents";
            $response = uploadImage($path,$request->attachment);

            if ($response['status'] == true) {
                $data['attachment'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }
        }

        $data['valid_from'] = $request->valid_from != '' && $request->valid_from != '0000-00-00' &&  $request->valid_from != Null ? date('Y-m-d', strtotime($request->valid_from)) : null;
        $data['valid_upto'] = $request->valid_upto != '' && $request->valid_upto != '0000-00-00' &&  $request->valid_upto != Null ? date('Y-m-d', strtotime($request->valid_upto)) : null;

        CompanyLicence::create($data);

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

        return redirect()->back()
            ->with('success','Company Licence has been 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)
    {
        $license = CompanyLicence::find($id);
        $types   = CompanyLicenceType::select(['id','license_type_name'])->where('license_status', 1)->get();

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

    /**
     * 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(), [
            'license_type_id' => 'required',
            'license_number'  => 'required',
            // 'attachment'      => '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',
            'attachment',
        ]);

        $data['valid_from'] = $request->valid_from != '' ? date('Y-m-d', strtotime($request->valid_from)) : '';
        $data['valid_upto'] = $request->valid_upto != '' ? date('Y-m-d', strtotime($request->valid_upto)) : '';

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

        if (!$type) {
            return redirect()->back()
                ->with('error','Company License not found!');
        }

        if ($request->hasFile('attachment')) {
            $path               = "company-documents";
            $response = uploadImage($path,$request->attachment);

            if ($response['status'] == true) {
                $data['attachment'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }
        }

        $type->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Company Licence has been updated successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Company Licence has been updated successfully');
    }

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

        $Redirect = 'accounts';

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

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

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