<?php
//ini_set('session.gc_maxlifetime', 86400);
//session_set_cookie_params(86400);
session_start();
include_once('../config/#Config.php');
if(!$_SESSION['UserName']){
    die('<script>window.location.href=\''.$config['site']['url'].'index.php\';</script>');
}
$get_AD = mysqli_query($conn, "Select * From config_admin WHERE Account = '".$_SESSION['UserName']."'");
if(!mysqli_num_rows($get_AD)){
    die('Không đủ quyền.');
}
mysqli_query($conn, "UPDATE config_admin Set TimerOnline = '".date('d/m/Y H:i:s')."' WHERE Account = '".$_SESSION['UserName']."'");

/*==================================================
=   KHAI BÁO SSH CỐ ĐỊNH + HÀM LOAD/SAVE CONFIG   =
==================================================*/

// THAY THÔNG TIN NÀY CHO ĐÚNG VPS CỦA BẠN
$SSH_HOST = '103.228.37.25';                 // IP VPS
$SSH_PORT = 22;                           // Port SSH
$SSH_USER = 'root';                       // Username SSH
$SSH_PASS = '@Duyanh130900';                    // Password SSH
$REMOTE_CONFIG_PATH = '/home/39P/Config.ini'; // File Config cần sửa trên VPS

$error       = '';
$success     = '';
$fileContent = '';

if (!function_exists('ssh2_connect')) {
    $error = "Hosting chưa bật extension SSH2! Vào cPanel → Select PHP Version → tick ssh2.";
}

/**
 * Đọc nội dung file config từ VPS
 */
function loadConfigFile()
{
    global $SSH_HOST, $SSH_PORT, $SSH_USER, $SSH_PASS, $REMOTE_CONFIG_PATH;

    $conn = @ssh2_connect($SSH_HOST, $SSH_PORT);
    if (!$conn) return [false, "Không kết nối được SSH tới $SSH_HOST:$SSH_PORT"];

    if (!@ssh2_auth_password($conn, $SSH_USER, $SSH_PASS)) {
        return [false, "Sai user/mật khẩu SSH"];
    }

    $sftp = @ssh2_sftp($conn);
    if (!$sftp) return [false, "Không khởi tạo được SFTP"];

    $remotePath = "ssh2.sftp://" . intval($sftp) . $REMOTE_CONFIG_PATH;
    $stream = @fopen($remotePath, 'r');
    if (!$stream) return [false, "Không mở được file config trên VPS: $REMOTE_CONFIG_PATH"];

    $content = stream_get_contents($stream);
    fclose($stream);

    if ($content === false) return [false, "Không đọc được file config"];

    return [true, $content];
}

/**
 * Ghi nội dung mới vào file config trên VPS
 */
function saveConfigFile($newContent)
{
    global $SSH_HOST, $SSH_PORT, $SSH_USER, $SSH_PASS, $REMOTE_CONFIG_PATH;

    $conn = @ssh2_connect($SSH_HOST, $SSH_PORT);
    if (!$conn) return "Không kết nối được SSH";

    if (!@ssh2_auth_password($conn, $SSH_USER, $SSH_PASS)) {
        return "Lỗi đăng nhập SSH (password sai?)";
    }

    $sftp = @ssh2_sftp($conn);
    if (!$sftp) return "Không khởi tạo được SFTP";

    $remotePath = "ssh2.sftp://" . intval($sftp) . $REMOTE_CONFIG_PATH;
    $stream = @fopen($remotePath, 'w');
    if (!$stream) return "Không mở được file để ghi: $REMOTE_CONFIG_PATH";

    $bytes = fwrite($stream, $newContent);
    fclose($stream);

    if ($bytes === false) return "Không ghi được file config";

    return true;
}

