<?php

namespace App\Http\Controllers\Admin;

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

class LevelController extends Controller
{
    public function all()
    {
        $pageTitle = "Levels";
        $levels  = Level::orderBy('min_points', 'asc')->get();
        return view('admin.rewards.levels.list', compact('pageTitle', 'levels'));
    }

    public function store(Request $request, $id = 0)
    {
        $request->validate([
            'name'        => 'required|string',
            'min_points'  => 'required|numeric|gt:-1',
            'max_points'  => 'required|numeric|gt:min_points',
        ]);

        if ($id) {
            $level = Level::findOrFail($id);
            $message = "Level updated successfully";
        } else {
            $level = new Level();
            $message = "Level added successfully";
        }

        $level->name        = $request->name;
        $level->min_points  = $request->min_points;
        $level->max_points  = $request->max_points;
        $level->save();

        $notify[] = ['success', $message];
        return back()->withNotify($notify);
    }

    public function status($id)
    {
        return Level::changeStatus($id);
    }
}
