<?php
namespace Services;

use Core\Database;

class SmsService {
    private Database $db;
    private array $school;

    public function __construct(int $schoolId = 0) {
        $this->db = Database::getInstance();
        if ($schoolId) {
            $this->school = $this->db->fetch("SELECT * FROM schools WHERE id=?", [$schoolId]) ?? [];
        }
    }

    // ── Main send method — auto-picks provider ───────────────
    public function send(string $phone, string $message, int $schoolId): bool {
        if (empty($this->school)) {
            $this->school = $this->db->fetch("SELECT * FROM schools WHERE id=?", [$schoolId]) ?? [];
        }
        $provider = $this->school['sms_provider'] ?? 'advanta';
        $phone    = $this->formatPhone($phone);

        $result = match($provider) {
            'advanta'       => $this->sendAdvanta($phone, $message),
            'africastalking'=> $this->sendAfricasTalking($phone, $message),
            default         => $this->sendAdvanta($phone, $message),
        };

        $this->log($schoolId, $phone, $message, $result['status'], $provider, $result['response'] ?? '');
        return $result['status'] === 'sent';
    }

    // ── Send to multiple phones ──────────────────────────────
    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;
    }

    // ── Advanta SMS (quicksms.advantasms.com) ────────────────
    private function sendAdvanta(string $phone, string $message): array {
        $apiKey   = $this->school['advanta_api_key'] ?? '';
        $senderId = $this->school['advanta_sender_id'] ?? 'EDUSMART';
        $partnerID= $this->school['advanta_partner_id'] ?? '';

        if (!$apiKey) return ['status'=>'failed','response'=>'Advanta API key not configured'];

        try {
            $payload = json_encode([
                'apikey'    => $apiKey,
                'partnerID' => $partnerID,
                'message'   => $message,
                'shortcode' => $senderId,
                'mobile'    => $phone,
            ]);

            $ch = curl_init('https://quicksms.advantasms.com/api/services/sendsms/');
            curl_setopt_array($ch, [
                CURLOPT_POST           => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Accept: application/json'],
                CURLOPT_POSTFIELDS     => $payload,
                CURLOPT_SSL_VERIFYPEER => false,
            ]);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curlErr  = curl_error($ch);
            curl_close($ch);

            if ($curlErr) return ['status'=>'failed','response'=>'cURL error: '.$curlErr];

            $result = json_decode($response, true);
            // Advanta returns responses_code 200 on success
            $code = $result['responses'][0]['response-code'] ?? $result['response-code'] ?? 0;
            if ($httpCode === 200 && (int)$code === 200) {
                return ['status'=>'sent','response'=>$response];
            }
            return ['status'=>'failed','response'=>$response];
        } catch (\Throwable $e) {
            return ['status'=>'failed','response'=>$e->getMessage()];
        }
    }

    // ── Africa's Talking ─────────────────────────────────────
    private function sendAfricasTalking(string $phone, string $message): array {
        $username = $this->school['at_username'] ?? '';
        $apiKey   = $this->school['at_api_key'] ?? '';
        $sender   = $this->school['at_sender_id'] ?? null;

        if (!$username || !$apiKey) return ['status'=>'failed','response'=>'AT credentials not configured'];

        try {
            $url = $username === 'sandbox'
                ? 'https://api.sandbox.africastalking.com/version1/messaging'
                : 'https://api.africastalking.com/version1/messaging';

            $params = ['username'=>$username,'to'=>$phone,'message'=>$message];
            if ($sender) $params['from'] = $sender;

            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_POST           => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_HTTPHEADER     => [
                    'apiKey: '.$apiKey,
                    'Accept: application/json',
                    'Content-Type: application/x-www-form-urlencoded',
                ],
                CURLOPT_POSTFIELDS => http_build_query($params),
            ]);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            return $httpCode === 201
                ? ['status'=>'sent','response'=>$response]
                : ['status'=>'failed','response'=>$response];
        } catch (\Throwable $e) {
            return ['status'=>'failed','response'=>$e->getMessage()];
        }
    }

    // ── Log SMS ──────────────────────────────────────────────
    private function log(int $schoolId, string $phone, string $message, string $status, string $provider, string $response): void {
        try {
            $this->db->insert('notifications_log', [
                'school_id'  => $schoolId,
                'type'       => 'sms',
                'recipient'  => $phone,
                'message'    => $message,
                'status'     => $status,
                'provider'   => $provider,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
        } catch (\Throwable $e) {}
    }

    // ── Format phone to international ────────────────────────
    public 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, '254')) $phone = $phone;
        return '+' . ltrim($phone, '+');
    }
}
