<?php

namespace App\Modules\TextMagic\Services;

use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use App\Modules\Bookings\CustomerNotification;
use App\Models\Setting;

class TextMagicService implements TextMagicServiceInterface
{
    protected string $username;
    protected string $apiKey;
    protected string $baseUrl = 'https://rest.textmagic.com/api/v2';

    public function __construct()
    {
        $this->username = Setting::get('integrations.textmagic.username', '');
        $this->apiKey = Setting::get('integrations.textmagic.api_key', '');
    }

    /**
     * Send SMS message
     */
    public function sendSMS(string $to, string $message, ?array $options = []): array
    {
        try {
            $to = $this->formatPhoneNumber($to);

            if (!$this->validatePhoneNumber($to)) {
                throw new Exception('Invalid phone number format');
            }

            if (empty($this->username) || empty($this->apiKey)) {
                throw new Exception('TextMagic not configured. Please check your settings.');
            }

            $response = Http::withBasicAuth($this->username, $this->apiKey)
                ->asForm()
                ->post($this->baseUrl . '/messages', [
                    'text' => $message,
                    'phones' => $to
                ]);

            if (!$response->successful()) {
                $error = $response->json('message') ?? 'Failed to send SMS';
                throw new Exception($error);
            }

            $data = $response->json();

            Log::info('[TEXTMAGIC] SMS sent', [
                'id' => $data['id'] ?? null,
                'to' => $to,
                'status' => $data['sessionId'] ?? 'sent'
            ]);

            return [
                'success' => true,
                'message_id' => $data['id'] ?? null,
                'session_id' => $data['sessionId'] ?? null,
                'status' => 'sent',
                'to' => $to
            ];

        } catch (Exception $e) {
            Log::error('[TEXTMAGIC] SMS failed', [
                'to' => $to,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * Send SMS with task context
     */
    public function sendTaskSMS(int $taskId, string $to, string $message): array
    {
        try {
            Log::info('[TEXTMAGIC] Sending task SMS', ['task_id' => $taskId, 'to' => $to]);

            $result = $this->sendSMS($to, $message);

            if ($result['success']) {
                $notification = CustomerNotification::create([
                    'type' => 'sms',
                    'sent_to' => $to,
                    'message' => $message,
                    'task_id' => $taskId,
                    'subject' => 'Task SMS Notification',
                    'message_sid' => $result['message_id'] ?? null
                ]);

                $result['notification_id'] = $notification->id;
            }

            return $result;

        } catch (Exception $e) {
            Log::error('[TEXTMAGIC] Failed to send task SMS', [
                'task_id' => $taskId,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * Send completion notification SMS
     */
    public function sendCompletionSMS(int $taskId, string $to, string $message): array
    {
        try {
            Log::info('[TEXTMAGIC] Sending completion SMS', ['task_id' => $taskId, 'to' => $to]);

            $result = $this->sendSMS($to, $message);

            if ($result['success']) {
                $notification = CustomerNotification::create([
                    'type' => 'sms',
                    'sent_to' => $to,
                    'message' => $message,
                    'task_id' => $taskId,
                    'subject' => 'Task Completion Notification',
                    'message_sid' => $result['message_id'] ?? null
                ]);

                $result['notification_id'] = $notification->id;
            }

            return $result;

        } catch (Exception $e) {
            Log::error('[TEXTMAGIC] Failed to send completion SMS', [
                'task_id' => $taskId,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * Test SMS configuration
     */
    public function testSMS(string $to, string $message): array
    {
        return $this->sendSMS($to, $message);
    }

    /**
     * Test credentials
     */
    public function testCredentials(): array
    {
        try {
            if (empty($this->username) || empty($this->apiKey)) {
                throw new Exception('Username and API Key are required');
            }

            $response = Http::withBasicAuth($this->username, $this->apiKey)
                ->get($this->baseUrl . '/user');

            if (!$response->successful()) {
                throw new Exception('Invalid credentials');
            }

            $userData = $response->json();

            return [
                'success' => true,
                'valid' => true,
                'user_info' => [
                    'username' => $userData['username'] ?? null,
                    'firstName' => $userData['firstName'] ?? null,
                    'lastName' => $userData['lastName'] ?? null,
                    'balance' => $userData['balance'] ?? null
                ]
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'valid' => false,
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * Validate phone number format
     */
    public function validatePhoneNumber(string $phoneNumber): bool
    {
        // Basic validation
        $cleaned = preg_replace('/[^0-9+]/', '', $phoneNumber);
        return strlen($cleaned) >= 10 && strlen($cleaned) <= 15;
    }

    /**
     * Format phone number for TextMagic
     */
    public function formatPhoneNumber(string $phoneNumber): string
    {
        // Remove all non-numeric characters except +
        $cleaned = preg_replace('/[^0-9+]/', '', $phoneNumber);

        // If UK number starts with 0, replace with +44
        if (preg_match('/^0/', $cleaned)) {
            $cleaned = preg_replace('/^0/', '44', $cleaned);
        }

        // Remove + prefix if present (TextMagic expects numbers without +)
        $cleaned = ltrim($cleaned, '+');

        return $cleaned;
    }
}
