<?php
/**
 * migrate.php
 * Jalankan sekali saat instalasi atau upgrade untuk membuat tabel yang diperlukan.
 * BUGFIX v2.9: Tabel member_topups sekarang dibuat di sini, BUKAN di setiap request topup_saldo.
 *
 * Cara pakai: buka di browser sekali → migrate.php
 * atau via CLI: php migrate.php
 */
include 'config.php';
checkLogin();
onlyAdmin();

$migrations = [];

// ── Tabel member_topups ─────────────────────────────────────
$sql_topups = "CREATE TABLE IF NOT EXISTS `member_topups` (
    `id`         INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `member_id`  INT UNSIGNED NOT NULL,
    `amount`     INT UNSIGNED NOT NULL DEFAULT 0,
    `note`       VARCHAR(255) NOT NULL DEFAULT '',
    `created_at` DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `idx_member`  (`member_id`),
    KEY `idx_created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

if ($conn->query($sql_topups)) {
    $migrations[] = ['table' => 'member_topups', 'status' => 'OK'];
} else {
    $migrations[] = ['table' => 'member_topups', 'status' => 'ERROR: ' . $conn->error];
}

// ── Pastikan kolom note ada (untuk instalasi lama) ───────────
$has_note = $conn->query("SHOW COLUMNS FROM member_topups LIKE 'note'")->num_rows > 0;
if (!$has_note) {
    if ($conn->query("ALTER TABLE member_topups ADD COLUMN note VARCHAR(255) NOT NULL DEFAULT '' AFTER amount")) {
        $migrations[] = ['table' => 'member_topups.note', 'status' => 'COLUMN ADDED'];
    } else {
        $migrations[] = ['table' => 'member_topups.note', 'status' => 'ERROR: ' . $conn->error];
    }
} else {
    $migrations[] = ['table' => 'member_topups.note', 'status' => 'ALREADY EXISTS'];
}

// ── Output hasil ─────────────────────────────────────────────
header('Content-Type: text/plain');
echo "=== MIGRASI DATABASE ===\n\n";
foreach ($migrations as $m) {
    echo "[{$m['status']}] {$m['table']}\n";
}
echo "\nSelesai. Halaman ini bisa ditutup.\n";
exit;