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

// Disable warnings/notices from leaking into JSON
error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', 0);

function parse_requirements($raw)
{
    if ($raw === null || $raw === '') {
        return [];
    }

    $decoded = json_decode((string)$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 !== '';
    }));
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        "status" => "error",
        "message" => "Invalid request method"
    ]);
    $conn->close();
    exit;
}

$id = (int)($_POST['id'] ?? 0);
$title = trim((string)($_POST['title'] ?? ''));
$type = trim((string)($_POST['type'] ?? ''));
$experience = trim((string)($_POST['experience'] ?? ''));
$salary = trim((string)($_POST['salary'] ?? ''));
$location = trim((string)($_POST['location'] ?? ''));
$description = trim((string)($_POST['description'] ?? ''));
$requirements = json_encode(parse_requirements($_POST['requirements'] ?? ''));

if ($id <= 0) {
    echo json_encode([
        "status" => "error",
        "message" => "Missing job ID"
    ]);
    $conn->close();
    exit;
}

$stmt = $conn->prepare(
    "UPDATE job_listing
     SET title = ?,
         type = ?,
         experience = ?,
         salary = ?,
         location = ?,
         description = ?,
         requirements = ?
     WHERE id = ?"
);

if (!$stmt) {
    echo json_encode([
        "status" => "error",
        "message" => "Database error: " . $conn->error
    ]);
    $conn->close();
    exit;
}

$stmt->bind_param("sssssssi", $title, $type, $experience, $salary, $location, $description, $requirements, $id);

if ($stmt->execute()) {
    echo json_encode([
        "status" => "success",
        "message" => "Job updated successfully"
    ]);
} else {
    echo json_encode([
        "status" => "error",
        "message" => "Database error: " . $stmt->error
    ]);
}

$stmt->close();
$conn->close();
exit;
?>
