<?php

namespace App\Models;

use Config\Lookups;

class GuestPreferenceModel extends TenantModel
{
    protected $table            = 'guest_preferences';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'guest_id',
        'room_type_id',
        'bed_type',
        'dietary_restrictions',
        'seating_preference',
        'allergies',
        'smoking_preference',
        'other_notes',
        'ai_inferred_summary',
        'ai_inferred_at',
    ];

    public function __construct()
    {
        parent::__construct();

        $this->validationRules = [
            'smoking_preference' => 'permit_empty|in_list[' . implode(',', array_keys((new Lookups())->smokingPreferences)) . ']',
        ];
    }

    public function forGuest(int $guestId): ?object
    {
        return $this->where('guest_id', $guestId)->first();
    }

    /**
     * Upsert — a guest has at most one preferences row, so there's no
     * separate "create" vs "edit" screen the way most of this app's
     * resources have; the guest form just always posts the current
     * values and this reconciles them into one row.
     */
    public function saveForGuest(int $guestId, array $data): bool
    {
        $existing = $this->forGuest($guestId);
        $data['guest_id'] = $guestId;

        if ($existing !== null) {
            return $this->update($existing->id, $data);
        }

        // A blank form (guest has no preferences at all) shouldn't create
        // an empty row — nothing to upsert.
        $hasAnyValue = array_filter($data, static fn ($v, $k) => $k !== 'guest_id' && $v !== null && $v !== '', ARRAY_FILTER_USE_BOTH);

        if ($hasAnyValue === []) {
            return true;
        }

        return $this->insert($data) !== false;
    }
}
