<?php
session_start();
include(__DIR__.'/../../config/db.php');
include(__DIR__.'/../../session.php');

$info_website = "SELECT * FROM configuration";
$stmt = $db->prepare($info_website);
$stmt->execute();
$config = $stmt->fetch(PDO::FETCH_ASSOC);

$trxid = $_GET['trxid'] ?? null;

$pemberitahuan = "SELECT COUNT(*) AS total FROM transaction WHERE type IN ('deposit', 'withdraw') AND user_id = :user_id AND is_read = 0";
$stmt = $db->prepare($pemberitahuan);
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();
$pesan = $stmt->fetchColumn();
    
$checkTransaction = "SELECT trxid, Amount, created_at, updated_at, is_read, status, type 
                     FROM transaction 
                     WHERE type IN ('deposit', 'withdraw') AND user_id = :user_id 
                     ORDER BY created_at DESC LIMIT 5";
$stmt = $db->prepare($checkTransaction);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

$sendMsg = !$trxid ? $result : null;

if ($trxid) {
  $getResult = "SELECT trxid, Amount, created_at, updated_at, is_read, status, type 
                  FROM transaction 
                  WHERE trxid = :trxid AND user_id = :user_id";
  $stmt = $db->prepare($getResult);
  $stmt->bindParam(':trxid', $trxid);
  $stmt->bindParam(':user_id', $user_id);
  $stmt->execute();
  $sendMsg = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Unread Announcements</title>
    <link href="/Content/zelma-v2-beta-desktop-css" rel="stylesheet"/>
    <link href="/Content/Message/zelma-v2-beta-desktop-css" rel="stylesheet"/>
    <link href="/Content/Theme/zelma-v2-beta-desktop-<?= $config['theme']; ?>-css" rel="stylesheet"/>

</head>
<body class="notification-popup-body" id="notification_popup_body">
    <h1 class="notification-popup-title">Notifikasi</h1>

<?php if (!$trxid): ?>
    <div class="notification-tabs">
        <div class="notification-tab-item" data-tab="transaction" data-active="true" data-count="<?= $pesan; ?>">
            Transaksi <span>(<?= $pesan; ?>)</span>
        </div>
        <div class="notification-tab-item" data-tab="promo" data-active="false" data-count="0">
            Promo <span>(0)</span>
        </div>
        <div class="notification-tab-item" data-tab="info" data-active="false" data-count="0">
            Info <span>(0)</span>
        </div>
    </div>
    <div class="notification-content">
        <div class="notification-list" id="notification_list">

                <?php foreach ($sendMsg as $trx):
                  $times = htmlspecialchars(
                    (new DateTime($trx['updated_at'], new DateTimeZone('UTC')))
                      ->setTimezone(new DateTimeZone('Asia/Jakarta'))
                      ->format('d-M-Y H:i T')
                  );
                ?>
              
                <?php
                $type = $trx['type'] === 'deposit' ? 'Deposit' : 'Withdrawal';
                $statusClass = '';
                $statusText = '';
                $statusImage = $trx['type'] === 'deposit' ? 'Deposit.svg' : 'Withdrawal.svg';

                switch ($trx['status']) {
                  case 0:
                    $statusClass = 'NEW';
                    $statusTitle = "Menunggu";
                    $statusText = "Berhasil dikirim";
                    break;
                  case 1:
                    $statusClass = 'SUC';
                    $statusTitle = "Berhasil";
                    $statusText = "Berhasil diproses";
                    break;
                  case 2:
                    $statusClass = 'REJ';
                    $statusTitle = "Ditolak";
                    $statusText = "Ditolak";
                    break;
                  default:
                    $statusClass = 'PRO';
                    $statusTitle = "Diproses";
                    $statusText = "Diproses";
                    break;
                }
                ?>
                
                <a href="javascript:void(0);" onclick="markAsRead('<?= htmlspecialchars($trx['trxid']); ?>')" class="" data-ticket-number="<?= urlencode($trx['trxid']); ?>">
                    <div class="notification-item" data-seen="<?= ($trx['is_read'] == 1 ? 'true' : 'false'); ?>" data-notification-type="transaction" data-rec-id="<?= urlencode($trx['trxid']); ?>" data-message-sub-category="<?= htmlspecialchars($trx['type'] === 'deposit' ? 'Deposit' : 'Withdrawal'); ?>">
                        <div class="notification-header">
                            <span class="notification-date"><?= htmlspecialchars((new DateTime($trx['updated_at']))->setTimezone(new DateTimeZone('Asia/Jakarta'))->format('d-M-Y H:i:s T')); ?></span>
                            <?php if(isset($trx['is_read']) && $trx['is_read'] == 0): ?>
                                <span class="notification-label">Baru</span>
                            <?php endif; ?>
                        </div>
                        <div class="notification-title-container">
                            <div class="notification-image" data-message-category="Transaction" data-message-subcategory="<?= htmlspecialchars($trx['type'] === 'deposit' ? 'Deposit' : 'Withdrawal'); ?>" data-transaction-status="<?= htmlspecialchars($statusClass); ?>">
                                <img loading="lazy" src="//d33egg70nrp50s.cloudfront.net/Images/announcement/<?= htmlspecialchars($trx['type'] === 'deposit' ? 'Deposit' : 'Withdrawal'); ?>.svg?v=20241125" />
                            </div>
                            <div class="notification-title-content">
                                <span><?= htmlspecialchars($trx['type'] === 'deposit' ? 'Deposit' : 'Withdrawal'); ?></span>
                                <h3 class="notification-title"><?= htmlspecialchars($trx['type'] === 'deposit' ? 'Deposit' : 'Withdrawal'); ?> : <?= htmlspecialchars(strtolower($statusText)); ?></h3>
                            </div>
                        </div>
                        <div class="notification-content">
                            <p>Permintaan <?= htmlspecialchars(strtolower($type)); ?> IDR <?= number_format($trx['Amount'], 0, ',', '.'); ?> anda telah <?= htmlspecialchars(strtolower($statusText)); ?>. Nomor Tiket : <?= htmlspecialchars($trx['trxid']); ?></p>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </a>

            <input id="request_verification_token" type="hidden" value="pIfol1BJsWYnS0-pxr8vrna3JgdZMOZkhWbjuLRkJnnlyut3DhuAAnpS4DtrgJJpjgxE9HTin7nl9uqWYhgdBtlltB41" />
        </div>
        <div class="empty-notification-container" id="empty_notification_container">
            <div class="empty-notification-image">
                <picture><source srcset="//d33egg70nrp50s.cloudfront.net/Images/announcement/empty.webp?v=20241125" type="image/webp" /><source srcset="//d33egg70nrp50s.cloudfront.net/Images/announcement/empty.png?v=20241125" type="image/png" /><img loading="lazy" src="//d33egg70nrp50s.cloudfront.net/Images/announcement/empty.png?v=20241125" /></picture>
            </div>
            <div class="empty-notification-content">
                <h3>Belum Ada Notifikasi</h3>
                <p>Saat Anda mendapatkan notifikasi, mereka akan muncul di sini</p>
            </div>
        </div>
    </div>

    <div class="notification-footer">
        <a href="#" id="read_all_announcements_button">Tandai Semua Dibaca</a>
        <a href="/desktop/message/announcement" id="view_more_button">Lihat Selengkapnya</a>
    </div>
<?php endif; ?>

    <script src='/bundles/jquery-1.10.2.min.js' defer></script>
    <script src='/bundles/Message/desktop-js' defer></script>
    
        <script>
function markAsRead(trxid) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "read_status.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("trxid=" + encodeURIComponent(trxid));

    xhr.onload = function() {
        if (xhr.status === 200) {
            location.reload();  // reload untuk memperbarui status notifikasi
        }
    };
}

document.addEventListener('DOMContentLoaded', function() {
    // Mengikat event klik ke setiap elemen <a>
    const links = document.querySelectorAll('.notification-item');
    links.forEach(function(link) {
        link.addEventListener('click', function(event) {
            // Mencegah aksi default link (misal, pengalihan ke URL)
            event.preventDefault();

            // Ambil trxid dari data attribute
            const trxid = this.getAttribute('data-rec-id');
            
            // Panggil fungsi markAsRead
            markAsRead(trxid);
        });
    });
});

    </script>

</body>
</html>