<?php
date_default_timezone_set("Asia/Kolkata");
header('Content-Type: application/json');

include('DB.php');

$raw = file_get_contents("php://input");

//file_put_contents(__DIR__ . '/call_debug.log',date('Y-m-d H:i:s') . " REQUEST: " . $raw . PHP_EOL,FILE_APPEND);

$data = json_decode($raw, true);

if (!$data) {
    echo json_encode(array(
        "status"  => "error",
        "message" => "Invalid JSON received"
    ));
    exit;
}

// ---- Fetch Fields (PHP 5.6 SAFE) ----
$followup_id = null;
$number      = null;
$seconds     = 0;

$started_ms  = 0;
$ended_ms    = 0;

if (isset($data['followup_id'])) {
    $followup_id = $data['followup_id'];
}

if (isset($data['number'])) {
    $number = $data['number'];
}

if (isset($data['duration'])) {
    $seconds = (int)$data['duration'];
}

// IMPORTANT – do NOT cast these to int directly
if (isset($data['started_at'])) {
    $started_ms = $data['started_at'];
}

if (isset($data['ended_at'])) {
    $ended_ms = $data['ended_at'];
}

// ---- Validation ----
if (!$followup_id || !$number || $seconds <= 0 || !$started_ms || !$ended_ms) {
    echo json_encode(array(
        "status"  => "error",
        "message" => "Missing or invalid fields from phone"
    ));
    exit;
}

// ---- Format Duration ----
function formatDuration($seconds) {

    if ($seconds < 60) {
        return $seconds . " second";
    }

    $minutes = floor($seconds / 60);
    $remain  = $seconds % 60;

    if ($remain > 0) {
        return $minutes . " minute " . $remain . " second";
    }

    return $minutes . " minute";
}

// ---- Convert milliseconds to readable PHONE time ----
function msToDateTime($ms) {

    $unix = (int)($ms / 1000);

    return date('d-m-Y H:i:s', $unix);
}

$started_at = msToDateTime($started_ms);
$ended_at   = msToDateTime($ended_ms);

// ---- Final JSON to store in DB ----
$final_json = json_encode(array(
    "number"     => $number,
    "duration"   => formatDuration($seconds),
    "started_at" => $started_at,
    "ended_at"   => $ended_at
));

try {

    $bdd = new DB();

    $bdd->execute(
        "UPDATE service_followup SET call_detail = ? WHERE id = ?",
        array($final_json, $followup_id)
    );

    //file_put_contents(__DIR__ . '/call_debug.log',date('Y-m-d H:i:s') . " DB UPDATE ID=$followup_id OK" . PHP_EOL,FILE_APPEND);

    echo json_encode(array(
        "status"      => "success",
        "followup_id" => $followup_id
    ));

    $bdd->disconnect();

} catch (Exception $e) {

    //file_put_contents(__DIR__ . '/call_debug.log',date('Y-m-d H:i:s') . " DB ERROR: " . $e->getMessage() . PHP_EOL,FILE_APPEND);

    echo json_encode(array(
        "status"  => "error",
        "message" => $e->getMessage()
    ));
}

?>
