<?php

namespace App\Imports;

use App\Models\Room;
use App\Models\RoomType;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\DB;

class RoomsImport implements ToCollection, WithHeadingRow
{
    protected int $hotelId;

    public function __construct(int $hotelId)
    {
        $this->hotelId = $hotelId;
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            if (empty($row['room_number'])) {
                continue;
            }

            // Find or create room type
            $roomType = RoomType::firstOrCreate(
                [
                    'hotel_id' => $this->hotelId,
                    'name' => $row['room_type'] ?? 'Standard',
                ],
                ['description' => 'Imported room type']
            );

            Room::create([
                'hotel_id' => $this->hotelId,
                'room_number' => $row['room_number'],
                'floor' => $row['floor'],
                'room_type_id' => $roomType->id,
                'category' => $row['category'],
                'price_per_night' => $row['price_per_night'],
                'capacity' => $row['capacity'],
                'status' => in_array(strtolower($row['status'] ?? 'available'), ['available', 'occupied', 'maintenance', 'cleaning'], true)
                    ? strtolower($row['status'])
                    : 'available',
                'description' => $row['description'],
                'is_available' => strtolower($row['status'] ?? 'available') === 'available' ? 1 : 0,
                'amenities' => $row['amenities'] ? json_encode(explode(',', $row['amenities'])) : null
            ]);
        }
    }
}