<?php
require_once '../config/db.php';
header('Content-Type: application/json');

try {
    // Ubah kolom dari ENUM terbatas → VARCHAR(50) agar bisa terima semua metode
    $pdo->exec("ALTER TABLE pembayaran MODIFY COLUMN metode_bayar VARCHAR(50) NOT NULL DEFAULT 'tunai'");

    // Sekarang update data lama
    $rows = $pdo->query(
        "SELECT id, keterangan FROM pembayaran
         WHERE (metode_bayar = '' OR metode_bayar = 'tunai')
         AND keterangan LIKE 'Midtrans - %'"
    )->fetchAll(PDO::FETCH_ASSOC);

    $updated = [];
    foreach ($rows as $r) {
        preg_match('/\b(dana|gopay|ovo|shopeepay|qris|credit_card|bank_transfer|bca|bni|bri|permata|linkaja|cstore|echannel)\b/i',
            $r['keterangan'], $m);
        if (!empty($m[1])) {
            $metode = strtolower($m[1]);
            $id = (int)$r['id'];
            $pdo->exec("UPDATE pembayaran SET metode_bayar = '$metode' WHERE id = $id");
            $updated[] = ['id' => $id, 'metode' => $metode];
        }
    }

    // Verifikasi
    $cek = $pdo->query(
        "SELECT metode_bayar, COUNT(*) as n FROM pembayaran GROUP BY metode_bayar ORDER BY n DESC"
    )->fetchAll(PDO::FETCH_ASSOC);

    $kolom = $pdo->query("SHOW COLUMNS FROM pembayaran LIKE 'metode_bayar'")->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        'status'          => 'success',
        'kolom_baru'      => $kolom['Type'],
        'rows_updated'    => count($updated),
        'detail'          => $updated,
        'metode_sekarang' => $cek
    ], JSON_PRETTY_PRINT);

} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}