<?php

namespace App\Http\Controllers\LicenseManagement;

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

class ClientLicenseController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:client-license-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = ClientLicense::select([
            'id',
            'unique_client_code',
            'client_mail_id',
            'product_code',
            'license_no',
            'license_key',
            'registration_date',
            'status'
        ])
            ->with('getProductCode')
            ->paginate(10);

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

            $data = ClientLicense::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.table', compact('data'));
        }
        else
        {
            return view('user-license.index',compact('data'));
        }
    }

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

    /**
     * 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(), [
            'unique_client_code'  => 'required',
            'client_mail_id'      => 'required',
            'product_code'        => 'required',
            'license_no'          => 'required',
            'license_key'         => 'required',
            'registration_date'   => '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['registration_date'] = $request->registration_date != '' ? date('Y-m-d', strtotime($request->registration_date)) : '';
        ClientLicense::create($data);

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

        return redirect()->route('user-license.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)
    {
        $product_code = Product::select('id','shortcode')->get();
        $user_license = ClientLicense::find($id);

        return view('user-license.edit',compact('user_license','product_code'));
    }

    /**
     * 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(), [
            'unique_client_code'  => 'required',
            'client_mail_id'      => 'required',
            'product_code'        => 'required',
            'license_no'          => 'required',
            'license_key'         => 'required',
            'registration_date'   => '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['registration_date'] = $request->registration_date != '' ? date('Y-m-d', strtotime($request->registration_date)) : '';
        $source = ClientLicense::find($id);

        if (!$source) {
            return redirect()->route('user-license.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.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)
    {
        ClientLicense::find($request->id)->delete();

        $Redirect = 'user-license';

        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 = ClientLicense::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 = ClientLicense::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 = ClientLicense::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'=>'',
                   ]
                ]);
            }
        }
    }
}
