<?php

namespace App\Services;

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

class SmsService
{
    public function send(string $phone, string $message, int $schoolId): bool
    {
        $phone = $this->formatPhone($phone);

        try {
            $response = Http::withHeaders([
                'apiKey' => config('services.africastalking.api_key'),
                'Accept' => 'application/json',
            ])->asForm()->post('https://api.africastalking.com/version1/messaging', [
                'username' => config('services.africastalking.username'),
                'to'       => $phone,
                'message'  => $message,
                'from'     => config('services.africastalking.sender_id') ?: null,
            ]);

            $success = $response->successful();
            $this->logNotification($schoolId, 'sms', $phone, $message, $success ? 'sent' : 'failed', 'africastalking');
            return $success;
        } catch (\Exception $e) {
            Log::error('SMS send failed: ' . $e->getMessage());
            $this->logNotification($schoolId, 'sms', $phone, $message, 'failed', 'africastalking');
            return false;
        }
    }

    public function sendBulk(array $phones, string $message, int $schoolId): array
    {
        $results = ['sent' => 0, 'failed' => 0];
        foreach ($phones as $phone) {
            $this->send($phone, $message, $schoolId) ? $results['sent']++ : $results['failed']++;
        }
        return $results;
    }

    private function formatPhone(string $phone): string
    {
        $phone = preg_replace('/\D/', '', $phone);
        if (str_starts_with($phone, '0')) {
            $phone = '254' . substr($phone, 1);
        }
        if (!str_starts_with($phone, '+')) {
            $phone = '+' . $phone;
        }
        return $phone;
    }

    private function logNotification(int $schoolId, string $type, string $recipient, string $message, string $status, string $provider): void
    {
        \DB::table('notifications_log')->insert([
            'school_id'  => $schoolId,
            'type'       => $type,
            'recipient'  => $recipient,
            'message'    => $message,
            'status'     => $status,
            'provider'   => $provider,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
