<?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 METHOD =================
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        "success" => false,
        "message" => "Method harus POST"
    ]);
    exit;
}

// ================= CEK USER =================
$get = $conn->prepare("SELECT photo FROM users WHERE id=? AND is_deleted=0");
$get->bind_param("s", $userId);
$get->execute();
$res = $get->get_result();

if ($res->num_rows === 0) {
    echo json_encode([
        "success" => false,
        "message" => "User tidak ditemukan"
    ]);
    exit;
}

$user = $res->fetch_assoc();
$oldPhoto = $user['photo'] ?? null;

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

$stmt = $conn->prepare("
    UPDATE users 
    SET is_deleted=1, is_active=0, updated_at=? 
    WHERE id=?
");

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

$stmt->bind_param("ss", $now, $userId);

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

// ================= OPTIONAL: HAPUS FOTO =================
if ($oldPhoto && $oldPhoto !== "uploads/profil/default.png") {
    $path = __DIR__ . "/" . $oldPhoto;

    if (file_exists($path) && is_file($path)) {
        unlink($path);
    }
}

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