<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Traits\DeleteModelTrait;
use App\Traits\FlashMessageTrait;
use App\Models\Hostel;
use App\Models\Property;
use App\Services\PropertyService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Redirect;

class AdminHostelController extends Controller
{
    use DeleteModelTrait, FlashMessageTrait;

    protected $propertyService;

    public function __construct(PropertyService $propertyService)
    {
        $this->propertyService = $propertyService;
    }

    /**
     * Display a listing of hostels
     */
    public function index(Request $request)
    {
        try {
            $perPage = 10;
            $query = Hostel::with(['property.landlord']);

            // Apply filters
            if ($request->has('search') && $request->search) {
                $query->whereHas('property', function ($q) use ($request) {
                    $q->where('title', 'like', '%' . $request->search . '%')
                      ->orWhere('address', 'like', '%' . $request->search . '%');
                });
            }

            if ($request->has('gender') && $request->gender) {
                $query->where('gender_restriction', $request->gender);
            }

            if ($request->has('room_sharing') && $request->room_sharing) {
                $query->where('room_sharing', $request->room_sharing);
            }

            $hostels = $query->orderBy('created_at', 'desc')->paginate($perPage);

            // Transform data for display
            $hostels->getCollection()->transform(function ($hostel, $index) use ($hostels) {
                $hostel->sn = ($hostels->currentPage() - 1) * $hostels->perPage() + $index + 1;
                $hostel->property_title = $hostel->property->title ?? 'N/A';
                $hostel->property_address = $hostel->property->address ?? 'N/A';
                $hostel->landlord_name = $hostel->property->landlord->name ?? 'N/A';
                $hostel->room_sharing_name = $hostel->room_sharing_name;
                $hostel->gender_restriction_name = $hostel->gender_restriction_name;
                $hostel->university_nearby_text = $hostel->university_nearby ?? 'N/A';
                $hostel->distance_text = $hostel->distance_to_university ? $hostel->distance_to_university . ' km' : 'N/A';
                return $hostel;
            });

            return Inertia::render('Admin/Hostels/Hostel', [
                'hostels' => $hostels->items(),
                'pagination' => [
                    'current_page' => $hostels->currentPage(),
                    'last_page' => $hostels->lastPage(),
                    'per_page' => $hostels->perPage(),
                    'total' => $hostels->total(),
                    'from' => $hostels->firstItem(),
                    'to' => $hostels->lastItem(),
                    'links' => $hostels->linkCollection()->toArray(),
                ],
                'filters' => $request->only(['search', 'gender', 'room_sharing'])
            ]);
        } catch (\Exception $e) {
            return $this->error('Failed to load hostels: ' . $e->getMessage());
        }
    }

    /**
     * Display the specified hostel with property details
     */
    public function show($id)
    {
        try {
            $hostel = Hostel::with(['property.landlord', 'property.images'])->find($id);
            
            if (!$hostel) {
                return $this->error('Hostel not found');
            }

            $property = $hostel->property;
            
            // Format property data for frontend (similar to AdminPropertyController::edit)
            $propertyData = [
                'id' => $property->id,
                'title' => $property->title,
                'description' => $property->description,
                'address' => $property->address,
                'latitude' => $property->latitude,
                'longitude' => $property->longitude,
                'property_type' => $property->property_type,
                'bedrooms' => $property->bedrooms,
                'bathrooms' => $property->bathrooms,
                'size_sqm' => $property->size_sqm,
                'monthly_rent' => $property->monthly_rent,
                'deposit_amount' => $property->deposit_amount,
                'is_furnished' => $property->is_furnished,
                'status' => $property->status,
                'landlord_id' => $property->landlord_id,
                'images' => $property->images->map(function($img) {
                    return is_string($img->image_url) && strpos($img->image_url, '/storage/') === 0
                        ? str_replace('/storage/', '', $img->image_url)
                        : $img->image_url;
                })->toArray(),
                'hostel' => [
                    'university_nearby' => $hostel->university_nearby ?? '',
                    'distance_to_university' => $hostel->distance_to_university ?? 0,
                    'room_sharing' => $hostel->room_sharing ?? 1,
                    'gender_restriction' => $hostel->gender_restriction ?? 3,
                    'meal_plan_available' => $hostel->meal_plan_available ?? false,
                    'study_room_available' => $hostel->study_room_available ?? false,
                    'curfew_time' => $hostel->curfew_time 
                        ? (is_string($hostel->curfew_time) 
                            ? $hostel->curfew_time 
                            : (method_exists($hostel->curfew_time, 'format') 
                                ? $hostel->curfew_time->format('H:i') 
                                : $hostel->curfew_time))
                        : '',
                ],
            ];

            return Inertia::render('Admin/Hostels/EditHostel', [
                'hostel' => $hostel,
                'property' => $propertyData,
            ]);
        } catch (\Exception $e) {
            return $this->error('Failed to load hostel: ' . $e->getMessage());
        }
    }

    /**
     * Remove the specified hostel and its associated property
     */
    public function destroy($id)
    {
        try {
            $hostel = Hostel::with('property')->find($id);

            if (!$hostel) {
                return Redirect::back()->with('error', [
                    "message" => "Hostel not found."
                ]);
            }

            // Get the property ID before deleting
            $propertyId = $hostel->property_id;

            // Delete the hostel (this will cascade delete due to migration, but we'll delete property explicitly)
            $hostel->delete();

            // Delete the associated property
            $property = Property::find($propertyId);
            if ($property) {
                $property->delete();
            }

            return Redirect::back()->with('success', [
                "message" => "Hostel and property deleted successfully."
            ]);
        } catch (\Exception $e) {
            return Redirect::back()->with('error', [
                "message" => "Failed to delete hostel: " . $e->getMessage()
            ]);
        }
    }
}






