<?php
set_time_limit(240);
require '../../connect.php';
require _DIR_('cron/formatter');

function logError($message) {
    $logFile = 'error_log.txt';
    $dateTime = date("Y-m-d H:i:s");
    file_put_contents($logFile, "[$dateTime] $message" . PHP_EOL, FILE_APPEND);
}

$get = file_get_contents('php://input');
// Simpan data mentah untuk keperluan debug
file_put_contents('raw_input_log.txt', $get . PHP_EOL, FILE_APPEND);

// Normalisasi key header ke huruf kecil
$header = array_change_key_case(getallheaders(), CASE_LOWER);
$FromIP = client_ip();

// Log seluruh header yang diterima untuk keperluan debugging
logError("Headers received: " . print_r($header, true));

function DFStatus($x) {
    if ($x == 'Transaksi Pending') return 'processing';
    if ($x == 'Transaksi Gagal') return 'error';
    if ($x == 'Transaksi Sukses') return 'success';
    return 'processing';
}

try {
    // Validasi header wajib dan user-agent dengan key huruf kecil
    if (isset($header['x-digiflazz-event']) 
        && isset($header['x-digiflazz-delivery']) 
        && isset($header['x-hub-signature']) 
        && in_array($header['user-agent'], ['Digiflazz-Hookshot', 'DigiFlazz-Pasca-Hookshot'])) {

        // Decode JSON
        $decoded = json_decode($get, true);
        $array = $decoded['data'] ?? [];
        if (!$array) {
            logError("JSON tidak valid: " . $get);
            die("Invalid JSON data");
        }

        $status = DFStatus($array['message']);
        $trxid = $array['trx_id'];
        $refid = $array['ref_id'];
        $note = $array['sn'] ?? 'Transaksi Gagal';
        $last = $array['buyer_last_saldo'];

        // Output format sederhana untuk debug
        $format = "$refid -> {$array['message']}<br>$note";
        print $format;

        // Proses transaksi berdasarkan ref_id dan provider DIGI
        $search = $call->query("SELECT * FROM trx WHERE tid = '$refid' AND provider = 'DIGI'");
        if (!$search) {
            logError("Query error: " . $call->error);
        } elseif ($search->num_rows > 0) {
            $row = $search->fetch_assoc();
            $cust = $row['user'];
            $WebID = $row['wid'];
            $service = $row['name'];
            $price = $row['price'];
            $profit = $row['profit'];
            $user = $call->query("SELECT * FROM users WHERE username = '$cust'")->fetch_assoc();
            
            if (!$user) {
                logError("User $cust tidak ditemukan");
                die("User not found");
            }

            $reff = $user['uplink'];
            $point = point($price, $profit, $row['provider']);

            // Update status transaksi
            if (!$call->query("UPDATE trx SET status = '$status', note = '$note', date_up = NOW() WHERE tid = '$refid' AND provider = 'DIGI'")) {
                logError("Gagal update transaksi: " . $call->error);
            }

            // Kirim notifikasi jika status transaksi success atau error
            if (in_array($status, ['success', 'error'])) {
                $fcmData = $call->query("SELECT token FROM users_token WHERE user = '$cust'")->fetch_assoc();
                $fcm_token = $fcmData['token'] ?? '';

                $notification = [
                    'title' => "Pesanan $service",
                    'body' => "Status " . ucwords($status) . " | Keterangan $note",
                    'click_action' => 'Open_URI',
                ];

                $data = ['picture' => '', 'uri' => base_url("order/detail/$WebID")];
                $FCM->sendNotif($fcm_token, $notification, $data);
            }

            // Jika transaksi sukses dan belum pernah diproses point referral
            if ($status == 'success' && $row['spoint'] == '0') {
                $point = conf('referral', 3);
                $komisi = conf('referral', 1);
                $notes = "ID Trx #{$WebID}";

                if (!$call->query("UPDATE users SET point = point+$point WHERE username = '$cust'")) {
                    logError("Gagal update poin user: " . $call->error);
                }

                if (!$call->query("INSERT INTO mutation VALUES ('', '$cust', '+', '$point', '$notes', NOW(), 'Point Transaksi')")) {
                    logError("Gagal insert mutasi: " . $call->error);
                }

                $reffQuery = $call->query("SELECT * FROM users WHERE username = '$reff' AND level IN ('Premium', 'Admin')");
                if ($reffQuery && $reffQuery->num_rows == 1) {
                    if (!$call->query("UPDATE users SET komisi = komisi+$komisi WHERE username = '$reff'")) {
                        logError("Gagal update komisi refferal: " . $call->error);
                    }
                }
            }
        }
    } else {
        logError("Access Denied! IP: $FromIP");
        die('Access Denied!');
    }
} catch (Exception $e) {
    logError("Exception: " . $e->getMessage());
    die("Internal Server Error");
}
