<?php

namespace App\Controllers;

use App\Libraries\SmsExecutor;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\RESTful\ResourceController;

class SmsController extends ResourceController
{
    use ResponseTrait;

    protected $modelName = 'App\Models\UserModel';
    protected $format    = 'json';

    private $smsExecutor;

    public function __construct()
    {
        $this->smsExecutor = new SmsExecutor();
    }

    /**
     * Send SMS notification - Modern CI4 endpoint
     * POST /api/sms/send
     */
    public function send()
    {
        $data = $this->request->getJSON();

        $phone = $data->phone ?? null;
        $message = $data->message ?? null;
        $reference = $data->reference ?? null;

        if (empty($phone) || empty($message)) {
            return $this->failValidationErrors([
                'phone' => 'Phone number is required',
                'message' => 'Message is required'
            ]);
        }

        // Normalize phone number
        $normalizedPhone = $this->normalizePhoneNumber($phone);

        // Send SMS
        $sent = $this->smsExecutor->sendSms($normalizedPhone, $message, $reference);

        if ($sent) {
            return $this->respond([
                'status' => 'success',
                'message' => 'SMS sent successfully',
                'phone' => $normalizedPhone
            ]);
        } else {
            return $this->fail('Failed to send SMS');
        }
    }

    /**
     * Send welcome SMS on user registration
     * POST /api/sms/welcome
     */
    public function sendWelcome()
    {
        $data = $this->request->getJSON();

        $phone = $data->phone ?? null;
        $name = $data->name ?? 'Mshiriki';

        if (empty($phone)) {
            return $this->failValidationErrors(['phone' => 'Phone number is required']);
        }

        $message = "Karibu DevanEvents.\n"
                 . "Ahsante kwa kujisajili, {$name}. Usajili wako umekamilika. Sasa unaweza kutafuta mikutano, kujisajili na kununua tiketi kupitia mfumo wetu. – Timu ya DevanEvents";

        $normalizedPhone = $this->normalizePhoneNumber($phone);
        $sent = $this->smsExecutor->sendSms($normalizedPhone, $message, 'welcome_' . time());

        return $this->respond([
            'status' => $sent ? 'success' : 'error',
            'message' => $sent ? 'Welcome SMS sent' : 'Failed to send welcome SMS',
            'sms_sent' => $sent
        ]);
    }

    /**
     * Send event registration confirmation SMS
     * POST /api/sms/event-registration
     */
    public function sendEventRegistration()
    {
        $data = $this->request->getJSON();

        $phone = $data->phone ?? null;
        $eventName = $data->event_name ?? 'Mkutano';
        $eventDate = $data->event_date ?? '';
        $eventTime = $data->event_time ?? '';
        $ticketCode = $data->ticket_code ?? '';

        if (empty($phone)) {
            return $this->failValidationErrors(['phone' => 'Phone number is required']);
        }

        $message = "✅ Devanevents: Usajili kufaulu!\n\n"
                 . "Umejisajili kwa: {$eventName}\n";

        if (!empty($eventDate)) {
            $message .= "📅 Tarehe: {$eventDate}\n";
        }
        if (!empty($eventTime)) {
            $message .= "⏰ Muda: {$eventTime}\n";
        }
        if (!empty($ticketCode)) {
            $message .= "🎫 Namba ya Tiketi: {$ticketCode}\n";
        }

        $message .= "\n📧 Tulipokea usajili wako. Tiketi yako itumwe kwa barua pepe yako.\n\n"
                   . "TIMU YA DEVANEVENTS 🎊";

        $normalizedPhone = $this->normalizePhoneNumber($phone);
        $sent = $this->smsExecutor->sendSms($normalizedPhone, $message, 'event_reg_' . time());

        return $this->respond([
            'status' => $sent ? 'success' : 'error',
            'message' => $sent ? 'Event registration SMS sent' : 'Failed to send SMS',
            'sms_sent' => $sent
        ]);
    }

    /**
     * Send payment confirmation SMS
     * POST /api/sms/payment-confirmation
     */
    public function sendPaymentConfirmation()
    {
        $data = $this->request->getJSON();

        $phone = $data->phone ?? null;
        $amount = $data->amount ?? '';
        $eventName = $data->event_name ?? 'Mkutano';
        $ticketCode = $data->ticket_code ?? '';

        if (empty($phone)) {
            return $this->failValidationErrors(['phone' => 'Phone number is required']);
        }

        $message = "🎉 Devanevents: Malipo kulu!\n\n"
                 . "✅ Tumepokea malipo yako: TZS " . number_format($amount, 0, '.', ',') . "\n"
                 . "📌 Kwa: {$eventName}\n";

        if (!empty($ticketCode)) {
            $message .= "🎫 Namba ya Tiketi: {$ticketCode}\n";
        }

        $message .= "\n📧 Tiketi yako imetumwa kwa barua pepe yako.\n"
                   . "🌟 Asante kwa kushiriki nasi!\n\n"
                   . "TIMU YA DEVANEVENTS 🎊";

        $normalizedPhone = $this->normalizePhoneNumber($phone);
        $sent = $this->smsExecutor->sendSms($normalizedPhone, $message, 'payment_' . time());

        return $this->respond([
            'status' => $sent ? 'success' : 'error',
            'message' => $sent ? 'Payment confirmation SMS sent' : 'Failed to send SMS',
            'sms_sent' => $sent
        ]);
    }

