<?php
/**
 * Webhook iPaymu - Dipanggil saat status pembayaran berubah
 * URL ini harus didaftarkan di dashboard iPaymu sebagai Notify URL
 */
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/iPaymu.php';
require_once __DIR__ . '/../classes/Payment.php';

// Log raw request untuk debugging
$logFile = __DIR__ . '/../logs/ipaymu_callback.log';
@mkdir(dirname($logFile), 0755, true);
file_put_contents($logFile, date('Y-m-d H:i:s') . " | " . file_get_contents('php://input') . "\n", FILE_APPEND);

// Baca headers
$headers = [];
foreach ($_SERVER as $k => $v) {
    if (substr($k, 0, 5) === 'HTTP_') {
        $headers[strtolower(str_replace('_', '-', substr($k, 5)))] = $v;
    }
}

// Baca body
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody, true);

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

// Verifikasi signature
$ipaymu = new iPaymu();
if (!$ipaymu->verifyCallback($headers, $data)) {
    http_response_code(403);
    file_put_contents($logFile, date('Y-m-d H:i:s') . " | SIGNATURE INVALID\n", FILE_APPEND);
    echo json_encode(['status' => 'error', 'message' => 'Invalid signature']);
    exit;
}

// Proses pembayaran
$success = Payment::processCallback($data);

http_response_code(200);
echo json_encode(['status' => $success ? 'success' : 'processed']);