<?php 

require('db_connection.php');

if (isset($_POST['kirim'])) {
    $profile = htmlspecialchars($_POST['profile'], ENT_QUOTES, 'UTF-8');
    $merchantRef = htmlspecialchars($_POST['vc'], ENT_QUOTES, 'UTF-8');
    $method = htmlspecialchars($_POST['rek'], ENT_QUOTES, 'UTF-8');
    $amount = htmlspecialchars($_POST['saldo'], ENT_QUOTES, 'UTF-8');
    $mac = htmlspecialchars($_POST['mac'], ENT_QUOTES, 'UTF-8');
    $email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
    $nama = htmlspecialchars($_POST['nama'], ENT_QUOTES, 'UTF-8');
    $phone = htmlspecialchars($_POST['phone'], ENT_QUOTES, 'UTF-8');

    $query = "SELECT * FROM transaction WHERE mac=? AND status='UNPAID'";
    $stmt = $db->prepare($query);
    if ($stmt === false) {
        die("Database query preparation failed: " . $db->error);
    }
    $stmt->bind_param('s', $mac);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result === false) {
        die("Database query execution failed: " . $stmt->error);
    }

    $row = $result->fetch_assoc();
    $ceklink = isset($row['checkout_url']) ? $row['checkout_url'] : null;
    $cekdata = $result->num_rows;

    if ($cekdata == 0) {
        $data = [
            'method'         => $method,
            'merchant_ref'   => $merchantRef,
            'amount'         => $amount,
            'customer_name'  => $nama,
            'customer_email' => $email,
            'customer_phone' => $phone,
            'order_items'    => [
                [
                    'sku'      => $merchantRef,
                    'name'     => "$profile-$merchantRef",
                    'price'    => $amount,
                    'quantity' => 1,
                ],
            ],
            'return_url'     => 'https://wifikonut.bang-al.my.id/voucher_detail.php?merchant_ref=' . $merchantRef, //link ke detail voucher
            // 'return_url'     => 'http://' . $dns . '/login?dst=&username=' . $merchantRef . '&password=' . $merchantRef, //dns hotspot
            'expired_time'   => (time() + (24 * 60 * 60)), // 24 jam
            'signature'      => hash_hmac('sha256', $merchantCode . $merchantRef . $amount, $privateKey)
        ];

        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_FRESH_CONNECT  => true,
            CURLOPT_URL            => $Endpoint,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER         => false,
            CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $apiKey],
            CURLOPT_FAILONERROR    => false,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => http_build_query($data),
            CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0
        ]);

        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        curl_close($curl);

        if ($error || $httpCode !== 200) {
            echo "Terjadi kesalahan saat melakukan koneksi: $error (HTTP Code: $httpCode)";
            file_put_contents('error_log.txt', "cURL Error: $error\nHTTP Code: $httpCode\nResponse: $response\n", FILE_APPEND);
            exit;
        }

        $invoiceData = json_decode($response, true);

        if ($invoiceData['success']) {
            $type = 'hotspot';
            $payment_url = $invoiceData['data']['checkout_url'];
            $reference = $invoiceData['data']['reference'];
            $status = $invoiceData['data']['status'];
            $customer_name = $invoiceData['data']['customer_name'];
            $customer_email = $invoiceData['data']['customer_email'];
            $customer_phone = $invoiceData['data']['customer_phone'];

            $stmt = $db->prepare("INSERT INTO transaction(reference, merchant_ref, profile, payment_method, amount, checkout_url, status, mac, customer_name, customer_email, customer_phone, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            if ($stmt === false) {
                die("Database insert preparation failed: " . $db->error);
            }
            $stmt->bind_param('ssssssssssss', $reference, $merchantRef, $profile, $method, $amount, $payment_url, $status, $mac, $customer_name, $customer_email, $customer_phone, $type);
            $stmt->execute();
            if ($stmt->error) {
                die("Database insert execution failed: " . $stmt->error);
            }

            header('Location: ' . $payment_url);
            exit;
        } else {
            $error_message = $invoiceData['message'];
            echo "Pembayaran gagal. Pesan error: $error_message";
        }
    } else {
        header('Location: ' . $ceklink);
        exit;
    }
}
?>