    /**
     * Send ticket reminder SMS
     * POST /api/sms/ticket-reminder
     */
    public function sendTicketReminder()
    {
        $data = $this->request->getJSON();

        $phone = $data->phone ?? null;
        $eventName = $data->event_name ?? 'Mkutano';
        $eventDate = $data->event_date ?? '';
        $eventTime = $data->event_time ?? '';
        $ticketCode = $data->ticket_code ?? '';

        if (empty($phone)) {
            return $this->failValidationErrors(['phone' => 'Phone number is required']);
        }

        $message = "🔔 Devanevents: Ukumbusho wa Tiketi!\n\n"
                 . "⏰ Usisahau - {$eventName}\n";

        if (!empty($eventDate)) {
            $message .= "📅 Tarehe: {$eventDate}\n";
        }
        if (!empty($eventTime)) {
            $message .= "⏰ Muda: {$eventTime}\n";
        }

        $message .= "🎫 Tiketi Namba: {$ticketCode}\n\n"
                   . "🌟 Tunangojea kukuona huko!\n\n"
                   . "TIMU YA DEVANEVENTS 🎊";

        $normalizedPhone = $this->normalizePhoneNumber($phone);
        $sent = $this->smsExecutor->sendSms($normalizedPhone, $message, 'reminder_' . time());

        return $this->respond([
            'status' => $sent ? 'success' : 'error',
            'message' => $sent ? 'Reminder SMS sent' : 'Failed to send SMS',
            'sms_sent' => $sent
        ]);
    }

    /**
     * Send bulk SMS to multiple recipients
     * POST /api/sms/bulk
     */
    public function sendBulk()
    {
        $data = $this->request->getJSON();

        $recipients = $data->recipients ?? [];
        $message = $data->message ?? null;

        if (empty($recipients) || empty($message)) {
            return $this->failValidationErrors([
                'recipients' => 'Recipients array is required',
                'message' => 'Message is required'
            ]);
        }

        $sent = 0;
        $failed = 0;

        foreach ($recipients as $recipient) {
            $phone = $recipient->phone ?? null;
            if (empty($phone)) continue;

            $normalizedPhone = $this->normalizePhoneNumber($phone);
            if ($this->smsExecutor->sendSms($normalizedPhone, $message, 'bulk_' . time())) {
                $sent++;
            } else {
                $failed++;
            }

            // Small delay to avoid rate limiting
            usleep(100000); // 0.1 second
        }

        return $this->respond([
            'status' => 'success',
            'message' => "Bulk SMS completed",
            'sent' => $sent,
            'failed' => $failed,
            'total' => count($recipients)
        ]);
    }

    /**
     * Test SMS endpoint
     * GET /api/sms/test
     */
    public function test()
    {
        $phone = $this->request->getGet('phone') ?? '+255715465042';
        $message = "🧪 Devanevents: Test SMS kutoka mfumo. System inafanya kazi vizuri! ✅";

        $normalizedPhone = $this->normalizePhoneNumber($phone);
        $sent = $this->smsExecutor->sendSms($normalizedPhone, $message, 'test_' . time());

        return $this->respond([
            'status' => $sent ? 'success' : 'error',
            'message' => $sent ? 'Test SMS sent successfully' : 'Failed to send test SMS',
            'phone' => $normalizedPhone
        ]);
    }

    /**
     * Normalize phone number to international format
     */
    private function normalizePhoneNumber($phone)
    {
        // Remove any non-numeric characters except +
        $phone = preg_replace('/[^0-9+]/', '', $phone);

        // Add + prefix if not present
        if (substr($phone, 0, 1) !== '+') {
            // Assume Tanzanian number if starts with 255
            if (substr($phone, 0, 3) === '255') {
                $phone = '+' . $phone;
            } elseif (substr($phone, 0, 1) === '0') {
                // Convert 07xx to +2557xx
                $phone = '+255' . substr($phone, 1);
            } else {
                $phone = '+' . $phone;
            }
        }

        return $phone;
    }

    /**
     * Legacy SMS controller methods (kept for backward compatibility)
     */
    public function password_recovery()
    {
        // Legacy method - redirect to modern endpoint or implement here
        log_message('debug', 'Legacy password_recovery called');
        return $this->respond(['message' => 'Use modern API endpoints']);
    }

    public function verify_reset()
    {
        log_message('debug', 'Legacy verify_reset called');
        return $this->respond(['message' => 'Use modern API endpoints']);
    }

    public function send_notification()
    {
        log_message('debug', 'Legacy send_notification called');
        return $this->respond(['message' => 'Use modern API endpoints']);
    }
}
