<?php

declare(strict_types=1);

namespace App\Channels;

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

class UnifonicSmsChannel
{
    public function send($notifiable, Notification $notification): void
    {
        $data = $notification->toSms($notifiable);

        // In non-production environments, send email instead of SMS (if enabled)
        if (! app()->isProduction() && config('unifonic.simulate_in_development', true)) {
            $this->sendEmailInstead($data);

            return;
        }

        // print all configs
        Log::info('config is h'.json_encode(config('unifonic')));

        try {

            // url must be unifonic.endpoint from env with '?AppSid={APP_SID}&SenderID={SENDER_ID}&Body={message}&Recipient={mobile_number}&responseType=JSON&CorrelationID=%22%22&baseEncode=true&statusCallback=sent&async=false'
            $url = config('unifonic.endpoint').'?AppSid='.config('unifonic.appsId').
                '&SenderID='.config('unifonic.senderId').
                '&Body='.urlencode($data['message']).
                '&Recipient='.$data['phone'].
                '&responseType=JSON&CorrelationID=""&baseEncode=true&statusCallback=sent&async=false';

            $response = Http::withHeaders([
                'accept' => 'application/json',
            ])
                ->asForm()
                ->post(config('unifonic.endpoint'), [
                    'AppSid' => config('unifonic.appsId'),
                    'Recipient' => $data['phone'],
                    'Body' => $data['message'],
                    'SenderID' => config('unifonic.senderId'),
                ]);

            if ($response->failed()) {
                Log::error('Failed to send SMS via Unifonic', [
                    'url' => $url,
                    'phone' => $data['phone'],
                    'message' => $data['message'],
                    'response' => $response->body(),
                ]);
            } else {
                Log::info('SMS sent successfully via Unifonic', [
                    'phone' => $data['phone'],
                    'message' => substr($data['message'], 0, 50).'...',
                ]);
            }
        } catch (Exception $e) {
            Log::error('Exception occurred while sending SMS via Unifonic', [
                'phone' => $data['phone'],
                'message' => $data['message'],
                'error' => $e->getMessage(),
            ]);
        }
    }

    /**
     * Send email instead of SMS in non-production environments
     */
    private function sendEmailInstead(array $data): void
    {
        try {
            $emailTo = config('unifonic.simulation_email', config('mail.from.address'));

            Mail::raw($data['message'], function ($message) use ($data, $emailTo) {
                $message->to($emailTo)
                    ->subject('[SMS SIMULATION] Message for '.$data['phone']);
            });

            Log::info('SMS simulated via email in non-production environment', [
                'phone' => $data['phone'],
                'message' => substr($data['message'], 0, 50).'...',
                'sent_to' => $emailTo,
            ]);
        } catch (Exception $e) {
            Log::error('Failed to send email simulation for SMS', [
                'phone' => $data['phone'],
                'message' => $data['message'],
                'error' => $e->getMessage(),
            ]);
        }
    }
}
