namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Stat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class StatController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth','verified']);
        $this->middleware(['auth','role:admin']);
    }

    public function index()
    {
        $stats = Stat::latest()->paginate(10);
        return view('admin.stats.index', compact('stats'));

        Log::channel('audit')->info('Stat updated', ['user'=>auth()->id(),'stat'=>$stat->id]);
    }

    public function create()
    {
        return view('admin.stats.create');
    }

    public function store(Request $request)
    {
        $data = $this->validateData($request);
        Stat::create($data);
        Log::info('Stat created', $data);

        return redirect()->route('admin.stats.index')->with('success','Created successfully');
    }

    public function show(Stat $stat)
    {
        return view('admin.stats.show', compact('stat'));
    }

    public function edit(Stat $stat)
    {
        return view('admin.stats.edit', compact('stat'));
    }

    public function update(Request $request, Stat $stat)
    {
       $data = $this->validateData($request, $stat->id);
        $stat->update($data);
        Log::info('Stat updated', $data);

        return redirect()->route('admin.stats.index')->with('success','Updated successfully');
    }

    public function destroy(Stat $stat)
    {
        $stat->delete();
        Log::warning('Stat deleted: '.$stat->id);

        return back()->with('success','Deleted');
    }

    private function validateData($request,$id=null)
    {
        return $request->validate([
        'title'=>'required|max:150',
        'slug'=>'required|max:150|unique:stats,slug,'.$id,
        'count'=>'required|integer|min:0',
        'color'=>'required',
        'icon'=>'nullable|max:100',
        'is_active'=>'boolean'
        ]);
    }
}