<?php
declare(strict_types=1);

namespace App\Modules\Members\Services;

use App\Core\App;

final class FormNumberGenerator
{
    /**
     * Get the next form number.
     * Returns null if not configured (super admin must set starting number).
     */
    public static function next(): ?int
    {
        $db = App::getInstance()->db();

        // Check existing form numbers in members table
        $last = $db->selectOne(
            "SELECT MAX(CAST(form_number AS UNSIGNED)) as last_num 
             FROM members 
             WHERE form_number IS NOT NULL 
             AND form_number REGEXP '^[0-9]+$'"
        );
        $lastNum = (int) ($last['last_num'] ?? 0);

        if ($lastNum > 0) {
            return $lastNum + 1;
        }

        // No existing forms — check system config for starting number
        $config = $db->selectOne(
            "SELECT config_value FROM system_config WHERE config_key = ?",
            ['membership.form_start_number']
        );

        if ($config && is_numeric($config['config_value']) && (int) $config['config_value'] > 0) {
            return (int) $config['config_value'];
        }

        // Not configured
        return null;
    }

    /**
     * Set the starting form number (called once by super admin).
     */
    public static function setStartNumber(int $number): void
    {
        $db = App::getInstance()->db();
        $existing = $db->selectOne(
            "SELECT id FROM system_config WHERE config_key = ?",
            ['membership.form_start_number']
        );

        if ($existing) {
            $db->update(
                'system_config',
                [
                    'config_value' => (string) $number,
                    'updated_at'   => date('Y-m-d H:i:s'),
                ],
                '`id` = ?',
                [(int) $existing['id']]
            );
        } else {
            $db->insert('system_config', [
                'config_key'     => 'membership.form_start_number',
                'config_value'   => (string) $number,
                'config_type'    => 'integer',
                'group_name'     => 'membership',
                'description_ar' => 'رقم بداية الاستمارات',
                'description_en' => 'Starting Form Number',
                'is_editable'    => 1,
                'created_at'     => date('Y-m-d H:i:s'),
                'updated_at'     => date('Y-m-d H:i:s'),
            ]);
        }
    }

    /**
     * Check if the form number system is configured.
     */
    public static function isConfigured(): bool
    {
        return self::next() !== null;
    }

    /**
     * Get the form fee amount from service catalog or default.
     */
    public static function getFormFee(): string
    {
        try {
            $db = App::getInstance()->db();
            $fee = $db->selectOne(
                "SELECT base_amount FROM service_catalog WHERE service_code = 'FORM_NEW_MEMBERSHIP' AND is_active = 1 LIMIT 1"
            );
            if ($fee && $fee['base_amount']) {
                return $fee['base_amount'];
            }
        } catch (\Throwable $e) {
        }

        return '505.00';
    }
}