<?php

namespace App\Http\Controllers\LicenseManagement;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\LicenseDetail;
use App\Models\LicenseRegistered;
use App\Models\BilingInterval;
use App\Models\LicenseActivationHistory;
use App\Models\ProductPrice;
use App\Models\LicenseProduct;
use App\Models\PlaneAndPackages;
use App\Models\PlanProductMapping;
use App\Models\Product;
use App\Models\Server;

class LicenseDetailsController extends Controller
{
    // function __construct()
    // {
    //      $this->middleware('permission:license-details-list',   ['only' => ['index']]);
    //      $this->middleware('permission:license-details-create', ['only' => ['create','store']]);
    //      $this->middleware('permission:license-details-edit',   ['only' => ['edit','update']]);
    //      $this->middleware('permission:license-details-delete', ['only' => ['destroy']]);
    //      $this->middleware('auth');
    // }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id = '')
    {
        $customer = LicenseRegistered::with('bill_to')->where('id',$id)->first();

        $data = LicenseDetail::with('license_registered','billing_interval')
            ->when(!empty($id), function ($query) use ($id) {
                return $query->where('order_id', $id);
            });

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

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

            return view('license-details.table', compact('data','id'));
        } else {
            // echo '<pre>';
            // print_r($data->get()->toArray());
            // echo '</pre>';
            // die();
            $data = $data->paginate(10);

            return view('license-details.index',compact('data','id','customer'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id = '')
    {
        if ($id != '') {
            $licence = LicenseRegistered::find($id);
        } else {
            $licence = LicenseRegistered::all();
        }

        $previous = LicenseDetail::where([
            'order_id' => $id,
            'type'     => 'Main',
        ])->exists();

        $products         = Product::all();
        $biling_intervals = BilingInterval::select('id','biling_interval')->get();
        $servers          = Server::select('id','server_name')->get();
        $planAndPackages  = PlaneAndPackages::select('id','plan_name')->get();

        return view('license-details.create', compact(
            'servers',
            'licence',
            'previous',
            'products',
            'biling_intervals',
            'id',
            'planAndPackages'
        ));
    }

    /**
     * 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(), [
            'order_id'            => 'required',
            'server_id'           => 'required',
            /*'front_end_url'     => 'required|url',
            'back_end_url'        => 'required|url',*/
            'plan_and_packages_id'=> 'required',
            /*'product_price_id'  => 'required',*/
            'billing_interval_id' => 'required',
            'quantity'            => 'required|numeric',
            'taxable_rate'        => 'required|numeric',
            // 'discount_type'    => 'required',
            // 'discount_value'   => 'required|numeric',
            'registration_date'   => 'required',
            'first_activation'    => 'required',
            'billing_start_date'  => 'required',
            'production'          => 'required',
        ],
        [
            'order_id.required'             => 'The license order field is required!',
            'server_id.required'            => 'The server field is required!',
            'plan_and_packages_id.required' => 'The plan and packages  field is required!',
            'billing_interval_id.required'  => 'The billing interval field is 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',
            'maintenance_mode',
            'registration_date',
            'first_activation',
            'billing_start_date',
        ]);

        $data['registration_date']  = isset($request->registration_date) && $request->registration_date   != '' ? date('Y-m-d', strtotime($request->registration_date)) : '';
        $data['first_activation']   = isset($request->first_activation) && $request->first_activation     != '' ? date('Y-m-d', strtotime($request->first_activation)) : '';
        $data['billing_start_date'] = isset($request->billing_start_date) && $request->billing_start_date != '' ? date('Y-m-d', strtotime($request->billing_start_date)) : '';

        $data['maintenance_mode'] = isset($request->maintenance_mode) && $request->maintenance_mode == 'on' ? 1 : 0;
        $data['product_token_no'] = \Str::uuid();

        $biling_interval = BilingInterval::find($request->billing_interval_id);

        if ($biling_interval) {
            if ($biling_interval->lifetime == false) {
                $registration_date = date('Y-m-d', strtotime($request->registration_date));
                $days = $biling_interval->days;

                $expiry_date = \Carbon\Carbon::parse($registration_date)->addDays($biling_interval->days)->toDateString();
            } else {
                $expiry_date = null;
            }
        } else {
            return response()->json([
                'success' => false,
                'message' => "Billing Interval is not valid!",
                'data'    => []
            ]);
        }

        $license       = LicenseDetail::whereOrderId($request->order_id)->get()->pluck('id');

        $type = LicenseDetail::create($data);

        $planAndPackages = PlanProductMapping::select('product_id')->where('plan_id',$request->plan_and_packages_id)->get();
        foreach ($planAndPackages as $list){

        $product_price = ProductPrice::where('product_id',$list->product_id)->first();
            LicenseProduct::create([
                'product_id'       => $list->product_id,
                'product_price_id' => ($product_price->id ?? ''),
                'license_id'       => $type->id,
            ]);
        }

            $history = [
                'license_id'             => $type->id,
                'last_renewal_date'      => $request->registration_date,
                'expiry_date'            => $expiry_date,
                'request_extention_date' => null,
                'remarks'                => '',
                'issued_by'              => \Auth()->id(),
            ];

            $history = LicenseActivationHistory::create($history);

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

