<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
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 BeachReservationApiController extends Controller
{
    /**
     * Display a listing of the authenticated user's reservations.
     */
    public function index()
    {
        $reservations = BeachReservation::where('user_id', Auth::id())
            ->latest()
            ->get();

        return response()->json([
            'success' => true,
            'data' => $reservations,
            'message' => 'Reservations retrieved successfully'
        ]);
    }

    /**
     * Store a newly created reservation.
     */
    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 response()->json([
                'success' => true,
                'data' => $reservation->load('user'),
                'message' => 'Beach reservation created successfully'
            ], 201);
        } 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 response()->json([
                'success' => false,
                'message' => 'Failed to create reservation. Please try again.'
            ], 500);
        }
    }

    /**
     * Display the specified reservation.
     */
    public function show(BeachReservation $beachReservation)
    {
        // Ensure user can only view their own reservations
        if ($beachReservation->user_id !== Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized access'
            ], 403);
        }

        return response()->json([
            'success' => true,
            'data' => $beachReservation->load('user'),
            'message' => 'Reservation retrieved successfully'
        ]);
    }

    /**
     * Update the specified reservation.
     */
    public function update(Request $request, BeachReservation $beachReservation)
    {
        // Ensure user can only update their own reservations
        if ($beachReservation->user_id !== Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized access'
            ], 403);
        }

        // Only allow updates if reservation is pending
        if ($beachReservation->status !== 'pending') {
            return response()->json([
                'success' => false,
                'message' => 'Cannot update reservation that is not pending'
            ], 400);
        }

        $request->validate([
            'reservation_date' => 'sometimes|required|date|after:today',
            'full_name' => 'sometimes|required|string|max:255',
            'number_of_persons' => 'sometimes|required|integer|min:1|max:50',
            'instagram_link' => 'sometimes|required|string|max:255|regex:/^https?:\/\/(www\.)?instagram\.com\/[a-zA-Z0-9._]+\/?$/',
        ]);

        $beachReservation->update($request->only([
            'reservation_date',
            'full_name',
            'number_of_persons',
            'instagram_link'
        ]));

        return response()->json([
            'success' => true,
            'data' => $beachReservation->load('user'),
            'message' => 'Reservation updated successfully'
        ]);
    }

    /**
     * Remove the specified reservation.
     */
    public function destroy(BeachReservation $beachReservation)
    {
        // Ensure user can only delete their own reservations
        if ($beachReservation->user_id !== Auth::id()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized access'
            ], 403);
        }

        // Only allow deletion if reservation is pending
        if ($beachReservation->status !== 'pending') {
            return response()->json([
                'success' => false,
                'message' => 'Cannot delete reservation that is not pending'
            ], 400);
        }

        // 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 response()->json([
            'success' => true,
            'message' => '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 reservation statistics for the authenticated user.
     */
    public function statistics()
    {
        $userId = Auth::id();

        $stats = [
            'total' => BeachReservation::where('user_id', $userId)->count(),
            'pending' => BeachReservation::where('user_id', $userId)->where('status', 'pending')->count(),
            'approved' => BeachReservation::where('user_id', $userId)->where('status', 'approved')->count(),
            'rejected' => BeachReservation::where('user_id', $userId)->where('status', 'rejected')->count(),
        ];

        return response()->json([
            'success' => true,
            'data' => $stats,
            'message' => 'Statistics retrieved successfully'
        ]);
    }
}
