<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class BackLoginController extends Controller
{
    const MAX_IMAGES = 10;
    const CAPTIONS_FILE = 'back-login/captions.json';

    public function __construct()
    {
        $this->middleware('auth');
    }

    private function loadCaptions(): array
    {
        if (Storage::disk('public')->exists(self::CAPTIONS_FILE)) {
            return json_decode(Storage::disk('public')->get(self::CAPTIONS_FILE), true) ?? [];
        }
        return [];
    }

    private function saveCaptions(array $captions): void
    {
        Storage::disk('public')->put(self::CAPTIONS_FILE, json_encode($captions, JSON_PRETTY_PRINT));
    }

    private function imageFiles(): array
    {
        return collect(Storage::disk('public')->files('back-login'))
            ->filter(fn($f) => !str_ends_with($f, 'captions.json'))
            ->sort()
            ->values()
            ->all();
    }

    public function index()
    {
        $files = $this->imageFiles();
        $captions = $this->loadCaptions();
        return view('admin.back-login.index', compact('files', 'captions'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'background' => 'required|image|mimes:jpg,jpeg,png,webp|max:5120',
            'caption'    => 'nullable|string|max:120',
        ]);

        $existing = $this->imageFiles();

        if (count($existing) >= self::MAX_IMAGES) {
            return redirect()->route('admin.back-login.index')
                ->with('error', 'Had maksimum ' . self::MAX_IMAGES . ' gambar telah dicapai. Sila padam gambar lama dahulu.');
        }

        $path = $request->file('background')->store('back-login', 'public');
        $filename = basename($path);

        if ($request->filled('caption')) {
            $captions = $this->loadCaptions();
            $captions[$filename] = trim($request->caption);
            $this->saveCaptions($captions);
        }

        return redirect()->route('admin.back-login.index')->with('success', 'Gambar background berjaya ditambah.');
    }

    public function updateCaption(Request $request, string $filename)
    {
        $request->validate(['caption' => 'nullable|string|max:120']);

        $captions = $this->loadCaptions();
        if ($request->filled('caption')) {
            $captions[$filename] = trim($request->caption);
        } else {
            unset($captions[$filename]);
        }
        $this->saveCaptions($captions);

        return redirect()->route('admin.back-login.index')->with('success', 'Kapsyen berjaya dikemaskini.');
    }

    public function destroyOne($filename)
    {
        Storage::disk('public')->delete('back-login/' . $filename);

        $captions = $this->loadCaptions();
        unset($captions[$filename]);
        $this->saveCaptions($captions);

        return redirect()->route('admin.back-login.index')->with('success', 'Gambar berjaya dipadam.');
    }

    public function destroy()
    {
        foreach (Storage::disk('public')->files('back-login') as $file) {
            Storage::disk('public')->delete($file);
        }
        $this->saveCaptions([]);
        return redirect()->route('admin.back-login.index')->with('success', 'Semua gambar background berjaya dipadam.');
    }
}
