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

$conn = new mysqli("localhost","srichitr_rajeevverma","jaimatadi131265","srichitraguptji_safetyapp");
if ($conn->connect_error) die("DB Error");

// active emergency sessions
$sql = "
SELECT DISTINCT 
    es.user_id,
    es.last_location,
    ec.contact_phone,
    u.name
FROM active_sessions es
JOIN emergency_contacts ec ON es.user_id = ec.user_id
JOIN users u ON es.user_id = u.id
WHERE es.status = 'EMERGENCY_TRIGGERED'
AND ec.called = 0
";

$result = $conn->query($sql);

if (!$result) {
    echo json_encode(['status'=>0,'error'=>$conn->error]);
    exit;
}

$data = [];
$action = "sms";
while ($row = $result->fetch_assoc()) {

    $name = trim($row['name']);
    $mobile = trim($row['contact_phone']);
    $location = trim($row['last_location']);

    if (!$mobile) continue;

    if (!$name) $name = "Your contact";

    //$message = $name . " needs immediate help. Last known location: " . $location; 94+50
    $message = "Emergency alert! " . $name .
           " needs immediate help. Last known location: " . $location;
           //". Please contact immediately.";

    $data[] = [
        "mobile" => $mobile,
        "message" => $message,
        "action" => $action
    ];
}

echo json_encode($data, JSON_UNESCAPED_SLASHES);