<?php
ob_clean();
header("Content-Type: application/json");

// 🔒 MATIKAN HTML ERROR
error_reporting(E_ALL);
ini_set('display_errors', 0);

// 🔥 ERROR → JSON
set_error_handler(function ($severity, $message, $file, $line) {
    echo json_encode([
        "success" => false,
        "message" => "PHP Error: $message"
    ]);
    exit;
});

require_once __DIR__ . '/config/koneksi.php';
require_once __DIR__ . '/config/jwt.php';

// ================= TOKEN =================
function getAuthHeader() {
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        return $_SERVER['HTTP_AUTHORIZATION'];
    } elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        return $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    } elseif (function_exists('getallheaders')) {
        $headers = getallheaders();
        return $headers['Authorization'] ?? $headers['authorization'] ?? '';
    }
    return '';
}

$auth = getAuthHeader();

if (!$auth) {
    echo json_encode(["success"=>false,"message"=>"Unauthorized"]);
    exit;
}

$token = str_replace("Bearer ", "", $auth);
$userData = verifyJWT($token);

if (!$userData) {
    echo json_encode(["success"=>false,"message"=>"Token invalid"]);
    exit;
}

$userId = $userData['user_id'] ?? null;

if (!$userId) {
    echo json_encode(["success"=>false,"message"=>"User tidak valid"]);
    exit;
}

// ================= VALIDASI REQUEST =================
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        "success" => false,
        "message" => "Method harus POST"
    ]);
    exit;
}

if (empty($_POST) && empty($_FILES)) {
    echo json_encode([
        "success" => false,
        "message" => "Format request tidak terbaca"
    ]);
    exit;
}

// ================= INPUT =================
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$password = $_POST['password'] ?? '';

if ($name === '') {
    echo json_encode(["success"=>false,"message"=>"Nama wajib"]);
    exit;
}

$now = date('Y-m-d H:i:s');




// ================= UPDATE =================
$stmt = null;

if (!empty($password) && strlen($password) >= 6) {

    $hash = password_hash($password, PASSWORD_BCRYPT);

   
       
        $stmt = $conn->prepare("
            UPDATE app_users 
            SET name=?, password=?, updated_at=? 
            WHERE id=?
        ");

        if (!$stmt) {
            echo json_encode(["success"=>false,"message"=>$conn->error]);
            exit;
        }

        $stmt->bind_param("ssss", $name, $hash, $now, $userId);
   

} else {


        $stmt = $conn->prepare("
            UPDATE app_users 
            SET name=?, updated_at=? 
            WHERE id=?
        ");

        if (!$stmt) {
            echo json_encode(["success"=>false,"message"=>$conn->error]);
            exit;
        }

        $stmt->bind_param("sss", $name, $now, $userId);
    
}

// ================= EXECUTE =================
if (!$stmt->execute()) {
    echo json_encode([
        "success" => false,
        "message" => $stmt->error
    ]);
    exit;
}

// ================= RESPONSE =================
echo json_encode([
    "success" => true,
    "message" => "Profil berhasil diupdate"
]);