<?php
/**
 * Test Manual: Simulasi Callback Pembayaran
 * HAPUS FILE INI SETELAH TESTING SELESAI!
 */
require_once __DIR__ . '/../includes/db.php';

header('Content-Type: text/html; charset=utf-8');

$db = db();

echo "<h1>🧪 Test Simulasi Pembayaran</h1>";
echo "<style>body{font-family:Arial;padding:20px;} .success{color:green;} .error{color:red;} .info{color:blue;} pre{background:#f4f4f4;padding:10px;border-radius:5px;}</style>";

// ============================================================================
// 1. CEK KONDISI AWAL
// ============================================================================
echo "<h2>1. Kondisi Awal</h2>";

// Cek bill unpaid yang bisa dipakai test
$stmt = $db->query("
    SELECT b.*, c.name as customer_name, c.branch_id, c.pppoe_username
    FROM bills b
    LEFT JOIN customers c ON b.customer_id = c.id
    WHERE b.status = 'unpaid' AND c.branch_id IS NOT NULL
    ORDER BY b.id DESC
    LIMIT 1
");
$testBill = $stmt->fetch();

if (!$testBill) {
    echo "<p class='error'>❌ Tidak ada bill unpaid dengan branch_id. Buat pelanggan & tagihan dulu.</p>";
    exit;
}

echo "<div class='info'>";
echo "<strong>Bill Test:</strong><br>";
echo "Bill Number: <code>{$testBill['bill_number']}</code><br>";
echo "Customer: {$testBill['customer_name']}<br>";
echo "Amount: Rp " . number_format($testBill['amount']) . "<br>";
echo "Branch ID: {$testBill['branch_id']}<br>";
echo "PPPoE: {$testBill['pppoe_username']}<br>";
echo "</div>";

// Cek saldo cabang sebelum
$stmt = $db->prepare("SELECT * FROM branch_balances WHERE branch_id = ?");
$stmt->execute([$testBill['branch_id']]);
$balanceBefore = $stmt->fetch();

echo "<div class='info'>";
echo "<strong>Saldo Cabang Sebelum:</strong><br>";
echo "Pending: Rp " . number_format($balanceBefore['pending_balance'] ?? 0) . "<br>";
echo "Available: Rp " . number_format($balanceBefore['available_balance'] ?? 0) . "<br>";
echo "Total Income: Rp " . number_format($balanceBefore['total_income'] ?? 0) . "<br>";
echo "</div>";

// ============================================================================
// 2. SIMULASI CALLBACK
// ============================================================================
echo "<h2>2. Simulasi Callback</h2>";

$trxId = 'TEST-' . time();
$amount = (float)$testBill['amount'];
$branchId = (int)$testBill['branch_id'];
$pendingUntil = date('Y-m-d H:i:s', strtotime('+5 days'));

try {
    $db->beginTransaction();
    
    // Update bill status
    $stmt = $db->prepare("
        UPDATE bills 
        SET status = 'paid', 
            paid_at = NOW(),
            transaction_id = ?,
            payment_method = 'TEST',
            payment_channel = 'SIMULATION',
            updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$trxId, $testBill['id']]);
    echo "<p class='success'>✅ Bill status updated to 'paid'</p>";
    
    // Update customer status
    $stmt = $db->prepare("UPDATE customers SET status = 'active', updated_at = NOW() WHERE id = ?");
    $stmt->execute([$testBill['customer_id']]);
    echo "<p class='success'>✅ Customer status updated to 'active'</p>";
    
    // Insert ke branch_transactions
    $stmt = $db->prepare("
        INSERT INTO branch_transactions 
        (branch_id, bill_id, customer_id, transaction_id, bill_number, 
         customer_name, amount, payment_method, payment_channel, 
         status, pending_until, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, 'TEST', 'SIMULATION', 'pending', ?, NOW())
    ");
    $stmt->execute([
        $branchId,
        $testBill['id'],
        $testBill['customer_id'],
        $trxId,
        $testBill['bill_number'],
        $testBill['customer_name'],
        $amount,
        $pendingUntil
    ]);
    echo "<p class='success'>✅ Transaksi tercatat di branch_transactions</p>";
    
    // Update branch_balances
    $stmt = $db->prepare("
        INSERT INTO branch_balances 
        (branch_id, pending_balance, available_balance, total_withdrawn, total_income)
        VALUES (?, ?, 0, 0, ?)
        ON DUPLICATE KEY UPDATE 
            pending_balance = pending_balance + VALUES(pending_balance),
            total_income = total_income + VALUES(total_income),
            last_updated_at = NOW()
    ");
    $stmt->execute([$branchId, $amount, $amount]);
    echo "<p class='success'>✅ Saldo cabang diupdate</p>";
    
    $db->commit();
    echo "<p class='success'><strong>✅ SIMULASI BERHASIL!</strong></p>";
    
} catch (\Throwable $e) {
    $db->rollBack();
    echo "<p class='error'>❌ ERROR: " . $e->getMessage() . "</p>";
    exit;
}

// ============================================================================
// 3. CEK KONDISI AKHIR
// ============================================================================
echo "<h2>3. Kondisi Setelah Simulasi</h2>";

$stmt = $db->prepare("SELECT * FROM branch_balances WHERE branch_id = ?");
$stmt->execute([$branchId]);
$balanceAfter = $stmt->fetch();

echo "<div class='info'>";
echo "<strong>Saldo Cabang Setelah:</strong><br>";
echo "Pending: Rp " . number_format($balanceAfter['pending_balance']) . "<br>";
echo "Available: Rp " . number_format($balanceAfter['available_balance']) . "<br>";
echo "Total Income: Rp " . number_format($balanceAfter['total_income']) . "<br>";
echo "</div>";

// Cek transaksi
$stmt = $db->prepare("
    SELECT * FROM branch_transactions 
    WHERE branch_id = ?
    ORDER BY created_at DESC
    LIMIT 5
");
$stmt->execute([$branchId]);
$transactions = $stmt->fetchAll();

echo "<h3>5 Transaksi Terakhir:</h3>";
echo "<table border='1' cellpadding='5'>";
echo "<tr><th>Tanggal</th><th>Customer</th><th>Bill</th><th>Amount</th><th>Status</th><th>Release</th></tr>";
foreach ($transactions as $t) {
    echo "<tr>";
    echo "<td>{$t['created_at']}</td>";
    echo "<td>{$t['customer_name']}</td>";
    echo "<td>{$t['bill_number']}</td>";
    echo "<td>Rp " . number_format($t['amount']) . "</td>";
    echo "<td>{$t['status']}</td>";
    echo "<td>{$t['pending_until']}</td>";
    echo "</tr>";
}
echo "</table>";

echo "<hr>";
echo "<p class='error'><strong>⚠️ PENTING: Hapus file ini setelah testing!</strong></p>";
echo "<p>Jika saldo sudah bertambah, berarti sistem berjalan normal. Pembayaran asli dari iPaymu akan otomatis tercatat.</p>";