<?php
// 1. Matikan laporan error ke layar agar tidak merusak JSON
error_reporting(0);
ini_set('display_errors', 0);

// 2. Mulai buffer untuk menangkap teks "sampah" (spasi/warning)
ob_start();

header('Content-Type: application/json');

function log_error($msg) {
    file_put_contents(__DIR__ . "/error_log.txt", date('[Y-m-d H:i:s] ') . $msg . PHP_EOL, FILE_APPEND);
}

try {
    require_once 'db_connect.php';
    $db = isset($conn) ? $conn : $con;

    if (!$db) throw new Exception("Koneksi database gagal.");

    // 3. Ambil data POST
    // Pastikan nama field di Android sama (email, token, new_password)
    $email    = isset($_POST['email']) ? trim($_POST['email']) : '';
    $token    = isset($_POST['token']) ? trim($_POST['token']) : '';
    $new_pass = isset($_POST['new_password']) ? $_POST['new_password'] : ''; 

    if (empty($email) || empty($token) || empty($new_pass)) {
        throw new Exception("Data tidak lengkap. Email: $email, Token: $token");
    }

    // 4. Validasi token
    $stmt = $db->prepare("SELECT email FROM password_resets WHERE email = ? AND UPPER(token) = UPPER(?) AND expires_at > NOW() LIMIT 1");
    $stmt->bind_param("ss", $email, $token);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res && $res->fetch_assoc()) {
        $new_hash = password_hash($new_pass, PASSWORD_BCRYPT);

        $update = $db->prepare("UPDATE aku SET password_hash = ? WHERE email = ?");
        $update->bind_param("ss", $new_hash, $email);

        if ($update->execute()) {
            $db->query("DELETE FROM password_resets WHERE email = '$email'");
            
            // BERHASIL: Buang semua output "sampah" sebelum echo JSON
            $response = ["success" => true, "message" => "Password berhasil diubah!"];
            ob_clean(); 
            echo json_encode($response);
        } else {
            throw new Exception("Gagal memperbarui password di database.");
        }
    } else {
        throw new Exception("Kode verifikasi salah atau sudah kadaluwarsa.");
    }
} catch (Exception $e) {
    // GAGAL: Buang semua output "sampah" sebelum echo JSON error
    $response = ["success" => false, "message" => $e->getMessage()];
    log_error("ERROR: " . $e->getMessage());
    ob_clean();
    echo json_encode($response);
}

// Akhiri buffer
ob_end_flush();
?>