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

$validApiKeys = [
    "api_key_1" => ["device_ip" => "192.168.1.25:8080", "status" => "active"], // Thay IP điện thoại của bạn
    "api_key_2" => ["device_ip" => "10.224.129.89", "status" => "active"]
];

$data = json_decode(file_get_contents('php://input'), true);

if (!$data || !isset($data['api_key']) || !isset($data['to']) || !isset($data['message'])) {
    http_response_code(400);
    echo json_encode(["error" => "Missing required fields"]);
    exit;
}

$apiKey = $data['api_key'];
$to = $data['to'];
$message = $data['message'];

if (!isset($validApiKeys[$apiKey]) || $validApiKeys[$apiKey]['status'] !== "active") {
    http_response_code(401);
    echo json_encode(["error" => "Invalid API key"]);
    exit;
}

$deviceIp = $validApiKeys[$apiKey]['device_ip'];
$commandUrl = "http://$deviceIp/send"; // Endpoint trên điện thoại (cần điều chỉnh sau)

$commandData = ["action" => "send_sms", "to" => $to, "message" => $message];
$ch = curl_init($commandUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($commandData));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode == 200) {
    echo json_encode(["status" => "success", "response" => $response]);
} else {
    http_response_code($httpCode);
    echo json_encode(["error" => "Failed to send", "code" => $httpCode]);
}
?>