<?php 
include 'dbconnt.php'; 

function Querydb($query) {
    GLOBAL $conn;
    return mysqli_query($conn, $query);
}

function generateSerialOrderId() {
    // 1. Get the last ID based on the primary key (id)
    $sql = "SELECT id FROM orders ORDER BY id DESC LIMIT 1";
    $result = Querydb($sql);
    
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        // Extract numbers from the string (e.g., "ORD-0005" becomes 5)
        $last_number = preg_replace('/[^0-9]/', '', $row['id']);
        $next_number = intval($last_number) + 1;
    } else {
        // First order in the system
        $next_number = 1;
    }

    // 2. Format with a prefix and leading zeros (4 digits)
    return "ORD-".date('y|'). str_pad($next_number, 10, "0", STR_PAD_LEFT);
}

function generateSerialTransId() {
    // 1. Get the last transaction ID
    $sql = "SELECT trans_id FROM transactions ORDER BY transaction_id DESC LIMIT 1";
    $result = Querydb($sql);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        // Extract numbers from the string (e.g., "TRN-0005" becomes 5)
        $last_number = preg_replace('/[^0-9]/', '', $row['trans_id']);
        $next_number = intval($last_number) + 1;
    } else {
        // First transaction in the system
        $next_number = 1;
    }

    // 2. Format with "TRN-" and pad with 4 zeros
    return "TRN-" . str_pad($next_number, 10, "0", STR_PAD_LEFT);
}

function get_avatar($name, $bg = '0d6efd', $color = 'fff') {
    // 1. URL encode the name to handle spaces and special characters
    $encoded_name = urlencode($name);
    
    // 2. Return the formatted URL
    return "https://ui-avatars.com/api/?name={$encoded_name}&background={$bg}&color={$color}&size=128";
}

?> 