<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept');

ob_start();

function respond(int $status_code, array $payload): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    http_response_code($status_code);
    echo json_encode($payload);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    respond(204, []);
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    respond(405, ['success' => false, 'message' => 'Method tidak dibenarkan.']);
}

require_once __DIR__ . '/../db.php';

$payload = json_decode(file_get_contents('php://input') ?: '', true);
if (!is_array($payload)) {
    $payload = $_POST;
}

$user_id = (int) ($payload['user_id'] ?? 0);
if ($user_id <= 0) {
    respond(422, ['success' => false, 'message' => 'Pengguna tidak sah.']);
}

$stmt = mysqli_prepare(
    $conn,
    'SELECT id, fullname, short_name, ic_number, email, department, status, role, position, signature_path, profile_photo
     FROM users
     WHERE id = ? AND status = "approved"
     LIMIT 1'
);

if (!$stmt) {
    respond(500, ['success' => false, 'message' => 'Profil tidak dapat dimuatkan.']);
}

mysqli_stmt_bind_param($stmt, 'i', $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user = $result ? mysqli_fetch_assoc($result) : null;

if (!$user) {
    respond(404, ['success' => false, 'message' => 'Profil pengguna tidak ditemui.']);
}

respond(200, [
    'success' => true,
    'user' => [
        'id' => (int) $user['id'],
        'fullname' => (string) ($user['fullname'] ?? ''),
        'shortName' => (string) ($user['short_name'] ?? ''),
        'identityCard' => (string) ($user['ic_number'] ?? ''),
        'email' => (string) ($user['email'] ?? ''),
        'department' => (string) ($user['department'] ?? ''),
        'role' => (string) ($user['role'] ?? 'user'),
        'position' => (string) ($user['position'] ?? ''),
        'signaturePath' => (string) ($user['signature_path'] ?? ''),
        'profileImage' => (string) ($user['profile_photo'] ?? ''),
    ],
]);
