<?php
require_once 'TelstraAPI.php';

header('Content-Type: application/json');

$action = $_GET['action'] ?? '';
$dataFile = __DIR__ . '/messages.json';

if (!file_exists($dataFile)) {
    @file_put_contents($dataFile, json_encode(['conversations' => []], JSON_PRETTY_PRINT));
}

function loadConversations()
{
    global $dataFile;
    $data = json_decode((string) @file_get_contents($dataFile), true);
    if (!is_array($data)) {
        $data = [];
    }
    return $data['conversations'] ?? [];
}

function getLastMessageTimestamp(array $conversation): int
{
    if (empty($conversation['messages'])) {
        return 0;
    }
    $lastMsg = end($conversation['messages']);
    return (int) ($lastMsg['timestamp'] ?? 0);
}

function saveConversationsData($conversations)
{
    global $dataFile;
    usort($conversations, function ($a, $b) {
        $aTime = getLastMessageTimestamp($a);
        $bTime = getLastMessageTimestamp($b);
        return $bTime <=> $aTime;
    });
    $data = json_decode((string) @file_get_contents($dataFile), true);
    if (!is_array($data))
        $data = [];
    $data['conversations'] = $conversations;
    @file_put_contents($dataFile, json_encode($data, JSON_PRETTY_PRINT | JSON_INVALID_UTF8_SUBSTITUTE));
}

switch ($action) {
    case 'getConversations':
        $data = json_decode((string) @file_get_contents($dataFile), true);
        if (!is_array($data)) {
            $data = [];
        }
        echo json_encode([
            'conversations' => loadConversations(),
            'provisionedNumber' => $data['provisionedNumber'] ?? null
        ], JSON_INVALID_UTF8_SUBSTITUTE);
        break;

    case 'sendMessage':
        try {
            $input = json_decode((string) file_get_contents('php://input'), true);
            if (!is_array($input)) {
                $input = [];
            }
            $to = trim($input['to'] ?? '');
            $message = trim($input['message'] ?? '');

            if (!$to || !$message) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Missing or empty destination number or message text.']);
                break;
            }

            $msgLength = function_exists('mb_strlen') ? mb_strlen($message) : strlen($message);
            if ($msgLength > 160) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Message too long (max 160 characters).']);
                break;
            }

            $appData = json_decode((string) @file_get_contents($dataFile), true);
            if (!is_array($appData)) {
                $appData = [];
            }
            $from = $appData['provisionedNumber'] ?? null;

            $api = new TelstraAPI();
            $result = $api->sendMessage($to, $message, $from);

            if (!$result['success']) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => $result['error'] ?? 'Failed to send message.']);
                break;
            }

            $conversations = loadConversations();
            $normalizedTo = $to;
            $conversationIndex = -1;

            foreach ($conversations as $idx => $conv) {
                if ($conv['contact'] === $normalizedTo) {
                    $conversationIndex = $idx;
                    break;
                }
            }

            if ($conversationIndex === -1) {
                $conversations[] = [
                    'contact' => $normalizedTo,
                    'messages' => []
                ];
                $conversationIndex = count($conversations) - 1;
            }

            $conversations[$conversationIndex]['messages'][] = [
                'id' => $result['messageId'] ?? 'msg_' . time(),
                'from' => 'me',
                'to' => $normalizedTo,
                'body' => $message,
                'timestamp' => time(),
                'direction' => 'sent'
            ];

            saveConversationsData($conversations);
            echo json_encode(['success' => true, 'messageId' => $result['messageId'] ?? 'msg_' . time()]);
        } catch (\Throwable $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Server Error: ' . $e->getMessage()]);
        }
        break;

    case 'saveConversations':
        $input = json_decode((string) file_get_contents('php://input'), true);
        if (!is_array($input)) {
            $input = [];
        }
        $conversations = $input['conversations'] ?? [];
        saveConversationsData($conversations);
        echo json_encode(['success' => true]);
        break;

    case 'provisionNumber':
        try {
            $api = new TelstraAPI();
            $result = $api->provisionNumber();
            if ($result['success']) {
                $data = json_decode((string) @file_get_contents($dataFile), true);
                if (!is_array($data))
                    $data = [];
                $data['provisionedNumber'] = $result['number'];
                @file_put_contents($dataFile, json_encode($data, JSON_PRETTY_PRINT | JSON_INVALID_UTF8_SUBSTITUTE));
                echo json_encode($result, JSON_INVALID_UTF8_SUBSTITUTE);
            } else {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => $result['error'] ?? 'Failed to provision number.'], JSON_INVALID_UTF8_SUBSTITUTE);
            }
        } catch (\Throwable $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Server Error: ' . $e->getMessage()]);
        }
        break;

    default:
        http_response_code(400);
        echo json_encode(['error' => 'Unknown action.']);
        break;
}