<?php

namespace App\Commands;

use App\Models\BookingModel;
use App\Models\Control\TenantRecordModel;
use App\Models\GuestModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

/**
 * Batch job (not real-time — per the Phase 3 brief) that sends a
 * pre-arrival reminder to every guest checking in tomorrow. Meant to run
 * once a day via cron/Task Scheduler:
 *   php spark bookings:send-pre-arrival-reminders
 *
 * Runs across every active tenant in one invocation (there's no tenant
 * context outside a web request otherwise) — each tenant's reminders use
 * that tenant's own WhatsApp/SMS settings and channel preference.
 *
 * `reminder_sent_at` on the booking prevents double-sending if the job
 * is run more than once on the same day (or retried after a partial
 * failure).
 */
class SendPreArrivalReminders extends BaseCommand
{
    protected $group       = 'Messaging';
    protected $name        = 'bookings:send-pre-arrival-reminders';
    protected $description = 'Sends a pre-arrival reminder (WhatsApp/SMS per tenant preference) to every guest checking in tomorrow.';

    public function run(array $params)
    {
        $tenants = (new TenantRecordModel())->where('status', 'active')->findAll();

        foreach ($tenants as $tenant) {
            $this->sendForTenant($tenant);
        }
    }

    private function sendForTenant(object $tenant): void
    {
        service('tenantContext')->setTenant($tenant);

        $tomorrow = date('Y-m-d', strtotime('+1 day'));
        $bookings = (new BookingModel())->withDetails()
            ->where('bookings.check_in_date', $tomorrow)
            ->where('bookings.status', 'confirmed')
            ->where('bookings.reminder_sent_at', null)
            ->findAll();

        if ($bookings === []) {
            CLI::write("{$tenant->slug}: no reminders due.", 'white');

            return;
        }

        $bookingModel = new BookingModel();
        $guests       = new GuestModel();

        foreach ($bookings as $booking) {
            $guest = $guests->find($booking->guest_id);

            if ($guest === null) {
                continue;
            }

            service('messagingService')->send(
                'pre_arrival_reminder',
                $guest->id,
                $guest->phone,
                "Hi {$guest->full_name}, this is a reminder that your stay at {$tenant->hotel_name} begins tomorrow, " .
                    "{$booking->check_in_date}. We look forward to welcoming you!",
                [$guest->full_name, $tenant->hotel_name, $booking->check_in_date],
            );

            $bookingModel->update($booking->id, ['reminder_sent_at' => date('Y-m-d H:i:s')]);
        }

        CLI::write("{$tenant->slug}: sent " . count($bookings) . ' reminder(s).', 'green');
    }
}
