<?php
// api/endpoints/midtrans_token_post.php
$tagihanId = $body['tagihanId'] ?? '';
$siswaId   = $body['siswaId']   ?? '';
$jumlah    = (int)($body['jumlah'] ?? 0);

if (!$tagihanId || !$siswaId || $jumlah <= 0) {
    respond(['status' => 'error', 'message' => 'Data tidak lengkap'], 400);
}

// Ambil data siswa & tagihan
$stmt = $pdo->prepare("
    SELECT s.nama, s.nis, s.no_hp,
           t.bulan, t.tahun, t.nominal
    FROM tagihan_spp t
    JOIN siswa s ON t.siswa_id = s.id
    WHERE t.id = ? AND s.id = ?
");
$stmt->execute([$tagihanId, $siswaId]);
$row = $stmt->fetch();
if (!$row) {
    respond(['status' => 'error', 'message' => 'Tagihan tidak ditemukan'], 404);
}

// ── Midtrans Config ──
$serverKey    = 'Mid-server-ihwyleskqRXA-0Lpz_7x4uVU';
$isProduction = false;
$snapUrl = $isProduction
    ? 'https://app.midtrans.com/snap/v1/transactions'
    : 'https://app.sandbox.midtrans.com/snap/v1/transactions';

$orderId = 'SPP-' . $tagihanId . '-' . time();

$bulanNama = [
    1=>'Januari', 2=>'Februari', 3=>'Maret',     4=>'April',
    5=>'Mei',     6=>'Juni',     7=>'Juli',       8=>'Agustus',
    9=>'September',10=>'Oktober',11=>'November',  12=>'Desember'
][(int)$row['bulan']] ?? '';

$payload = [
    'transaction_details' => [
        'order_id'     => $orderId,
        'gross_amount' => $jumlah,
    ],
    'item_details' => [[
        'id'       => 'SPP-' . $tagihanId,
        'price'    => $jumlah,
        'quantity' => 1,
        'name'     => "SPP $bulanNama {$row['tahun']}",
    ]],
    'customer_details' => [
        'first_name' => $row['nama'],
        'phone'      => $row['no_hp'] ?? '',
    ],
    'enabled_payments' => [
        'bca_va', 'bni_va', 'bri_va', 'mandiri_va', 'permata_va',
        'other_va', 'gopay', 'shopeepay', 'dana', 'qris'
    ],
    // ── Webhook URL — Midtrans kirim notifikasi ke sini setelah bayar ──
    'notification_url' => 'https://abduluran.my.id/spp_admin/api/router.php?endpoint=midtrans_webhook&api_key=spp_secret_key_2024',
    'callbacks' => [
        'finish' => 'myapp://payment/finish',
    ],
];

$ch = curl_init($snapUrl);
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 ' . base64_encode($serverKey . ':'),
    ],
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_TIMEOUT        => 30,
]);

$response  = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response === false) {
    respond(['status' => 'error', 'message' => 'cURL error: ' . $curlError], 500);
}

$result = json_decode($response, true);
if ($result === null) {
    respond(['status' => 'error', 'message' => 'Response tidak valid dari Midtrans'], 500);
}

if ($httpCode === 201 && isset($result['token'])) {
    // Simpan order_id ke tabel tagihan_spp
    $pdo->prepare("UPDATE tagihan_spp SET midtrans_order_id = ? WHERE id = ?")
        ->execute([$orderId, $tagihanId]);

    respond([
        'status'    => 'success',
        'snapToken' => $result['token'],
        'snapUrl'   => $result['redirect_url'],
        'orderId'   => $orderId,
    ]);
} else {
    respond([
        'status'       => 'error',
        'message'      => $result['message'] ?? 'Gagal mendapatkan token Midtrans',
        'midtransCode' => $result['status_code'] ?? $httpCode,
    ], 500);
}