<?php

define('SECRET_KEY', 2704960011);

// Enkripsi ID -> format: MP-<salt><middle>-<checksum>
function encryptNumberID($id) {
    $salt = rand(100, 999); // 3 digit salt
    $raw = ($id + $salt) * SECRET_KEY;
    $middle = substr(str_pad($raw, 12, '0', STR_PAD_LEFT), 0, 7); // bagian dienkripsi
    $checksum = substr(strval(($id * 97 + $salt) % 100000), -5); // 5 digit checksum

    return "MP-$salt$middle-$checksum";
}

// Dekripsi berdasarkan salt yang sudah ditanam
function decryptNumberID($encrypted) {
    if (!preg_match('/^MP-(\d{10})-(\d{5})$/', $encrypted, $matches)) {
        return null;
    }

    $salt = intval(substr($matches[1], 0, 3));  // 3 digit salt di awal
    $middle = substr($matches[1], 3);           // 7 digit encode
    $checksum = $matches[2];

    $maxTries = 100000; // Maksimal 100.000 iterasi, tidak sampai 9 juta

    for ($id = 1; $id <= $maxTries; $id++) {
        $raw = ($id + $salt) * SECRET_KEY;
        $encoded = substr(str_pad($raw, 12, '0', STR_PAD_LEFT), 0, 7);
        if ($encoded !== $middle) {
            continue; // langsung skip jika encode beda
        }

        // Jika middle cocok, baru cek checksum
        $check = substr(strval(($id * 97 + $salt) % 100000), -5);
        if ($check === $checksum) {
            return $id; // ketemu
        }
    }

    return null; // tidak ditemukan
}