<?php

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

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

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

$id = isset($_GET["id"]) ? (int) $_GET["id"] : 0;

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

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

$username = trim($input["username"] ?? "");
$nama = trim($input["nama"] ?? "");
$email = trim($input["email"] ?? "");
$password = trim($input["password"] ?? "");
$role = trim($input["role"] ?? "sppg");
$status = trim($input["status"] ?? "Aktif");

if ($username === "" || $nama === "" || $email === "") {
    response(false, "Username, nama, dan email wajib diisi", null);
}

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

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

$duplicateSql = "SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ? LIMIT 1";
$duplicateStmt = $conn->prepare($duplicateSql);
$duplicateStmt->bind_param("ssi", $username, $email, $id);
$duplicateStmt->execute();
$duplicateResult = $duplicateStmt->get_result();

if ($duplicateResult->num_rows > 0) {
    response(false, "Username atau email sudah digunakan user lain", null);
}

if ($password !== "") {
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    $sql = "
        UPDATE users
        SET
            username = ?,
            nama = ?,
            email = ?,
            password = ?,
            role = ?,
            status = ?
        WHERE id = ?
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssssssi", $username, $nama, $email, $hashedPassword, $role, $status, $id);
} else {
    $sql = "
        UPDATE users
        SET
            username = ?,
            nama = ?,
            email = ?,
            role = ?,
            status = ?
        WHERE id = ?
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssssi", $username, $nama, $email, $role, $status, $id);
}

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

response(false, "Gagal memperbarui user", null);

?>