<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class VehicleRentalController extends Controller
{
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'pickUpLocation' => 'required|string|max:255',
            'dropOffLocation' => 'required|string|max:255',
            'pickUpDate' => 'required|date|after_or_equal:today',
            'dropOffDate' => 'required|date|after:pickUpDate',
            'vehicleType' => 'required|in:economy,compact,suv,luxury,van',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $rentalId = DB::table('vehicle_rentals')->insertGetId([
                'pick_up_location' => $request->pickUpLocation,
                'drop_off_location' => $request->dropOffLocation,
                'pick_up_date' => $request->pickUpDate,
                'drop_off_date' => $request->dropOffDate,
                'vehicle_type' => $request->vehicleType,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $rental = DB::table('vehicle_rentals')->find($rentalId);

            return response()->json([
                'success' => true,
                'message' => 'Vehicle rental request created successfully',
                'data' => $rental
            ], 201);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create vehicle rental',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function showAc($id)
    {
        try {
            $accommodation = DB::table('accommodation')->where('id', $id)->first();
            
            if (!$accommodation) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Accommodation not found'
                ], 404);
            }

            return response()->json([
                'status' => 'success',
                'data' => $accommodation
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch accommodation',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}