<?php
header('Content-Type: application/json');
include '../includes/db_connect.php';

// Xác thực thiết bị
$apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
$deviceId = $_SERVER['HTTP_X_DEVICE_ID'] ?? '';

if (empty($apiKey) || empty($deviceId)) {
    http_response_code(401);
    echo json_encode(['error' => 'Thông tin xác thực bị thiếu.']);
    exit();
}

$stmt = $conn->prepare("SELECT user_id FROM devices WHERE api_key = ? AND id = ? AND status = 'active'");
$stmt->bind_param("si", $apiKey, $deviceId);
$stmt->execute();
$result = $stmt->get_result();
$device = $result->fetch_assoc();

if (!$device) {
    http_response_code(401);
    echo json_encode(['error' => 'Thông tin xác thực không hợp lệ.']);
    exit();
}
$userId = $device['user_id'];

// Lấy tin nhắn đang chờ
$conn->begin_transaction();
try {
    $stmt = $conn->prepare("SELECT id, phone_number, message FROM messages WHERE user_id = ? AND status = 'pending' AND schedule_time <= NOW() ORDER BY schedule_time ASC LIMIT 1 FOR UPDATE");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    $message = $result->fetch_assoc();

    if ($message) {
        $updateStmt = $conn->prepare("UPDATE messages SET status = 'sending' WHERE id = ?");
        $updateStmt->bind_param("i", $message['id']);
        $updateStmt->execute();
        $conn->commit();
        echo json_encode(['status' => 'success', 'data' => $message]);
    } else {
        $conn->commit();
        echo json_encode(['status' => 'success', 'data' => null]);
    }
} catch (Exception $e) {
    $conn->rollback();
    http_response_code(500);
    echo json_encode(['error' => 'Lỗi cơ sở dữ liệu: ' . $e->getMessage()]);
}

if (isset($stmt)) $stmt->close();
$conn->close();
?>