<?php
defined('BASEPATH') or exit('No direct script access allowed');

class MessagesController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('firebase');
        $this->load->model('admin/Content_model');
        $this->load->helper('url');
        $this->load->library('twilio_lib');



        // Set JSON header for all responses
    }
    public function messages()
    {
        $data['page_title'] = 'Messages';
        $data['active_menu'] = 'messages';
        $data['content_view'] = 'admin/pages/messages';
        // print_r($data);
        // exit;

        $this->load->view('admin/layouts/main', $data);
    }
    public function sendPush()
    {
        $input = json_decode(file_get_contents("php://input"), true);

        $userId          = $input['userId'] ?? null;
        $message         = $input['message'] ?? '';
        $eventName       = $input['eventName'] ?? 'Event';

        $eventId         = $input['eventId'] ?? null;
        $conversationId  = $input['conversation_id'] ?? null;
        $type = 'chat';

        if (!$userId || !$message || !$eventId || !$conversationId) {
            echo json_encode(['success' => false, 'reason' => 'Missing data']);
            return;
        }

        $user = $this->firebase->getDocument('Users', $userId);

        if (!$user || empty($user['token'])) {
            echo json_encode(['success' => false, 'reason' => 'No FCM token']);
            return;
        }

        $title = "New message from Admin";
        $body  = "{$eventName}: " . mb_strimwidth($message, 0, 80, '...');

        //  PASS IDs TO FCM METHOD
        $result = $this->firebase->sendFCMNotification(
            $user['token'],
            $title,
            $body,
            $eventId,
            $conversationId

        );

        echo json_encode(['success' => (bool)$result]);
    }
    public function send_twillio_message()
    {
        $input = json_decode(file_get_contents('php://input'), true);
        $to_numbers = $input['to'] ?? [];
        $msg = $input['msg'] ?? '';

        if (empty($to_numbers) || empty($msg)) {
            echo json_encode(['status' => 'error', 'message' => 'No numbers or message provided']);
            return;
        }

        $success_numbers = [];
        $failed_numbers = [];

        foreach ($to_numbers as $to) {
            try {
                $response = $this->twilio_lib->send_sms($to, $msg);
                print_r($response);
                die;

                // CORRECT property
                if (isset($response->sid)) {
                    $success_numbers[] = $to;
                } else {
                    $failed_numbers[] = $to;
                }
            } catch (\Twilio\Exceptions\TwilioException $e) {
                log_message('error', "Twilio error for $to: " . $e->getMessage());
                $failed_numbers[] = $to;
            }
        }

        echo json_encode([
            'status' => empty($failed_numbers)
                ? 'success'
                : (empty($success_numbers) ? 'error' : 'partial'),
            'success_numbers' => $success_numbers,
            'failed_numbers' => $failed_numbers
        ]);
    }


    public function textMessage()
    {
        $data['page_title'] = 'text-message';
        $data['active_menu'] = 'text-message';
        $data['content_view'] = 'admin/pages/text-message';
        // print_r($data);
        // exit;

        $this->load->view('admin/layouts/main', $data);
    }

    // public function send_twillio_message()
    // {
    //     $to  = '+923444212152';
    //     $msg = 'Hello from CodeIgniter 3 + Twilio';

    //     try {
    //         $response = $this->twilio_lib->send_sms($to, $msg);

    //         if (isset($response->sid)) {
    //             echo json_encode([
    //                 'status' => 'success',
    //                 'sid' => $response->sid
    //             ]);
    //         } else {
    //             echo json_encode([
    //                 'status' => 'error',
    //                 'message' => 'Message not sent'
    //             ]);
    //         }
    //     } catch (\Twilio\Exceptions\TwilioException $e) {
    //         log_message('error', $e->getMessage());

    //         echo json_encode([
    //             'status' => 'error',
    //             'message' => $e->getMessage()
    //         ]);
    //     }
    // }
}
