<?php
declare(strict_types=1);

const BILLING_BUILD_ID = '20260723-sodazw-v15-unified-cash-dashboard';
const BILLING_REQUIRED_SCHEMA_VERSION = '20260722_finance_centre_repair';

function billing_finance_schema_gaps(): array {
    try {
        $pdo = db();
        $tables = [
            'payment_accounts','suppliers','bills','bill_payments',
            'credit_note_applications','payment_reversals','reconciliation_entries',
            'reminder_log','stock_receipts','stock_receipt_items',
            'user_permissions','backup_events',
        ];
        $columns = [
            'settings' => ['credit_prefix','next_credit_number','auto_invoice_web_orders','auto_reminders','reminder_days_before','reminder_days_overdue','reminder_template_name','cron_token','last_backup_at'],
            'payments' => ['account_id','received_amount','received_currency','exchange_rate','fee_amount'],
            'documents' => ['order_source','fulfilment_method','delivery_address','stock_processed_at','source_document_id','sent_at','accepted_at','rejected_at','cancelled_at'],
            'document_items' => ['unit_cost'],
            'products' => ['category','cost_price','reorder_level'],
            'expenses' => ['currency_code'],
            'users' => ['session_version'],
        ];
        $gaps = [];
        $tableCheck = $pdo->prepare('SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?');
        foreach ($tables as $table) {
            $tableCheck->execute([$table]);
            if (!(int)$tableCheck->fetchColumn()) $gaps[] = 'table:'.$table;
        }
        $columnCheck = $pdo->prepare('SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?');
        foreach ($columns as $table => $names) {
            foreach ($names as $column) {
                $columnCheck->execute([$table,$column]);
                if (!(int)$columnCheck->fetchColumn()) $gaps[] = 'column:'.$table.'.'.$column;
            }
        }
        return $gaps;
    } catch (Throwable $e) {
        return ['preflight:'.$e->getMessage()];
    }
}

function billing_schema_is_current(): bool {
    try {
        $stmt = db()->prepare('SELECT 1 FROM schema_migrations WHERE version=? LIMIT 1');
        $stmt->execute([BILLING_REQUIRED_SCHEMA_VERSION]);
        return (bool)$stmt->fetchColumn() && billing_finance_schema_gaps() === [];
    } catch (Throwable $ignored) {
        return false;
    }
}
