<?php
/**
 * API: استقبال الرسائل الجديدة
 * GET /api/poll.php?since=TIMESTAMP
 */

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

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    jsonResponse(['error' => 'Method not allowed'], 405);
}

if (!isset($_SESSION['whatsapp_number'])) {
    jsonResponse(['error' => 'لا توجد جلسة نشطة'], 401);
}

$phone = $_SESSION['whatsapp_number'];
$since = intval($_GET['since'] ?? 0);

$newMessages = getNewMessages($phone, $since);

$formatted = array_map(function($msg) {
    return [
        'id'        => $msg['id'],
        'body'      => htmlspecialchars($msg['body'], ENT_QUOTES, 'UTF-8'),
        'timestamp' => $msg['timestamp'],
        'direction' => $msg['direction'],
        'type'      => $msg['type'] ?? 'text',
        'status'    => $msg['status'] ?? 'delivered',
    ];
}, $newMessages);

jsonResponse([
    'success'  => true,
    'messages' => $formatted,
    'count'    => count($formatted),
]);