        return redirect()->route('license-registered-details', $request->order_id)
            ->with('success','License Details created successfully');
    }



    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = LicenseDetail::with('license_registered','billing_interval')->find($id);

        if (!$data) {
            return redirect()->route('license-details.index')
                ->with('success','Invalid License Details Id');
        }

        $license_product  = LicenseProduct::where(['license_id' => $id])->get()->pluck('product_id')->toArray();

        $licence_list     = LicenseRegistered::all();
        $products         = Product::all();
        $biling_intervals = BilingInterval::select('id','biling_interval')->get();
        $servers          = Server::select('id','server_name')->get();
        $planAndPackages  = PlaneAndPackages::select('id','plan_name')->get();

        return view('license-details.edit', compact('id', 'data', 'license_product', 'licence_list','products','biling_intervals','servers','planAndPackages'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $detail = LicenseDetail::find($id);

        if (!$detail) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => 'License Details Not Found!',
                    'data'    => $type
                ]);
            }

            return redirect()->back()->with('error','License Details Not Found!');
        }

        $validator = \Validator::make($request->all(), [
            'order_id'            => 'required',
            'server_id'           => 'required',
            /*'front_end_url'       => 'required|url',
            'back_end_url'        => 'required|url',*/
            /*'product_id'          => 'required',
            'product_price_id'    => 'required',*/
            'billing_interval_id' => 'required',
            'quantity'            => 'required|numeric',
            'taxable_rate'        => 'required|numeric',
            // 'discount_type'       => 'required',
            'discount_value'      => 'required|numeric',
            'registration_date'   => 'required',
            'first_activation'    => 'required',
            'billing_start_date'  => 'required',
            'production'          => 'required',
        ],
        [
            'order_id.required'            => 'The license order field is required!',
            'server_id.required'           => 'The server field is required!',
            /*'product_id.required'          => 'The product field is required!',
            'product_price_id.required'    => 'The product field is required!',*/
            'billing_interval_id.required' => 'The billing interval field is 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',
            'maintenance_mode',
            'product_id',
            'registration_date',
            'first_activation',
            'billing_start_date',
        ]);

        $data['registration_date']  = isset($request->registration_date) && $request->registration_date != '' ? date('Y-m-d', strtotime($request->registration_date)) : '';
        $data['first_activation']   = isset($request->first_activation) && $request->first_activation != '' ? date('Y-m-d', strtotime($request->first_activation)) : '';
        $data['billing_start_date'] = isset($request->billing_start_date) && $request->billing_start_date != '' ? date('Y-m-d', strtotime($request->billing_start_date)) : '';

        $data['maintenance_mode'] = isset($request->maintenance_mode) && $request->maintenance_mode == 'on' ? 1 : 0;

        if ($request->billing_interval_id != $detail->billing_interval_id) {
            $biling_interval = BilingInterval::find($request->billing_interval_id);

            if ($biling_interval) {
                if ($biling_interval->lifetime == false) {
                    $registration_date = date('Y-m-d', strtotime($request->registration_date));
                    $days = $biling_interval->days;

                    $expiry_date = \Carbon\Carbon::parse($registration_date)->addDays($biling_interval->days)->toDateString();
                } else {
                    $expiry_date = null;
                }

                $history = LicenseActivationHistory::where(['license_id' => $id])->latest()->first();

                $history->update([
                    'last_renewal_date' => $request->registration_date,
                    'expiry_date'       => $expiry_date,
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => "Biling Interval is not valid!",
                    'data'    => []
                ]);
            }
        }

        //$license = LicenseDetail::whereOrderId($request->order_id)->get()->pluck('id');

        //$type = LicenseDetail::updateOrCreate(['order_id' => $request->order_id], $data);
        $type = $detail->update($data);

        $planAndPackages = PlanProductMapping::select('product_id')->where('plan_id', $request->plan_and_packages_id)->get();
        $test = LicenseProduct::where('license_id', $id)->delete();
        foreach ($planAndPackages as $list){
            $product_price = ProductPrice::where('product_id', $list->product_id)->first();
            LicenseProduct::updateOrCreate([
                'product_id' => $list->product_id,
                'license_id' => $id,
            ], [
                'product_price_id' => ($product_price->id ?? ''),
            ]);
        }

        $history = [
            'license_id'             => $id,
            'last_renewal_date'      => $request->registration_date,
            // 'expiry_date'            => $expiry_date,
            'request_extention_date' => null,
            'remarks'                => '',
            'issued_by'              => \Auth()->id(),
        ];

        $history = LicenseActivationHistory::updateOrCreate(['license_id' => $id], $history);


        $detail->update($data);

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

        return redirect()->route('license-details.index')
            ->with('success','License Details updated successfully');
    }

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

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

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

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

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

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

    public function activationHistory(Request $request, $id)
    {
        $data = LicenseDetail::with('license_registered','billing_interval')->find($id);

        if (!$data) {
            return redirect()->route('license-details.index')
                ->with('success','Invalid License Details Id');
        }

        $history = LicenseActivationHistory::where(['license_id' => $id])->with('issuedBy');

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

            $history = $history->paginate($sort_by);

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

            return view('license-activation-history.index',compact('data','history'));
        }

        return view('license-activation-history.index', compact('id', 'data', 'history'));
    }
}
