<?php

/**
 * UltyScan Web Interface - Git Version Info
 * Reads version from .version file (created during deployment)
 */

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

$versionFile = __DIR__ . '/.version';

// Default values
$data = [
    'commit' => '',
    'fullCommit' => '',
    'branch' => '',
    'date' => '',
    'age' => '',
    'timestamp' => false
];

// Try reading from .version file first
if (file_exists($versionFile)) {
    $lines = file($versionFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (count($lines) >= 4) {
        $data['commit'] = trim($lines[0]);
        $data['fullCommit'] = trim($lines[1]);
        $data['branch'] = trim($lines[2]);
        $data['date'] = trim($lines[3]);
        $data['timestamp'] = strtotime($data['date']);
    }
}

// Calculate age if we have a timestamp
if ($data['timestamp']) {
    $diff = time() - $data['timestamp'];

    if ($diff < 60) {
        $data['age'] = $diff . ' seconds ago';
    } elseif ($diff < 3600) {
        $mins = floor($diff / 60);
        $data['age'] = $mins . ' minute' . ($mins > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 86400) {
        $hours = floor($diff / 3600);
        $data['age'] = $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 604800) {
        $days = floor($diff / 86400);
        $data['age'] = $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 2592000) {
        $weeks = floor($diff / 604800);
        $data['age'] = $weeks . ' week' . ($weeks > 1 ? 's' : '') . ' ago';
    } else {
        $months = floor($diff / 2592000);
        $data['age'] = $months . ' month' . ($months > 1 ? 's' : '') . ' ago';
    }
}

echo json_encode($data);
