<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
ini_set('display_errors', '1');
require_once __DIR__ . '/config/database.php';

echo "<h1>Fix Wallet Tables</h1>";

try {
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]);

    $stmt = $pdo->query("DESCRIBE `branch_wallet_transactions`");
    $cols = $stmt->fetchAll();
    $colNames = array_column($cols, 'Field');

    $required = [
        'txn_id'         => "ADD COLUMN `txn_id` VARCHAR(100) NULL DEFAULT NULL",
        'balance_after'  => "ADD COLUMN `balance_after` DECIMAL(10,2) NULL DEFAULT NULL",
        'reference_type' => "ADD COLUMN `reference_type` VARCHAR(50) NULL DEFAULT NULL",
        'reference_id'   => "ADD COLUMN `reference_id` INT NULL DEFAULT NULL",
        'created_by'     => "ADD COLUMN `created_by` INT NULL DEFAULT NULL",
    ];

    $added = 0;
    foreach ($required as $col => $ddl) {
        if (!in_array($col, $colNames)) {
            try {
                $pdo->exec("ALTER TABLE `branch_wallet_transactions` {$ddl}");
                echo "<p style='color:green;'>✓ Added: {$col}</p>";
                $added++;
            } catch (\Throwable $e) {
                echo "<p style='color:red;'>✗ Failed {$col}: " . $e->getMessage() . "</p>";
            }
        }
    }
    echo "<h2 style='color:green;'>Done! Added {$added} columns.</h2>";

} catch (Exception $e) {
    echo "<p style='color:red;'>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
}