<?php
// api/endpoints/midtrans_webhook_post.php

// ── Log semua request masuk ───────────────────────────────────────
file_put_contents(
    __DIR__ . '/webhook_log.txt',
    date('Y-m-d H:i:s') . "\n" . file_get_contents('php://input') . "\n\n",
    FILE_APPEND
);

// ── Server Key Midtrans ───────────────────────────────────────────
$serverKey = 'Mid-server-ihwyleskqRXA-0Lpz_7x4uVU';

// ── Terima payload ────────────────────────────────────────────────
$rawInput = file_get_contents('php://input');
if (empty($rawInput) && !empty($body)) {
    $data = $body;
} else {
    $data = json_decode($rawInput, true);
}

if (!$data) {
    http_response_code(200);
    echo json_encode(['status' => 'error', 'message' => 'Invalid payload']);
    exit;
}

$orderId           = $data['order_id']           ?? '';
$transactionStatus = $data['transaction_status'] ?? '';
$fraudStatus       = $data['fraud_status']       ?? '';
$grossAmountRaw    = $data['gross_amount']        ?? '0';
$grossAmount       = (int) $grossAmountRaw;
$paymentType       = $data['payment_type']        ?? '';
$signatureKey      = $data['signature_key']       ?? '';
$statusCode        = $data['status_code']         ?? '';

// ── Normalisasi payment_type → nama metode yang konsisten ─────────
// Midtrans mengirim: gopay, qris, dana, ovo, shopeepay, linkaja,
//                   bank_transfer, credit_card, cstore, echannel, permata
function normalisasiMetode(string $paymentType, array $data = []): string {
    $pt = strtolower(trim($paymentType));

    // bank_transfer — cek bank spesifik dari acquirer/bank
    if ($pt === 'bank_transfer') {
        $bank = strtolower($data['va_numbers'][0]['bank'] ?? $data['permata_va_number'] ?? '');
        if (str_contains($bank, 'bca'))    return 'bca';
        if (str_contains($bank, 'bni'))    return 'bni';
        if (str_contains($bank, 'bri'))    return 'bri';
        if (str_contains($bank, 'permata'))return 'permata';
        return 'transfer';
    }

    // echannel = Mandiri VA
    if ($pt === 'echannel') return 'echannel';

    // cstore = Indomaret/Alfamart
    if ($pt === 'cstore') return 'cstore';

    // e-wallet / QRIS
    $map = [
        'gopay'     => 'gopay',
        'qris'      => 'qris',
        'dana'      => 'dana',
        'ovo'       => 'ovo',
        'shopeepay' => 'shopeepay',
        'linkaja'   => 'linkaja',
        'credit_card' => 'credit_card',
        'akulaku'   => 'akulaku',
        'kredivo'   => 'kredivo',
    ];

    return $map[$pt] ?? $pt; // fallback: pakai nilai asli
}

$metodeBayar = normalisasiMetode($paymentType, $data);

// ── Verifikasi signature ──────────────────────────────────────────
$expectedSignature = hash('sha512',
    $orderId . $statusCode . $grossAmountRaw . $serverKey
);

file_put_contents(
    __DIR__ . '/webhook_log.txt',
    date('Y-m-d H:i:s') . " | orderId: $orderId | status: $transactionStatus" .
    " | paymentType: $paymentType | metode: $metodeBayar" .
    " | signatureMatch: " . ($signatureKey === $expectedSignature ? 'YES' : 'NO') . "\n",
    FILE_APPEND
);

if ($signatureKey !== $expectedSignature) {
    http_response_code(200);
    echo json_encode(['status' => 'error', 'message' => 'Invalid signature']);
    exit;
}

// ── Cari tagihan berdasarkan order_id ─────────────────────────────
$stmt = $pdo->prepare("
    SELECT id, siswa_id
    FROM tagihan_spp
    WHERE midtrans_order_id = ?
    LIMIT 1
");
$stmt->execute([$orderId]);
$tagihan = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$tagihan) {
    http_response_code(200);
    echo json_encode(['status' => 'error', 'message' => 'Tagihan not found']);
    exit;
}

$tagihanId = (int) $tagihan['id'];
$siswaId   = (int) $tagihan['siswa_id'];

// ── Tentukan status ───────────────────────────────────────────────
$statusBayar = null;

if ($transactionStatus === 'capture' && $fraudStatus === 'accept') {
    $statusBayar = 'lunas';
} elseif ($transactionStatus === 'settlement') {
    $statusBayar = 'lunas';
} elseif (in_array($transactionStatus, ['cancel', 'deny', 'expire'], true)) {
    $pdo->prepare("
        UPDATE tagihan_spp
        SET status            = 'belum_bayar',
            midtrans_order_id = NULL,
            updated_at        = NOW()
        WHERE id = ?
    ")->execute([$tagihanId]);

    http_response_code(200);
    echo json_encode(['status' => 'ok', 'info' => $transactionStatus]);
    exit;
} elseif ($transactionStatus === 'pending') {
    http_response_code(200);
    echo json_encode(['status' => 'ok', 'info' => 'pending']);
    exit;
}

// ── Proses LUNAS ──────────────────────────────────────────────────
if ($statusBayar === 'lunas') {

    $adminRow = $pdo->query("SELECT id FROM admin LIMIT 1")
                    ->fetch(PDO::FETCH_ASSOC);
    $adminId  = (int)($adminRow['id'] ?? 1);

    // Cek duplikat
    $cek = $pdo->prepare("
        SELECT COUNT(*) FROM pembayaran
        WHERE tagihan_id = ?
        AND   keterangan LIKE ?
    ");
    $cek->execute([$tagihanId, '%' . $orderId . '%']);
    $sudahAda = (int) $cek->fetchColumn();

    if ($sudahAda === 0) {
        $ins = $pdo->prepare("
            INSERT INTO pembayaran
                (tagihan_id, siswa_id, admin_id, jumlah_bayar,
                 metode_bayar, keterangan, tanggal_bayar)
            VALUES (?, ?, ?, ?, ?, ?, NOW())
        ");
        $ins->execute([
            $tagihanId,
            $siswaId,
            $adminId,
            $grossAmount,
            $metodeBayar,                                        // ← pakai nilai yang sudah dinormalisasi
            'Midtrans - ' . $metodeBayar . ' - ' . $orderId,    // ← keterangan konsisten
        ]);
    } else {
        // Transaksi sudah ada tapi metode_bayar kosong — update metode saja
        $pdo->prepare("
            UPDATE pembayaran
            SET metode_bayar = ?
            WHERE tagihan_id = ?
            AND (metode_bayar IS NULL OR metode_bayar = '')
        ")->execute([$metodeBayar, $tagihanId]);
    }

    $pdo->prepare("
        UPDATE tagihan_spp
        SET status     = 'lunas',
            updated_at = NOW()
        WHERE id = ?
    ")->execute([$tagihanId]);

    file_put_contents(
        __DIR__ . '/webhook_log.txt',
        date('Y-m-d H:i:s') . " | SUCCESS: tagihan $tagihanId LUNAS via $metodeBayar\n",
        FILE_APPEND
    );
}

http_response_code(200);
echo json_encode(['status' => 'ok', 'status_bayar' => $statusBayar, 'metode' => $metodeBayar]);