<?php

namespace App\Http\Controllers\LicenseManagement;

use App\Http\Controllers\Controller;
use App\Models\BilingInterval;
use Illuminate\Http\Request;

class BilingIntervalsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:billing-interval-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = BilingInterval::select(
            'id',
            'biling_interval',
            'code',
            'per_year',
            'days',
            'lifetime',
        );

        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('biling_interval', 'like', '%'.$search_query.'%');
            })
            ->orderBy('id','ASC')
            ->groupBy('id')
            ->paginate($sort_by);

            return view('biling-interval.table', compact('data'));
        } else {
            $data = $data->groupBy('id')
                ->orderBy('id','ASC')
                ->paginate(10);

            return view('biling-interval.index',compact('data'));
        }
    }

    public function list(Request $request)
    {

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('biling-interval.create');
    }

    /**
     * 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(), [
            'biling_interval' => 'required|unique:biling_intervals,biling_interval,NULL,id,deleted_at,NULL',
            'per_year'        => 'required|integer|min:1|max:12',
            'days'            => 'required|integer|min:1|max:366',
        ]);

        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']);
        // $data['lifetime'] = isset($request->lifetime) ? $request->lifetime : 0;
        $data['lifetime'] = isset($request->lifetime) && $request->lifetime === 'on' ? 1 : 0;


        $data = BilingInterval::create($data);

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

        return redirect()->route('biling-interval.index')
            ->with('success', 'Biling Interval 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)
    {
        $data = BilingInterval::find($id);

        return view('biling-interval.edit', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // dd($request->all());
        $validator = \Validator::make($request->all(), [
            'biling_interval' => 'required|unique:biling_intervals,biling_interval,' . $id . ',id,deleted_at,NULL',
            'per_year'        => 'required|integer|min:1|max:12',
            'days'            => 'required|integer|min:1|max:366',
        ]);

        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['lifetime'] = isset($request->lifetime) ? $request->lifetime : 0;

        $data = BilingInterval::whereId($id)->update($data);
        $data = BilingInterval::find($id);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Biling Interval updated successfully',
                'data' => $data
            ]);
        }
        return redirect()->route('biling-interval.index')
            ->with('success', 'Biling Interval updated successfully');
    }

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

        BilingInterval::find($request->id)->delete();

        $Redirect = 'biling-interval';

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

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