/*=============================
=   XỬ LÝ LƯU CONFIG (POST)   =
=============================*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && function_exists('ssh2_connect')) {
    $newContent = $_POST['file_content'] ?? '';

    $result = saveConfigFile($newContent);

    if ($result === true) {
        $success = "Lưu file Config.ini thành công!";
    } else {
        $error = $result;
    }
}

/*====================================
=   LOAD CONFIG ĐỂ ĐỔ VÀO TEXTAREA   =
====================================*/
if (function_exists('ssh2_connect')) {
    list($okCfg, $dataCfg) = loadConfigFile();
    if ($okCfg) {
        $fileContent = $dataCfg;
    } else {
        $error = $dataCfg;
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Content-Language" content="en">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Config Editor - <?=$config['site']['Domain']?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, shrink-to-fit=no" />
    <meta name="description" content="Config.ini Editor">
    <meta name="msapplication-tap-highlight" content="no">
    <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
    <link href="main.css" rel="stylesheet">
</head>
<body>
<div class="app-container app-theme-white body-tabs-shadow fixed-sidebar fixed-header">
    <div class="app-header header-shadow">
        <div class="app-header__logo">
            <div class="logo-src"></div>
            <div class="header__pane ml-auto">
                <div>
                    <button type="button" class="hamburger close-sidebar-btn hamburger--elastic" data-class="closed-sidebar">
                        <span class="hamburger-box">
                            <span class="hamburger-inner"></span>
                        </span>
                    </button>
                </div>
            </div>
        </div>
        <div class="app-header__mobile-menu">
            <div>
                <button type="button" class="hamburger hamburger--elastic mobile-toggle-nav">
                    <span class="hamburger-box">
                        <span class="hamburger-inner"></span>
                    </span>
                </button>
            </div>
        </div>
        <div class="app-header__menu">
                <span>
                    <button type="button" class="btn-icon btn-icon-only btn btn-primary btn-sm mobile-toggle-header-nav">
                        <span class="btn-icon-wrapper">
                            <i class="fa fa-ellipsis-v fa-w-6"></i>
                        </span>
                    </button>
                </span>
        </div>
        <div class="app-header__content">
            <div class="app-header-left">
                <div class="search-wrapper">
                    <div class="input-holder">
                        <input type="text" class="search-input" placeholder="Type to search">
                        <button class="search-icon"><span></span></button>
                    </div>
                    <button class="close"></button>
                </div>
                <ul class="header-menu nav">
                    <li class="nav-item">
                        <a href="javascript:void(0);" class="nav-link">
                            <i class="nav-link-icon fa fa-database"> </i>
                            Statistics
                        </a>
                    </li>
                    <li class="btn-group nav-item">
                        <a href="javascript:void(0);" class="nav-link">
                            <i class="nav-link-icon fa fa-edit"></i>
                            Projects
                        </a>
                    </li>
                    <li class="dropdown nav-item">
                        <a href="javascript:void(0);" class="nav-link">
                            <i class="nav-link-icon fa fa-cog"></i>
                            Settings
                        </a>
                    </li>
                </ul>
            </div>
            <div class="app-header-right">
                <div class="header-btn-lg pr-0">
                    <div class="widget-content p-0">
                        <div class="widget-content-wrapper">
                            <div class="widget-content-right header-user-info ml-3">
                                <button type="button" class="btn-shadow p-1 btn btn-primary btn-sm show-toastr-example">
                                    <i class="fa text-white fa-calendar pr-1 pl-1"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>        
            </div>
        </div>
    </div>
    <div class="ui-theme-settings">
        <button type="button" id="TooltipDemo" class="btn-open-options btn btn-warning">
            <i class="fa fa-cog fa-w-16 fa-spin fa-2x"></i>
        </button>
        <?php include_once('temp_setting.php');?>
    </div>
    <div class="app-main">
        <div class="app-sidebar sidebar-shadow">
            <div class="app-header__logo">
                <div class="logo-src"></div>
                <div class="header__pane ml-auto">
                    <div>
                        <button type="button" class="hamburger close-sidebar-btn hamburger--elastic" data-class="closed-sidebar">
                            <span class="hamburger-box">
                                <span class="hamburger-inner"></span>
                            </span>
                        </button>
                    </div>
                </div>
            </div>
            <div class="app-header__mobile-menu">
                <div>
                    <button type="button" class="hamburger hamburger--elastic mobile-toggle-nav">
                        <span class="hamburger-box">
                            <span class="hamburger-inner"></span>
                        </span>
                    </button>
                </div>
            </div>
            <div class="app-header__menu">
                <span>
                    <button type="button" class="btn-icon btn-icon-only btn btn-primary btn-sm mobile-toggle-header-nav">
                        <span class="btn-icon-wrapper">
                            <i class="fa fa-ellipsis-v fa-w-6"></i>
                        </span>
                    </button>
                </span>
            </div>
            <div class="scrollbar-sidebar">
                <div class="app-sidebar__inner">
                    <?php include_once('temp_menu.php'); ?>
                </div>
            </div>
        </div>
        <div class="app-main__outer">
            <div class="app-main__inner">
                <div class="app-page-title">
                    <div class="page-title-wrapper">
                        <div class="page-title-heading">
                            <div class="page-title-icon">
                                <i class="pe-7s-config icon-gradient bg-premium-dark"></i>
                            </div>
                            <div>
                                Config.ini Editor
                                <div class="page-title-subheading">
                                    Sửa file cấu hình trực tiếp.
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- NỘI DUNG CHÍNH -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="main-card mb-3 card">
                            <div class="card-body">
                                <h5 class="card-title">Chỉnh sửa file Config.ini</h5>

                                <?php if ($error): ?>
                                    <div class="alert alert-danger" role="alert">
                                        <?php echo htmlspecialchars($error, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); ?>
                                    </div>
                                <?php endif; ?>

                                <?php if ($success): ?>
                                    <div class="alert alert-success" role="alert">
                                        <?php echo htmlspecialchars($success, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); ?>
                                    </div>
                                <?php endif; ?>

                                <form method="POST">
                                    <div class="form-group">
                                        <!--<label>Nội dung file (<?php echo htmlspecialchars($REMOTE_CONFIG_PATH); ?>)</label>-->
                                        <label>Nội dung file config</label>
                                        <textarea
                                            name="file_content"
                                            class="form-control"
                                            rows="25"
                                            spellcheck="false"
                                            autocomplete="off"
                                            autocorrect="off"
                                            autocapitalize="off"
                                        ><?php echo htmlspecialchars($fileContent, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); ?></textarea>
                                    </div>
                                    <button type="submit" class="btn btn-primary">
                                        💾 Lưu File Config Lên VPS
                                    </button>
                                </form>

                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="app-wrapper-footer">
                <div class="app-footer">
                    <div class="app-footer__inner">
                        <div class="app-footer-left">
                            <ul class="nav">
                                <li class="nav-item">
                                    <a href="javascript:void(0);" class="nav-link">
                                        Võ lâm Truyền Kỳ
                                    </a>
                                </li>
                                <li class="nav-item">
                                    <a href="javascript:void(0);" class="nav-link">
                                        Võ lâm Truyền Kỳ
                                    </a>
                                </li>
                            </ul>
                        </div>
                        <div class="app-footer-right">
                            <ul class="nav">
                                <li class="nav-item">
                                    <a href="javascript:void(0);" class="nav-link">
                                        Võ lâm Truyền Kỳ
                                    </a>
                                </li>
                                <li class="nav-item">
                                    <a href="javascript:void(0);" class="nav-link">
                                        <div class="badge badge-success mr-1 ml-0">
                                            <small>NEW</small>
                                        </div>
                                        Võ lâm Truyền Kỳ
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>    

        </div>
    </div>
</div>

<!-- JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>   
<script type="text/javascript" src="assets/scripts/main.js"></script>
<link href="assets/scripts/toastr.css" rel="stylesheet" />
<script src="assets/scripts/toastr.js"></script>
<script src="assets/scripts/script.js"></script> 
<script type="text/javascript" src="assets/scripts/jquery.watermark.js"></script>
</body>
</html>
