<?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;
}

$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 ($title === '') {
    echo json_encode([
        "status" => "error",
        "message" => "Job title is required"
    ]);
    $conn->close();
    exit;
}

$stmt = $conn->prepare(
    "INSERT INTO job_listing (title, type, experience, salary, location, description, requirements)
     VALUES (?, ?, ?, ?, ?, ?, ?)"
);

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

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

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

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