<?php

namespace App\Core;

/**
 * إرسال رسائل SMS (Twilio / Unifonic)
 */
class SMS
{
    private \PDO $db;
    private array $config;
    private int $tenantId;

    public function __construct(\PDO $db, array $config, int $tenantId = 1)
    {
        $this->db = $db;
        $this->config = $config;
        $this->tenantId = $tenantId;
    }

    public function isEnabled(): bool
    {
        return !empty($this->config['enabled']) && !empty($this->config['app_sid'] ?? $this->config['account_sid'] ?? '');
    }

    /**
     * إرسال SMS
     * @return array{success: bool, message?: string, error?: string}
     */
    public function send(string $to, string $message): array
    {
        if (!$this->isEnabled()) {
            return ['success' => false, 'error' => 'SMS غير مفعّل'];
        }

        $to = preg_replace('/\D/', '', $to);
        if (strlen($to) < 8) {
            return ['success' => false, 'error' => 'رقم هاتف غير صالح'];
        }

        $provider = strtolower($this->config['provider'] ?? 'unifonic');

        if ($provider === 'twilio') {
            return $this->sendTwilio($to, $message);
        }

        return $this->sendUnifonic($to, $message);
    }

    private function sendTwilio(string $to, string $message): array
    {
        $sid = $this->config['account_sid'] ?? $this->config['app_sid'] ?? '';
        $token = $this->config['auth_token'] ?? '';

        if ($sid === '' || $token === '') {
            return ['success' => false, 'error' => 'إعدادات Twilio غير مكتملة'];
        }

        $from = $this->config['from_number'] ?? $this->config['sender_id'] ?? '';

        $url = 'https://api.twilio.com/2010-04-01/Accounts/' . $sid . '/Messages.json';
        $body = http_build_query([
            'To' => '+' . $to,
            'From' => $from ?: $sid,
            'Body' => $message
        ]);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_USERPWD => $sid . ':' . $token,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded']
        ]);
        $resp = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($code >= 200 && $code < 300) {
            return ['success' => true];
        }

        $err = json_decode($resp, true);
        return ['success' => false, 'error' => $err['message'] ?? 'فشل إرسال الرسالة'];
    }

    private function sendUnifonic(string $to, string $message): array
    {
        $appSid = $this->config['app_sid'] ?? '';
        $senderId = $this->config['sender_id'] ?? '';

        if ($appSid === '') {
            return ['success' => false, 'error' => 'إعدادات Unifonic غير مكتملة'];
        }

        $url = 'https://api.unifonic.com/rest/Messages/Send';
        $payload = json_encode([
            'AppSid' => $appSid,
            'SenderID' => $senderId ?: null,
            'Body' => $message,
            'Recipient' => $to
        ]);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json']
        ]);
        $resp = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $data = json_decode($resp, true);

        if ($code >= 200 && $code < 300 && !empty($data['success']) && $data['success'] === true) {
            return ['success' => true];
        }

        return ['success' => false, 'error' => $data['message'] ?? 'فشل إرسال الرسالة'];
    }

    /**
     * إرسال إشعار بجاهزية النتائج للمريض
     */
    public function sendResultsReady(int $orderId, int $patientId): bool
    {
        try {
            $stmt = $this->db->prepare(
                'SELECT p.phone, o.order_number FROM patients p JOIN lab_orders o ON o.patient_id = p.id WHERE p.id = ? AND o.id = ?'
            );
            $stmt->execute([$patientId, $orderId]);
            $row = $stmt->fetch();
            if (!$row || empty(trim($row['phone'] ?? ''))) {
                return false;
            }

            $msg = 'نتائج تحاليلك جاهزة. رقم الطلب: ' . ($row['order_number'] ?? $orderId);
            $r = $this->send($row['phone'], $msg);
            return $r['success'];
        } catch (\Throwable $e) {
            return false;
        }
    }

    /**
     * إرسال تذكير بدين
     */
    public function sendDebtReminder(int $patientId, float $amount, string $invoiceNumbers = ''): bool
    {
        try {
            $stmt = $this->db->prepare('SELECT phone FROM patients WHERE id = ?');
            $stmt->execute([$patientId]);
            $row = $stmt->fetch();
            if (!$row || empty(trim($row['phone'] ?? ''))) {
                return false;
            }

            $msg = 'تذكير: لديك مبلغ متبقي ' . number_format($amount, 0) . ' د.ع';
            if ($invoiceNumbers !== '') {
                $msg .= ' - فواتير: ' . $invoiceNumbers;
            }
            $r = $this->send($row['phone'], $msg);
            return $r['success'];
        } catch (\Throwable $e) {
            return false;
        }
    }
}
