<?php
// ============================================================
// FILE: includes/midtrans.php — Helper Midtrans
// ============================================================

/**
 * Buat Snap Token dari Midtrans API.
 * Throw RuntimeException jika gagal.
 */
function midtransCreateTransaction(array $payload): array {
    $auth = base64_encode(MIDTRANS_SERVER_KEY . ':');

    $ch = curl_init(MIDTRANS_API_URL);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Accept: application/json',
            'Authorization: Basic ' . $auth,
        ],
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ]);

    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($err) {
        throw new RuntimeException('cURL Error: ' . $err);
    }

    $data = json_decode($resp, true);

    if ($code !== 201 || empty($data['token'])) {
        $msg = $data['error_messages'][0]
            ?? $data['message']
            ?? 'Unknown Midtrans error';
        throw new RuntimeException('Midtrans API: ' . $msg . ' (HTTP ' . $code . ')');
    }

    return $data; // ['token' => '...', 'redirect_url' => '...']
}

/**
 * Bangun payload untuk Midtrans Snap.
 * Kuantitas harus integer — harga dikali quantity harus = gross_amount.
 */
function midtransBuildPayload(array $pesanan, array $items): array {
    // order_id unik: kode pesanan + timestamp
    $orderId = 'BJ-' . $pesanan['kode_pesanan'] . '-' . time();

    // Bangun item_details
    $itemDetails = [];
    foreach ($items as $it) {
        // Midtrans hanya menerima integer untuk price & quantity
        // Untuk produk per-meter: bulatkan jumlah ke integer, sesuaikan harga
        $qty   = max(1, (int) round((float)$it['jumlah']));
        $price = (int) round((float)$it['harga_satuan']);

        $itemDetails[] = [
            'id'       => 'P' . $it['produk_id'],
            'price'    => $price,
            'quantity' => $qty,
            'name'     => mb_substr($it['nama_produk'], 0, 50),
        ];
    }

    // Hitung total dari item_details
    $itemTotal    = array_sum(array_map(fn($i) => $i['price'] * $i['quantity'], $itemDetails));
    $grossAmount  = (int) round((float)$pesanan['total_harga']);

    // Koreksi selisih pembulatan (wajib: item total HARUS = gross_amount)
    $selisih = $grossAmount - $itemTotal;
    if ($selisih !== 0) {
        $itemDetails[] = [
            'id'       => 'ADJ',
            'price'    => $selisih,
            'quantity' => 1,
            'name'     => 'Penyesuaian Pembulatan',
        ];
    }

    return [
        'transaction_details' => [
            'order_id'     => $orderId,
            'gross_amount' => $grossAmount,
        ],
        'item_details'     => $itemDetails,
        'customer_details' => [
            'first_name' => mb_substr($pesanan['nama_pembeli'], 0, 50),
            'phone'      => $pesanan['no_hp'],
        ],
        // Semua metode diaktifkan
        'enabled_payments' => [
            'bca_va', 'bni_va', 'bri_va', 'permata_va', 'other_va',
            'gopay', 'shopeepay', 'qris',
            'credit_card',
        ],
        'credit_card' => ['secure' => true],
        'expiry' => [
            'start_time' => date('Y-m-d H:i:s O'),
            'unit'       => 'hours',
            'duration'   => 24,
        ],
        'callbacks' => [
            'finish' => BASE_URL . '/payment_finish.php',
        ],
    ];
}

/**
 * Verifikasi signature webhook Midtrans.
 * SHA512(order_id + status_code + gross_amount + server_key)
 */
function midtransVerifySignature(
    string $orderId,
    string $statusCode,
    string $grossAmount,
    string $signatureKey
): bool {
    $expected = hash('sha512', $orderId . $statusCode . $grossAmount . MIDTRANS_SERVER_KEY);
    return hash_equals($expected, $signatureKey);
}

/**
 * Map status Midtrans → status pesanan lokal.
 */
function midtransMapStatus(string $txStatus, string $fraudStatus = ''): array {
    switch ($txStatus) {
        case 'capture':
            $ok = ($fraudStatus === 'accept' || $fraudStatus === '');
            return ['pesanan_status' => $ok ? 'diverifikasi' : 'pending', 'diverifikasi' => $ok];

        case 'settlement':
            return ['pesanan_status' => 'diverifikasi', 'diverifikasi' => true];

        case 'pending':
            return ['pesanan_status' => 'dibayar', 'diverifikasi' => false];

        case 'deny': case 'cancel': case 'expire': case 'failure':
            return ['pesanan_status' => 'dibatalkan', 'diverifikasi' => false];

        default:
            return ['pesanan_status' => 'pending', 'diverifikasi' => false];
    }
}