<?php

namespace App\Modules\Pilkades\Http\Controllers\AdminDesa;

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Models\Candidate;
use App\Modules\Pilkades\Models\CandidateGallery;
use App\Modules\Pilkades\Models\Media;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class CandidateGalleryController extends Controller
{
    public function store(Request $request, Candidate $candidate): RedirectResponse
    {
        $this->authorize('update', $candidate);

        $data = $request->validate([
            'photo' => ['required', 'image', 'max:2048'],
            'caption' => ['nullable', 'string', 'max:255'],
            'urutan' => ['nullable', 'integer'],
        ]);

        $file = $request->file('photo');
        $path = $file->store('candidate-gallery', 'public');

        $media = Media::create([
            'desa_id' => $candidate->desa_id,
            'model_type' => Candidate::class,
            'model_id' => $candidate->id,
            'disk' => 'public',
            'file_name' => $file->getClientOriginalName(),
            'mime_type' => $file->getClientMimeType(),
            'size' => $file->getSize(),
            'path' => $path,
        ]);

        $candidate->gallery()->create([
            'media_id' => $media->id,
            'caption' => $data['caption'] ?? null,
            'urutan' => $data['urutan'] ?? 0,
        ]);

        return back()->with('success', 'Foto galeri berhasil ditambahkan.');
    }

    public function destroy(CandidateGallery $galleryItem): RedirectResponse
    {
        $this->authorize('update', $galleryItem->candidate);

        Storage::disk($galleryItem->media->disk)->delete($galleryItem->media->path);
        $galleryItem->media->delete();
        $galleryItem->delete();

        return back()->with('success', 'Foto galeri berhasil dihapus.');
    }
}
