<?php

function ensureTopupSchema(mysqli $con): void
{
    $con->query("
        CREATE TABLE IF NOT EXISTS payment_methods (
            id INT(11) NOT NULL AUTO_INCREMENT,
            method_name VARCHAR(100) NOT NULL,
            method_type VARCHAR(40) NOT NULL DEFAULT 'other',
            wallet_address VARCHAR(255) DEFAULT NULL,
            network_type VARCHAR(80) DEFAULT NULL,
            bank_name VARCHAR(120) DEFAULT NULL,
            account_name VARCHAR(120) DEFAULT NULL,
            account_number VARCHAR(120) DEFAULT NULL,
            instructions TEXT DEFAULT NULL,
            require_receipt TINYINT(1) NOT NULL DEFAULT 0,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
    ");

    $colNet = $con->query("SHOW COLUMNS FROM payment_methods LIKE 'network_type'");
    if ($colNet && $colNet->num_rows === 0) {
        $con->query("ALTER TABLE payment_methods ADD COLUMN network_type VARCHAR(80) DEFAULT NULL AFTER wallet_address");
    }
    if ($colNet) {
        $colNet->free();
    }

    $con->query("
        CREATE TABLE IF NOT EXISTS topup_requests (
            id INT(11) NOT NULL AUTO_INCREMENT,
            customerid INT(11) NOT NULL,
            method_id INT(11) NOT NULL,
            amount DECIMAL(15,2) NOT NULL DEFAULT 0.00,
            reference VARCHAR(40) NOT NULL,
            note TEXT DEFAULT NULL,
            receipt_path VARCHAR(255) DEFAULT NULL,
            status VARCHAR(20) NOT NULL DEFAULT 'pending',
            notified_customer TINYINT(1) NOT NULL DEFAULT 0,
            admin_note TEXT DEFAULT NULL,
            processed_by VARCHAR(100) DEFAULT NULL,
            processed_at DATETIME DEFAULT NULL,
            created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_topup_customer (customerid),
            KEY idx_topup_method (method_id),
            KEY idx_topup_status (status),
            UNIQUE KEY uq_topup_reference (reference)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
    ");

    $colNotified = $con->query("SHOW COLUMNS FROM topup_requests LIKE 'notified_customer'");
    if ($colNotified && $colNotified->num_rows === 0) {
        $con->query("ALTER TABLE topup_requests ADD COLUMN notified_customer TINYINT(1) NOT NULL DEFAULT 0 AFTER status");
    }
    if ($colNotified) {
        $colNotified->free();
    }
}

function generateTopupReference(): string
{
    return 'TUP' . date('YmdHis') . strtoupper(substr(md5((string) mt_rand()), 0, 5));
}

