<?php

namespace App\Http\Controllers;

use App\Http\Requests\BeachReservationRequest;
use App\Models\BeachReservation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class BeachReservationController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = BeachReservation::with('user');

        // Filter by status
        if ($request->has('status') && in_array($request->status, ['pending', 'approved', 'rejected'])) {
            $query->where('status', $request->status);
        }

        // Filter by date range
        if ($request->has('date_from') && $request->date_from != '') {
            $query->where('reservation_date', '>=', $request->date_from);
        }

        if ($request->has('date_to') && $request->date_to != '') {
            $query->where('reservation_date', '<=', $request->date_to);
        }

        // Search by full name
        if ($request->has('search') && $request->search != '') {
            $query->where('full_name', 'like', '%' . $request->search . '%');
        }

        $reservations = $query->latest()->paginate(15);

        return view('beach_reservations.index', compact('reservations'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('beach_reservations.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(BeachReservationRequest $request)
    {
        try {
            // Handle file uploads
            $idHeadImage = $this->uploadImage($request->file('id_head_image'), 'id_head');
            $idTailImage = $this->uploadImage($request->file('id_tail_image'), 'id_tail');

            // Create the reservation
            $reservation = BeachReservation::create([
                'user_id' => Auth::id(),
                'reservation_date' => $request->reservation_date,
                'full_name' => $request->full_name,
                'number_of_persons' => $request->number_of_persons,
                'instagram_link' => $request->instagram_link,
                'id_head_image' => $idHeadImage,
                'id_tail_image' => $idTailImage,
                'status' => 'pending',
            ]);

            return redirect()->route('beach-reservations.index')
                ->with('success', 'Beach reservation created successfully!');
        } catch (\Exception $e) {
            // Clean up uploaded files if creation fails
            if (isset($idHeadImage)) {
                Storage::disk('public')->delete($idHeadImage);
            }
            if (isset($idTailImage)) {
                Storage::disk('public')->delete($idTailImage);
            }

            return back()->withErrors(['error' => 'Failed to create reservation. Please try again.']);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(BeachReservation $beachReservation)
    {
        return view('beach_reservations.show', compact('beachReservation'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(BeachReservation $beachReservation)
    {
        return view('beach_reservations.edit', compact('beachReservation'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, BeachReservation $beachReservation)
    {
        $request->validate([
            'status' => 'required|in:pending,approved,rejected',
            'notes' => 'nullable|string|max:1000',
        ]);

        $beachReservation->update([
            'status' => $request->status,
            'notes' => $request->notes,
        ]);

        return redirect()->route('beach-reservations.index')
            ->with('success', 'Reservation status updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(BeachReservation $beachReservation)
    {
        // Delete associated images
        if ($beachReservation->id_head_image) {
            Storage::disk('public')->delete($beachReservation->id_head_image);
        }
        if ($beachReservation->id_tail_image) {
            Storage::disk('public')->delete($beachReservation->id_tail_image);
        }

        $beachReservation->delete();

        return redirect()->route('beach-reservations.index')
            ->with('success', 'Reservation deleted successfully!');
    }

    /**
     * Upload image to storage.
     */
    private function uploadImage($file, $prefix): string
    {
        $filename = $prefix . '_' . time() . '_' . Str::random(10) . '.' . $file->getClientOriginalExtension();
        $path = $file->storeAs('beach_reservations', $filename, 'public');

        return $path;
    }

    /**
     * Get user's own reservations.
     */
    public function myReservations()
    {
        $reservations = BeachReservation::where('user_id', Auth::id())
            ->latest()
            ->paginate(10);

        return view('beach_reservations.my_reservations', compact('reservations'));
    }

    /**
     * Approve a reservation.
     */
    public function approve(BeachReservation $beachReservation)
    {
        $beachReservation->update([
            'status' => 'approved',
            'notes' => request('notes'),
        ]);

        return redirect()->route('beach-reservations.index')
            ->with('success', 'Reservation approved successfully!');
    }

    /**
     * Reject a reservation.
     */
    public function reject(BeachReservation $beachReservation)
    {
        $beachReservation->update([
            'status' => 'rejected',
            'notes' => request('notes'),
        ]);

        return redirect()->route('beach-reservations.index')
            ->with('success', 'Reservation rejected successfully!');
    }
}
