<?php

namespace App\Http\Controllers\Admin;

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

class LevelController extends Controller
{
    public function index()
    {
        $levels = Level::paginate(getPaginate());
        $pageTitle = 'Levels';
        return view('admin.level.index', compact('levels', 'pageTitle'));
    }

    public function editCreate($id = null)
    {
        $level = Level::findorNew($id);
        return view('admin.level.form', compact('level'));
    }

    public function updateStore(Request $request, $id = null)
    {
        $validatedFields = $request->validate([
            'image' => ['nullable', 'image', new FileTypeValidate(['jpg', 'jpeg', 'png'])],
            'title' => 'required',
            'level' => 'required|integer',
            'reward_amount' => 'required|integer',
            'eligibility_duration' => 'required|integer',
        ]);

        $level = Level::findorNew($id);
        $level->fill($validatedFields);

        if ($request->hasFile('image')) {
            try {
                $old = $level->image;
                $level->image = fileUploader($request->image, getFilePath('levels'), getFileSize('levels'), $old);
            } catch (\Exception $exp) {
                $notify[] = ['error', 'Couldn\'t upload your image'];
                return back()->withNotify($notify);
            }
        }

        $level->save();

        $notify = [];
        if ($level->id) {
            $notify[] = ['success', 'Level updated successfully'];
        } else {
            $notify[] = ['success', 'Level created successfully'];
        }
        return redirect()->route('admin.level.index')->withNotify($notify);
    }
}
