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

error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', 0);

function normalize_requirements($raw)
{
    if ($raw === null || $raw === "") {
        return [];
    }

    $decoded = json_decode($raw, true);
    if (is_array($decoded)) {
        return array_values(array_filter(array_map('trim', $decoded), function ($item) {
            return $item !== '';
        }));
    }

    $lines = preg_split('/\r\n|\r|\n/', (string)$raw);
    return array_values(array_filter(array_map('trim', $lines), function ($item) {
        return $item !== '';
    }));
}

function calculate_posted_days_ago($createdAt)
{
    if (empty($createdAt)) {
        return 0;
    }

    $createdTimestamp = strtotime((string)$createdAt);
    if ($createdTimestamp === false) {
        return 0;
    }

    return max(0, (int)floor((time() - $createdTimestamp) / 86400));
}

$result = $conn->query("SELECT * FROM job_listing ORDER BY id DESC");
$jobs = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $row['requirements'] = normalize_requirements($row['requirements'] ?? '');
        $row['postedDaysAgo'] = calculate_posted_days_ago($row['created_at'] ?? null);
        $jobs[] = $row;
    }
}

echo json_encode($jobs);
$conn->close();
exit;
?>
