<?php

namespace App\Support;

use App\Models\Booking;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class Notify
{
    public static function send(string $to, string $message, string $channel = 'generic'): bool
    {
        $apiKey = config('services.termii.api_key');

        if (empty($apiKey)) {
            Log::info("Termii not configured — skipped SMS to {$to}");
            return false;
        }

        try {
            $response = Http::timeout(10)->post('https://api.termii.com/api/sms/send', [
                'api_key' => $apiKey,
                'to' => $to,
                'from' => config('services.termii.sender_id', 'Epelcon'),
                'sms' => $message,
                'type' => 'plain',
                'channel' => $channel,
            ]);

            if ($response->failed()) {
                Log::warning("Termii send failed for {$to}: " . $response->body());
                return false;
            }

            return true;
        } catch (\Throwable $e) {
            Log::warning("Termii send error for {$to}: " . $e->getMessage());
            return false;
        }
    }

    public static function whatsapp(string $to, string $message): bool
    {
        return static::send($to, $message, 'whatsapp');
    }

    public static function bookingStatus(Booking $booking, string $status): void
    {
        try {
            $phone = $booking->customer->phone ?? null;

            if (empty($phone)) {
                return;
            }

            $code = $booking->code;
            $name = $booking->customer->name ?? 'Guest';

            $message = match ($status) {
                'confirmed' => "Hi {$name}, your booking {$code} at Epelcon Hospitality is confirmed. We look forward to hosting you!",
                'checked_in' => "Welcome, {$name}! You are checked in (booking {$code}). Dial reception for anything you need. Enjoy your stay!",
                'checked_out' => "Thank you for staying with us, {$name}! Booking {$code} is now checked out. Safe travels — see you again soon.",
                'cancelled' => "Hi {$name}, your booking {$code} at Epelcon Hospitality has been cancelled. Contact us if this was a mistake.",
                default => "Hi {$name}, your booking {$code} status is now: {$status}. Epelcon Hospitality.",
            };

            static::send($phone, $message);
        } catch (\Throwable $e) {
            Log::warning('Booking status SMS failed: ' . $e->getMessage());
        }
    }
}
