<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit;
}

require "../../config/database.php";
require "../../helpers/response.php";

$input = json_decode(file_get_contents("php://input"), true);

$sppg_id = isset($input["sppg_id"]) ? (int) $input["sppg_id"] : 0;
$nama = trim($input["nama"] ?? "");
$jabatan = trim($input["jabatan"] ?? "");
$no_hp = trim($input["no_hp"] ?? "");
$alamat = trim($input["alamat"] ?? "");
$gaji = isset($input["gaji"]) ? (float) $input["gaji"] : 0;
$status = trim($input["status"] ?? "Aktif");

if ($sppg_id <= 0) {
    response(false, "ID SPPG tidak valid", null);
}

if ($nama === "") {
    response(false, "Nama karyawan wajib diisi", null);
}

if ($gaji < 0) {
    response(false, "Gaji tidak boleh negatif", null);
}

$checkSql = "SELECT id FROM sppg WHERE id = ? LIMIT 1";
$checkStmt = $conn->prepare($checkSql);
$checkStmt->bind_param("i", $sppg_id);
$checkStmt->execute();

$checkResult = $checkStmt->get_result();

if ($checkResult->num_rows === 0) {
    response(false, "Data SPPG tidak ditemukan", null);
}

$sql = "
    INSERT INTO karyawan
    (
        sppg_id,
        nama,
        jabatan,
        no_hp,
        alamat,
        gaji,
        status
    )
    VALUES (?, ?, ?, ?, ?, ?, ?)
";

$stmt = $conn->prepare($sql);

$stmt->bind_param(
    "issssds",
    $sppg_id,
    $nama,
    $jabatan,
    $no_hp,
    $alamat,
    $gaji,
    $status
);

if ($stmt->execute()) {
    response(true, "Karyawan berhasil ditambahkan", [
        "id" => $stmt->insert_id
    ]);
}

response(false, "Gagal menambahkan karyawan", null);

?>