<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\HomepageStat;
use App\Services\FileUploadService;
use Illuminate\Http\Request;

class HomepageStatController extends Controller
{
    public function index()
    {
        $stats = HomepageStat::orderBy('sort_order')->paginate(20);

        return view('admin.stats.index', compact('stats'));
    }

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

    public function store(Request $request)
    {
        $validated = $this->validateStat($request);

        if ($request->hasFile('flag')) {
            $validated['flag'] = FileUploadService::store($request->file('flag'), 'flags');
        }
        if ($request->hasFile('popup_image')) {
            $validated['popup_image'] = FileUploadService::store($request->file('popup_image'), 'flags');
        }

        HomepageStat::create($validated);

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

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

    public function update(Request $request, HomepageStat $stat)
    {
        $validated = $this->validateStat($request);

        if ($request->hasFile('flag')) {
            $validated['flag'] = FileUploadService::store($request->file('flag'), 'flags');
        }
        if ($request->hasFile('popup_image')) {
            $validated['popup_image'] = FileUploadService::store($request->file('popup_image'), 'flags');
        }

        $stat->update($validated);

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

    public function destroy(HomepageStat $stat)
    {
        $stat->delete();

        return back()->with('success', 'Statistic deleted.');
    }

    protected function validateStat(Request $request): array
    {
        return $request->validate([
            'label' => 'required|string|max:255',
            'value' => 'required|string|max:255',
            'flag' => 'nullable|file|extensions:jpeg,jpg,jpe,png,gif,webp,svg,bmp,ico,tif,tiff,avif,heic,heif|max:2048',
            'popup_title' => 'nullable|string|max:255',
            'popup_image' => 'nullable|file|extensions:jpeg,jpg,jpe,png,gif,webp,svg,bmp,ico,tif,tiff,avif,heic,heif|max:10240',
            'sort_order' => 'nullable|integer|min:0',
            'is_active' => 'nullable|boolean',
        ]);
    }
}
