<?php

namespace App\Http\Controllers\LicenseManagement;

use App\Http\Controllers\Controller;
use App\Models\ClientLicense;
use App\Models\ClientLicenseValidity;
use Illuminate\Http\Request;

class ClientLicenseDetailsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:client-license-validity-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = ClientLicenseValidity::select([
            'id',
            'license_id',
            'activation_date',
            'valid_upto',
            'grace_period',
            'payment_status',
            'status'
        ])
            ->with('getLisence')
            ->paginate(10);

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

            $data = ClientLicenseValidity::when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('user_licenses.id', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $ClientLicense = ClientLicense::select('id','license_key')->get();
        return view('user-license-validity.create',compact('ClientLicense'));
    }

    /**
     * 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(), [

        ]);

        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['activation_date'] = $request->activation_date != '' ? date('Y-m-d', strtotime($request->activation_date)) : '';
        $data['valid_upto'] = $request->valid_upto != '' ? date('Y-m-d', strtotime($request->valid_upto)) : '';
        $data['grace_period'] = $request->grace_period != '' ? date('Y-m-d', strtotime($request->grace_period)) : '';
        ClientLicenseValidity::create($data);
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'User License created successfully',
            ]);
        }

        return redirect()->route('user-license-validity.index')
            ->with('success','User License 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)
    {
        $ClientLicense = ClientLicense::select('id','license_key')->get();
        $user_license_validity = ClientLicenseValidity::find($id);

        return view('user-license-validity.edit',compact('user_license_validity','ClientLicense'));
    }

    /**
     * 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(), [

        ]);

        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['activation_date'] = $request->activation_date != '' ? date('Y-m-d', strtotime($request->activation_date)) : '';
        $data['valid_upto'] = $request->valid_upto != '' ? date('Y-m-d', strtotime($request->valid_upto)) : '';
        $data['grace_period'] = $request->grace_period != '' ? date('Y-m-d', strtotime($request->grace_period)) : '';
        $source = ClientLicenseValidity::find($id);

        if (!$source) {
            return redirect()->route('user-license-validity.index')
                ->with('error','User License not found!');
        }

        $source->update($data);

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

        return redirect()->route('user-license-validity.index')
            ->with('success','User License updated successfully');
    }

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

        $Redirect = 'user-license-validity';

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

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

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

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

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

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