<?php

namespace App\Http\Controllers\Admin;

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

class RegistrationController extends Controller
{
    public function index(Request $request)
    {
        $query = Registration::query()->latest();

        if ($request->filled('category')) {
            $query->where('category', $request->category);
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('q')) {
            $query->where(function ($w) use ($request) {
                $w->where('name', 'like', '%'.$request->q.'%')
                  ->orWhere('city', 'like', '%'.$request->q.'%')
                  ->orWhere('contact', 'like', '%'.$request->q.'%');
            });
        }

        $registrations = $query->paginate(15)->withQueryString();

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

    public function show(Registration $registration)
    {
        return view('admin.registrations.show', compact('registration'));
    }

    public function updateStatus(Request $request, Registration $registration)
    {
        $request->validate(['status' => ['required', 'in:pending,shortlisted,approved,rejected']]);
        $registration->update(['status' => $request->status]);

        return back()->with('success', 'Status updated.');
    }

    public function destroy(Registration $registration)
    {
        foreach ([$registration->photo_one, $registration->photo_two] as $photo) {
            if ($photo) {
                Storage::disk('public')->delete($photo);
            }
        }
        $registration->delete();

        return redirect()->route('admin.registrations.index')->with('success', 'Registration deleted.');
    }
}
