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

// Fetch calls (latest first)
$sql = "SELECT 
            c.id, 
            c.caller, 
            c.receiver, 
            c.CallStatus, 
            c.Duration, 
            c.Date_time,
            COALESCE(ct1.name, c.caller) AS caller_name,
            COALESCE(ct2.name, c.receiver) AS receiver_name
        FROM Calls c
        LEFT JOIN Contact ct1 ON c.caller = ct1.from_number
        LEFT JOIN Contact ct2 ON c.receiver = ct2.from_number
        ORDER BY c.id DESC";

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

$calls = [];
while ($row = $result->fetch_assoc()) {
    $calls[] = $row;
}

echo json_encode($calls);
