<?php
require_once "../config.php";

if (isset($_GET['cek_status']) && isset($_GET['order_id'])) {
    header('Content-Type: application/json');

    $order_id = $_GET['order_id'];
    $serverKey = "Mid-server-AGyISGYL0OVVyNhML0c-vQ55"; // karya bintang baru
    // $serverKey = "SB-Mid-server-qiKmLL4BXLEINNs38Ye4HxtW";

    $ch = curl_init("https://api.sandbox.midtrans.com/v2/$order_id/status");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Basic ' . base64_encode($serverKey . ':')
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);

    if (!isset($data['transaction_status'])) {
        echo json_encode([
            'status' => 'error',
            'message' => $data['status_message'] ?? 'Midtrans tidak mengembalikan status'
        ]);
        exit;
    }

    $trx = $data['transaction_status'];

    if ($trx === 'settlement' || $trx === 'capture') {
        $stmt = $conn->prepare("UPDATE tbpiutang SET cid = 'B', cstatuspembayaran = 'settlement' WHERE cnoorder = ? AND cid = 'A'");
        $stmt->bind_param("s", $order_id);
        $stmt->execute();
        $stmt->close();
    
        $stmt2 = $conn->prepare("SELECT cnomer FROM tbpiutang WHERE cnoorder = ?");
        $stmt2->bind_param("s", $order_id);
        $stmt2->execute();
        $result = $stmt2->get_result();
        $row = $result->fetch_assoc();
        $cnomer = $row['cnomer'];
        $stmt2->close();
    
        if ($cnomer) {
            $stmt3 = $conn->prepare("UPDATE tbSO SET chal = 1 WHERE cNoSO = ?");
            $stmt3->bind_param("s", $cnomer);
            $stmt3->execute();
            $stmt3->close();
        }
    
        echo json_encode([
            'status' => 'settlement',
            'message' => 'Pembayaran berhasil'
        ]);
        exit;
    }


    if ($trx === 'expire' || $trx === 'expired') {
        $stmt = $conn->prepare("UPDATE tbpiutang SET cid = 'C', cstatuspembayaran = 'expired' WHERE cnoorder = ? AND cid = 'A'");
        $stmt->bind_param("s", $order_id);
        $stmt->execute();
        $stmt->close();
    
        $stmt2 = $conn->prepare("SELECT cnomer FROM tbpiutang WHERE cnoorder = ?");
        $stmt2->bind_param("s", $order_id);
        $stmt2->execute();
        $result = $stmt2->get_result();
        $row = $result->fetch_assoc();
        $cnomer = $row['cnomer'];
        $stmt2->close();
    
        if ($cnomer) {
            $stmt3 = $conn->prepare("DELETE FROM tbSO WHERE cNoSO = ?");
            $stmt3->bind_param("s", $cnomer);
            $stmt3->execute();
            $stmt3->close();
    
            $stmt4 = $conn->prepare("DELETE FROM tbSODtl WHERE cNoSO = ?");
            $stmt4->bind_param("s", $cnomer);
            $stmt4->execute();
            $stmt4->close();
    
            $stmt5 = $conn->prepare("DELETE FROM tbstockaplikasi WHERE cnomer = ?");
            $stmt5->bind_param("s", $cnomer);
            $stmt5->execute();
            $stmt5->close();
    
            $checkSO = $conn->prepare("SELECT COUNT(*) AS countSO FROM tbSO WHERE cNoSO = ?");
            $checkSO->bind_param("s", $cnomer);
            $checkSO->execute();
            $checkSOResult = $checkSO->get_result();
            $checkSORow = $checkSOResult->fetch_assoc();
            $countSO = $checkSORow['countSO'];
            $checkSO->close();
    
            $checkSODtl = $conn->prepare("SELECT COUNT(*) AS countSODtl FROM tbSODtl WHERE cNoSO = ?");
            $checkSODtl->bind_param("s", $cnomer);
            $checkSODtl->execute();
            $checkSODtlResult = $checkSODtl->get_result();
            $checkSODtlRow = $checkSODtlResult->fetch_assoc();
            $countSODtl = $checkSODtlRow['countSODtl'];
            $checkSODtl->close();
    
            $checkStock = $conn->prepare("SELECT COUNT(*) AS countStock FROM tbstockaplikasi WHERE cnomer = ?");
            $checkStock->bind_param("s", $cnomer);
            $checkStock->execute();
            $checkStockResult = $checkStock->get_result();
            $checkStockRow = $checkStockResult->fetch_assoc();
            $countStock = $checkStockRow['countStock'];
            $checkStock->close();
    
            if ($countSO == 0 && $countSODtl == 0 && $countStock == 0) {
                $stmt6 = $conn->prepare("DELETE FROM tbpiutang WHERE cnomer = ?");
                $stmt6->bind_param("s", $cnomer);
                $stmt6->execute();
                $stmt6->close();
            } else {
                echo json_encode([
                    'status' => 'failed',
                    'message' => 'Gagal menghapus data di tbSO, tbSODtl, atau tbstockaplikasi, tidak dapat menghapus tbpiutang'
                ]);
                exit;
            }
        }
    
        echo json_encode([
            'status' => 'expired',
            'message' => 'Pembayaran sudah expired, data terkait telah dihapus'
        ]);
        exit;
    }





    echo json_encode([
        'status' => 'pending',
        'message' => 'Menunggu pembayaran'
    ]);
    exit;
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cek Pembayaran</title>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ccc; padding: 8px; text-align: center; }
        th { background: #f2f2f2; }
        button { padding: 6px 10px; cursor: pointer; }
        .settlement { color: green; font-weight: bold; }
        .pending { color: orange; font-weight: bold; }
        .expired { color: red; font-weight: bold; }
        .timerbox { margin: 10px 0; font-weight: bold; }
    </style>
</head>
<body>

<h2>Daftar Pembayaran</h2>

<div class="timerbox">
    Reload tabel dalam <span id="timer">10</span> detik
</div>

<table>
    <thead>
        <tr>
            <th>No SO</th>
            <th>No Order</th>
            <th>Kode Cust</th>
            <th>Nama Cust</th>
            <th>Tgl Order</th>
            <th>Expired</th>
            <th>Nominal</th>
            <th>Jenis Biaya</th>
            <th>Status</th>
            <th>Link</th>
            <th>Aksi</th>
        </tr>
    </thead>
    <tbody id="dataTable"></tbody>
</table>

<script>
const rowsData = <?php echo json_encode($data_rows); ?>;

function rupiah(angka) {
    const n = Number(angka) || 0;
    return "Rp " + n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function autoCekPending() {
    const pendingRows = document.querySelectorAll('td[data-status="pending"]');
    let delay = 0;

    pendingRows.forEach(td => {
        const orderId = td.id.replace('status-', '');
        setTimeout(() => {
            cekStatus(orderId, true);
        }, delay);
        delay += 800;
    });
}

function loadTable() {
    const tbody = document.getElementById('dataTable');
    tbody.innerHTML = '';

    const timestamp = new Date().getTime(); 

    fetch(`datatabelpiutang.php?timestamp=${timestamp}`)
        .then(response => response.json())
        .then(data => {
            console.log(data);

            if (data.length === 0) {
                tbody.innerHTML = `<tr><td colspan="11">Tidak ada data</td></tr>`;
                return;
            }

            data.forEach(r => {
                tbody.innerHTML += ` 
                <tr>
                    <td>${r.cnomer ?? ''}</td>
                    <td>${r.cnoorder ?? ''}</td>
                    <td>${r.ckdcust ?? ''}</td>
                    <td>${r.cnmcust ?? ''}</td>
                    <td>${r.dtglorder ?? ''}</td>
                    <td>${r.etglexpired ?? ''}</td>
                    <td>${rupiah(r.nnominal)}</td>
                    <td>${r.cjnsbiaya ?? ''}</td>
                    <td id="status-${r.cnoorder}" class="${r.cstatuspembayaran ?? ''}" data-status="${r.cstatuspembayaran ?? ''}">${(r.cstatuspembayaran ?? '').toUpperCase()}</td>
                    <td><a href="${r.clinkpembayaran ?? '#'}" target="_blank">Bayar</a></td>
                    <td><button onclick="cekStatus('${r.cnoorder}')">Cek Status</button></td>
                </tr>
                `;
            });

            autoCekPending(); 
        })
        .catch(error => {
            console.error('Error fetching data:', error);
            tbody.innerHTML = `<tr><td colspan="11">Gagal memuat data</td></tr>`;
        });
}

function rupiah(angka) {
    const n = Number(angka) || 0;
    return "Rp " + n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}


function cekStatus(orderId, silent = false) {
    if (!silent) {
        Swal.fire({
            title: 'Cek Status',
            text: 'Menghubungi Midtrans...',
            allowOutsideClick: false,
            didOpen: () => Swal.showLoading()
        });
    }

    fetch('?cek_status=1&order_id=' + encodeURIComponent(orderId))
        .then(res => res.json())
        .then(data => {
            if (!silent) Swal.close();

            if (data.status === 'error') {
                if (!silent) Swal.fire('Error', data.message, 'error');
                return;
            }

            const el = document.getElementById('status-' + orderId);
            if (el) {
                el.innerText = data.status.toUpperCase();
                el.className = data.status;
                el.setAttribute('data-status', data.status);
            }

            if (!silent) {
                Swal.fire(
                    'Status Pembayaran',
                    data.message,
                    data.status === 'settlement' ? 'success' :
                    data.status === 'pending' ? 'warning' : 'error'
                );
            }
        })
        .catch(() => {
            if (!silent) Swal.fire('Error', 'Gagal menghubungi server', 'error');
        });
}

let countdown = 10;
let timerInterval = null;

function startCountdown() {
    const timerEl = document.getElementById('timer');
    countdown = 10;
    timerEl.textContent = countdown;

    if (timerInterval) clearInterval(timerInterval);

    timerInterval = setInterval(() => {
        countdown--;
        timerEl.textContent = countdown;

        if (countdown <= 0) {
            loadTable();
            countdown = 10;
            timerEl.textContent = countdown;
        }
    }, 1000);
}

document.addEventListener('DOMContentLoaded', function () {
    loadTable();
    startCountdown();
});
</script>

</body>
</html>
