<?php
// ============================================================
// FILE: midtrans_notification.php — Webhook dari Midtrans
//
// Midtrans otomatis kirim POST ke URL ini setiap ada update
// status pembayaran (bayar, expire, cancel, dll).
//
// Daftarkan di Midtrans Dashboard:
//   Settings → Configuration → Payment Notification URL
//   → https://DOMAIN_ANDA/budijaya_ecommerce/midtrans_notification.php
//
// Di XAMPP localhost: pakai ngrok untuk expose ke internet
//   1. Download ngrok dari https://ngrok.com
//   2. Jalankan: ngrok http 80
//   3. Copy URL: https://xxxx.ngrok.io
//   4. Daftarkan: https://xxxx.ngrok.io/budijaya_ecommerce/midtrans_notification.php
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/midtrans.php';

// Hanya terima POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

// Baca body JSON
$raw   = file_get_contents('php://input');
$notif = json_decode($raw, true);

if (!$notif || !is_array($notif)) {
    http_response_code(400);
    exit('Bad Request');
}

// Log untuk debug (bisa dihapus di production)
error_log('[Midtrans Notif] ' . $raw);

$orderId     = $notif['order_id']           ?? '';
$statusCode  = $notif['status_code']        ?? '';
$grossAmount = $notif['gross_amount']       ?? '';
$sigKey      = $notif['signature_key']      ?? '';
$txStatus    = $notif['transaction_status'] ?? '';
$fraudStatus = $notif['fraud_status']       ?? '';
$paymentType = $notif['payment_type']       ?? '';

// ── 1. Verifikasi Signature (wajib! cegah pemalsuan) ─────────
if (!$orderId || !midtransVerifySignature($orderId, $statusCode, $grossAmount, $sigKey)) {
    error_log('[Midtrans Notif] INVALID SIGNATURE: ' . $orderId);
    http_response_code(403);
    exit('Forbidden');
}

// ── 2. Cari pesanan di DB ─────────────────────────────────────
$pdo  = db();
$stmt = $pdo->prepare("
    SELECT pay.id AS pay_id, pay.pesanan_id, pay.midtrans_status,
           pes.status AS pesanan_status, pes.kode_pesanan
    FROM pembayaran pay
    JOIN pesanan pes ON pes.id = pay.pesanan_id
    WHERE pay.midtrans_order_id = ?
    LIMIT 1
");
$stmt->execute([$orderId]);
$row = $stmt->fetch();

if (!$row) {
    error_log('[Midtrans Notif] Order not found: ' . $orderId);
    http_response_code(404);
    exit('Not Found');
}

// ── 3. Map status ─────────────────────────────────────────────
$mapped           = midtransMapStatus($txStatus, $fraudStatus);
$newPesananStatus = $mapped['pesanan_status'];
$diverifikasi     = $mapped['diverifikasi'];

// ── 4. Update tabel pembayaran ────────────────────────────────
$pdo->prepare("
    UPDATE pembayaran SET
        midtrans_status = ?,
        payment_type    = ?,
        diverifikasi    = ?,
        verified_at     = ?
    WHERE id = ?
")->execute([
    $txStatus,
    $paymentType,
    $diverifikasi ? 1 : 0,
    $diverifikasi ? date('Y-m-d H:i:s') : null,
    $row['pay_id'],
]);

// ── 5. Update status pesanan (tidak downgrade) ────────────────
$urutan = ['pending', 'dibayar', 'diverifikasi', 'diproses', 'selesai', 'dibatalkan'];
$idxNow = array_search($row['pesanan_status'], $urutan);
$idxNew = array_search($newPesananStatus, $urutan);

$update = is_int($idxNow) && is_int($idxNew)
    && ($idxNew > $idxNow || $newPesananStatus === 'dibatalkan');

if ($update) {
    $pdo->prepare("UPDATE pesanan SET status=?, updated_at=NOW() WHERE id=?")
        ->execute([$newPesananStatus, $row['pesanan_id']]);
    error_log("[Midtrans Notif] {$row['kode_pesanan']}: {$row['pesanan_status']} → $newPesananStatus");
}

// ── 6. Kembalikan stok jika dibatalkan ───────────────────────
if ($newPesananStatus === 'dibatalkan' && $row['pesanan_status'] !== 'dibatalkan') {
    $its = $pdo->prepare("SELECT produk_id, jumlah FROM pesanan_item WHERE pesanan_id=?");
    $its->execute([$row['pesanan_id']]);
    $upd = $pdo->prepare("UPDATE produk SET stok = stok + ? WHERE id = ?");
    foreach ($its->fetchAll() as $it) {
        $upd->execute([$it['jumlah'], $it['produk_id']]);
    }
    error_log("[Midtrans Notif] Stok dikembalikan: {$row['kode_pesanan']}");
}

// Wajib balas 200 OK ke Midtrans
http_response_code(200);
echo json_encode(['status' => 'OK', 'order_id' => $orderId]);