<?php

namespace App\Http\Controllers\Admin;

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

class HallController extends Controller
{
    public function index()
    {
        $halls = Hall::all();
        return view('admin.halls.index', compact('halls'));
    }

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'capacity' => 'required|integer',
            'price_per_day' => 'required|numeric',
            'description' => 'nullable|string',
            'features' => 'nullable|array',
            'image' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('halls', 'public');
            $validated['image'] = $path;
        }

        Hall::create($validated);

        return redirect()->route('admin.halls.index')->with('success', 'Hall created successfully.');
    }

    public function edit(Hall $hall)
    {
        return view('admin.halls.edit', compact('hall'));
    }

    public function update(Request $request, Hall $hall)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'capacity' => 'required|integer',
            'price_per_day' => 'required|numeric',
            'description' => 'nullable|string',
            'features' => 'nullable|array',
            'image' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('image')) {
            // Delete old image if exists
            if ($hall->image) {
                Storage::disk('public')->delete($hall->image);
            }
            $path = $request->file('image')->store('halls', 'public');
            $validated['image'] = $path;
        }

        $hall->update($validated);

        return redirect()->route('admin.halls.index')->with('success', 'Hall updated successfully.');
    }

    public function destroy(Hall $hall)
    {
        if ($hall->image) {
            Storage::disk('public')->delete($hall->image);
        }
        $hall->delete();
        return redirect()->route('admin.halls.index')->with('success', 'Hall deleted successfully.');
    }
}
