<?php
declare(strict_types=1);

return function (\App\Core\Database $db): void {
    $table = 'daily_cash_movements';

    $columns = [
        ['movement_type', "VARCHAR(50) NULL AFTER `movement_date`"],
        ['direction', "ENUM('in','out') NULL AFTER `movement_type`"],
        ['amount', "DECIMAL(15,2) NOT NULL DEFAULT 0.00 AFTER `direction`"],
        ['description', "VARCHAR(500) NULL AFTER `amount`"],
        ['reference_type', "VARCHAR(100) NULL AFTER `description`"],
        ['reference_id', "INT UNSIGNED NULL AFTER `reference_type`"],
    ];

    foreach ($columns as [$col, $def]) {
        $exists = $db->selectOne(
            "SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?",
            [$table, $col]
        );
        if (!$exists) {
            $db->raw("ALTER TABLE `{$table}` ADD COLUMN `{$col}` {$def}");
        }
    }

    $db->raw("ALTER TABLE `{$table}` DROP INDEX IF EXISTS `uk_date_bank`");
    $db->raw("ALTER TABLE `{$table}` DROP INDEX IF EXISTS `uk_date_safe`");

    $idx = $db->selectOne("SELECT 1 FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? AND index_name = 'idx_movement_date'", [$table]);
    if (!$idx) {
        $db->raw("ALTER TABLE `{$table}` ADD INDEX `idx_movement_date` (`movement_date`)");
    }
    $idx = $db->selectOne("SELECT 1 FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? AND index_name = 'idx_movement_type'", [$table]);
    if (!$idx) {
        $db->raw("ALTER TABLE `{$table}` ADD INDEX `idx_movement_type` (`movement_type`)");
    }
    $idx = $db->selectOne("SELECT 1 FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? AND index_name = 'idx_direction'", [$table]);
    if (!$idx) {
        $db->raw("ALTER TABLE `{$table}` ADD INDEX `idx_direction` (`direction`)");
    }
};

