<?php

namespace App\Data;

use Spatie\LaravelData\Data;

class BookingResponseData extends Data
{
    public function __construct(
        public int $id,
        public int $property_id,
        public int $tenant_id,
        public int $landlord_id,
        public string $check_in_date,
        public ?string $check_out_date = null,
        public int $status,
        public string $status_text,
        public string $created_at,
        public string $updated_at,
        public ?PropertyData $property = null,
        public ?UserData $tenant = null,
        public ?UserData $landlord = null,
        public ?RentalAgreementData $rental_agreement = null,
    ) {}

    public static function fromBooking(\App\Models\Booking $booking): self
    {
        return new self(
            id: $booking->id,
            property_id: $booking->property_id,
            tenant_id: $booking->tenant_id,
            landlord_id: $booking->landlord_id,
            check_in_date: $booking->check_in_date->format('Y-m-d'),
            check_out_date: $booking->check_out_date?->format('Y-m-d'),
            status: $booking->status,
            status_text: $booking->status_text,
            created_at: $booking->created_at->format('Y-m-d H:i:s'),
            updated_at: $booking->updated_at->format('Y-m-d H:i:s'),
            property: $booking->relationLoaded('property') ? PropertyData::fromProperty($booking->property) : null,
            tenant: $booking->relationLoaded('tenant') ? UserData::from($booking->tenant) : null,
            landlord: $booking->relationLoaded('landlord') ? UserData::from($booking->landlord) : null,
            rental_agreement: $booking->relationLoaded('rentalAgreement') && $booking->rentalAgreement 
                ? RentalAgreementData::fromRentalAgreement($booking->rentalAgreement) 
                : null,
        );
    }

    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'property_id' => $this->property_id,
            'tenant_id' => $this->tenant_id,
            'landlord_id' => $this->landlord_id,
            'check_in_date' => $this->check_in_date,
            'check_out_date' => $this->check_out_date,
            'status' => $this->status,
            'status_text' => $this->status_text,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'property' => $this->property?->toArray(),
            'tenant' => $this->tenant?->toArray(),
            'landlord' => $this->landlord?->toArray(),
            'rental_agreement' => $this->rental_agreement?->toArray(),
        ];
    }
}
