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

$dataFile = __DIR__ . '/messages.json';
$webhookLog = __DIR__ . '/webhook_log.json';

// Initialize data if not exists
if (!file_exists($dataFile)) {
    file_put_contents($dataFile, json_encode(['conversations' => []], JSON_PRETTY_PRINT));
}

// Get raw POST data
$input = (string) file_get_contents('php://input');
$data = json_decode($input, true);

// Log webhook call
$log = file_exists($webhookLog) ? json_decode((string) file_get_contents($webhookLog), true) : [];
$log[] = [
    'timestamp' => date('Y-m-d H:i:s'),
    'payload' => $data
];
file_put_contents($webhookLog, json_encode($log, JSON_PRETTY_PRINT));

// Process incoming message
if (isset($data['messages']) && is_array($data['messages'])) {
    $allData = json_decode((string) file_get_contents($dataFile), true);
    if (!isset($allData['conversations'])) {
        $allData['conversations'] = [];
    }

    foreach ($data['messages'] as $msg) {
        $from = trim($msg['from'] ?? $msg['sourceAddress'] ?? '');
        $content = trim($msg['body'] ?? $msg['content'] ?? $msg['message'] ?? '');

        if ($from === '' || $content === '') {
            continue;
        }

        $timestamp = time();
        if (!empty($msg['timestamp'])) {
            $dt = DateTime::createFromFormat(DateTimeInterface::ATOM, $msg['timestamp']);
            if ($dt) {
                $timestamp = $dt->getTimestamp();
            } else {
                $parsed = strtotime($msg['timestamp']);
                $timestamp = $parsed !== false ? $parsed : $timestamp;
            }
        }

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

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

        $allData['conversations'][$conversationIndex]['messages'][] = [
            'id' => uniqid('sms_', true),
            'from' => $from,
            'to' => 'me',
            'body' => $content,
            'timestamp' => $timestamp,
            'direction' => 'received'
        ];
    }

    file_put_contents($dataFile, json_encode($allData, JSON_PRETTY_PRINT));
}

http_response_code(200);
echo json_encode(['status' => 'received']);
?>
