<?php
include('../dbconnection.php');

$data = $_POST;
$finalStatuses = ['completed', 'no-answer', 'busy', 'failed'];

// Only log/save final states
if (isset($data['CallStatus']) && in_array($data['CallStatus'], $finalStatuses)) {
    // file_put_contents("twilio_events.log", print_r($data, true), FILE_APPEND);
    
    $caller = $data['From'];
    $receiver = $data['Called'];
    $CallStatus = $data['CallStatus'];
    $Duration = $data['RecordingDuration'];
    
    date_default_timezone_set('EST');
    $Date_time = date("d-m-Y h:i:sa");
    
    if(empty($Duration)){
        $Duration = '0';
    }
    if($CallStatus == 'no-answer'){
        $CallStatus = 'Missed';
    }
    if($caller == 'client:Jonathan'){
        $caller = '+13322308524';
    }
     if($receiver == 'client:Jonathan'){
        $receiver = '+13322308524';
    }
    
    $sql = "INSERT INTO Calls (caller, receiver, CallStatus, Duration, Date_time)VALUES ('$caller', '$receiver', '$CallStatus', '$Duration', '$Date_time')";
    
    $insert = mysqli_query($con,$sql);
}

http_response_code(200);
echo "OK";
