<?php

class MembershipNumberGenerator
{
    public static function generate(
        $conn,
        $prefix = "M",
        $prefix_divider = ".",
        $midfix_format = "ymd",
        $midfix_divider = ".",
        $suffix_pad = 4
    ) {
        try {

            // Midfix tanggal
            $midfix = date($midfix_format);

            $currentYear  = date('Y');
            $currentMonth = date('m');

            // 🔥 Ambil MAX(counter) bulan ini
            $sql = "SELECT MAX(counter) as max_counter
                    FROM membership
                    WHERE YEAR(CreateAt) = ?
                    AND MONTH(CreateAt) = ?";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("Prepare statement gagal: " . $conn->error);
            }

            $stmt->bind_param("ii", $currentYear, $currentMonth);
            $stmt->execute();

            $result = $stmt->get_result();
            $row = $result->fetch_assoc();

            $maxCounter = $row['max_counter'] ?? 0;

            $stmt->close();

            // 🔥 Kalau belum ada data bulan ini → mulai dari 1
            $newCounter = ($maxCounter > 0) ? $maxCounter + 1 : 1;

            // Padding suffix
            $suffix = $suffix_pad > 0
                ? str_pad($newCounter, $suffix_pad, '0', STR_PAD_LEFT)
                : (string)$newCounter;

            // Build membership number
            $membershipNumber = $prefix
                . $prefix_divider
                . $midfix
                . $midfix_divider
                . $suffix;

            return [
                'membership_number' => $membershipNumber,
                'counter' => $newCounter
            ];

        } catch (Exception $e) {
            throw new Exception("Gagal generate membership number: " . $e->getMessage());
        }
    }
}
?>