<?php
/* ============================================================================
 *  pay_id.php  —  helper for the short, easy-to-type customer "Pay ID".
 *  Include with: require_once '../config/pay_id.php';
 *
 *  The Pay ID is the shortest number that still leaves plenty of room: it starts
 *  at 4 digits (1000–9999) and automatically grows to 5, 6, ... digits only once
 *  the pool starts filling up. Short enough to read aloud to a shop, and
 *  future-proof as the customer base grows.
 * ==========================================================================*/

if (!defined('PAY_ID_MIN_DIGITS')) {
    define('PAY_ID_MIN_DIGITS', 4);   // ← change this if you ever want a different minimum
}

if (!function_exists('pay_id_digit_count')) {
    /* pick how many digits to use: smallest length whose range is still <50% full */
    function pay_id_digit_count(PDO $pdo): int {
        try {
            $count = (int) $pdo->query("SELECT COUNT(*) FROM customers WHERE pay_id IS NOT NULL AND pay_id <> ''")->fetchColumn();
        } catch (Throwable $e) {
            $count = 0;
        }
        $digits = PAY_ID_MIN_DIGITS;
        while (true) {
            $capacity = 9 * (10 ** ($digits - 1));      // count of N-digit numbers (no leading zero)
            if ($count < $capacity * 0.5) break;        // keep usage under 50% → collisions stay rare
            $digits++;
        }
        return $digits;
    }
}

if (!function_exists('generate_unique_pay_id')) {
    function generate_unique_pay_id(PDO $pdo): string {
        $digits = pay_id_digit_count($pdo);
        for ($attempt = 0; $attempt < 80; $attempt++) {
            $lo = 10 ** ($digits - 1);                  // e.g. 1000 for 4 digits
            $hi = (10 ** $digits) - 1;                  // e.g. 9999
            $candidate = (string) random_int($lo, $hi);
            $st = $pdo->prepare("SELECT 1 FROM customers WHERE pay_id = ? LIMIT 1");
            $st->execute([$candidate]);
            if (!$st->fetchColumn()) {
                return $candidate;
            }
            if (($attempt + 1) % 25 === 0) $digits++;   // struggling to find a free one → add a digit
        }
        /* extreme fallback */
        return (string) random_int(10 ** $digits, (10 ** ($digits + 1)) - 1);
    }
}