<?php

namespace App\Notifications\Channels;

use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WhatsAppChannel
{
    public function send(object $notifiable, Notification $notification): void
    {
        $message = $notification->toWhatsApp($notifiable);
        $phone = $notifiable->telefon_parinte ?? $notifiable->phone ?? null;

        if (!$phone || !$message) {
            return;
        }

        $scoala = $notifiable->clasa?->scoala;
        $apiUrl = $scoala?->whatsapp_api_url;
        $apiKey = $scoala?->whatsapp_api_key;

        if (!$apiUrl) {
            Log::warning("WhatsApp: API URL nu e configurat pentru școala {$scoala?->nume}");
            return;
        }

        try {
            Http::withHeaders([
                'Authorization' => "Bearer {$apiKey}",
                'Content-Type' => 'application/json',
            ])->post($apiUrl, [
                'phone' => $phone,
                'message' => $message,
            ]);
        } catch (\Exception $e) {
            Log::error("WhatsApp notification failed: {$e->getMessage()}");
        }
    }
}
