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

include "db.php"; 
include "commen.php";
$message = '';
$message_class = '';

// Initialize variables
$bot_name = '';
$token = '';
$edit_id = '';

// Check if edit_id is provided for editing
if (isset($_REQUEST['edit_id']) && $_REQUEST['edit_id'] != '') {
    $edit_id = $_REQUEST['edit_id'];

    // Fetch the current user data for editing
    $edit_query = "SELECT * FROM telegram_bot_tokens  WHERE id = ?";
    $stmt = $conn->prepare($edit_query);
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $edit_data = $result->fetch_assoc();
        $bot_name = $edit_data['bot_name'];
        $token = $edit_data['token'];
    } else {
        $message = "Token not found!";
        $message_class = "alert-danger";
    }
}

// Check if form is submitted
if (isset($_POST['submit_user']) && $_POST['submit_user'] != '') {
    // Sanitize user input
    $bot_name = trim($_POST['bot_name']);
    $token = trim($_POST['token']);


    // Validate input
    if (!empty($bot_name) && !empty($token)) {
        if ($edit_id) {
            // Update user data
            $update_query = "UPDATE telegram_bot_tokens SET bot_name = ?, token = ? WHERE id = ?";
            $stmt = $conn->prepare($update_query);
            $stmt->bind_param("sssi", $username, $message_prompt, $category_name, $edit_id);

            if ($stmt->execute()) {
                $message = "Updated successfully!";
                $message_class = "alert-success";
                
            } else {
                $message = "Error updating user: " . $stmt->error;
                $message_class = "alert-danger";
            }
        } else {
            // Check if the user already exists
            $check_query = "SELECT * FROM telegram_bot_tokens  WHERE token = ?";
            $stmt = $conn->prepare($check_query);
            $stmt->bind_param("s", $token);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $message = "Token already exists!";
                $message_class = "alert-warning";
            } else {
                // Prepare curl request for setting webhook
                $curl = curl_init();
                
                curl_setopt_array($curl, array(
                  CURLOPT_URL => 'https://api.telegram.org/bot'.$token.'/setWebhook',
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => '',
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 0,
                  CURLOPT_FOLLOWLOCATION => true,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_CUSTOMREQUEST => 'POST',
                  CURLOPT_POSTFIELDS => array('url' => 'https://tele1.ali1.work/setwebhook.php'),
                ));
                
                // Execute the curl request
                $response = curl_exec($curl);
                curl_close($curl);

                // Check if the webhook was set successfully
                if ($response && strpos($response, '"ok":true') !== false) {
                    // If webhook is set, insert the new user data
                    $sql = "INSERT INTO telegram_bot_tokens (bot_name, token) VALUES (?, ?)";
                    $stmt = $conn->prepare($sql);

                    if ($stmt) {
                        $stmt->bind_param("ss", $bot_name, $token);
                        if ($stmt->execute()) {
                            $message = "Added successfully!";
                            $message_class = "alert-success";
                        } else {
                            $message = "Error: " . $stmt->error;
                            $message_class = "alert-danger";
                        }
                    } else {
                        $message = "Error preparing the statement.";
                        $message_class = "alert-danger";
                    }
                } else {
                    $message = "Error setting webhook. Please try again.";
                    $message_class = "alert-danger";
                }
            }
        }
    } else {
        $message = "Please fill in all fields.";
        $message_class = "alert-warning";
    }
}
?>

<div class="content" id="dynamic-content">
    <h2><?php echo $edit_id ? 'Edit' : 'Add New'; ?></h2>
    <p class='alert <?php echo $message_class; ?>'><?php echo $message; ?></p>
    <form method="POST" action="">
        <div class="mb-3">
            <label for="bot_name" class="form-label">Add Bot Name</label>
            <input type="text" name="bot_name" class="form-control" id="bot_name" value="<?php echo htmlspecialchars($bot_name); ?>" required />
        </div>
        <div class="mb-3">
            <label for="token" class="form-label">Add Token</label>
            <input type="text" name="token" class="form-control" id="token" value="<?php echo htmlspecialchars($token); ?>" required />
        </div>
        <button type="submit" name="submit_user" value="submit" class="btn btn-primary"><?php echo $edit_id ? 'Update' : 'Submit'; ?></button>
    </form>
</div>