<?php
// Include HTML header
require_once("includes/html-header.php");

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

// PHPMailer for email notifications
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

// Initialize PHPMailer
$mail = new PHPMailer(true);

try {
    // Fetch Telegram bot settings from the database
    $telegramSql = "SELECT * FROM telegram_settings LIMIT 1";
    $telegramQuery = $dbh->prepare($telegramSql);
    $telegramQuery->execute();
    $telegramSettings = $telegramQuery->fetch(PDO::FETCH_OBJ);
    $telegramToken = $telegramSettings->bot_token ?? null;
    $adminChatId = $telegramSettings->admin_chat_id ?? null;

    // Fetch user information
    $email = $_SESSION['alogin'];
    $userSql = "SELECT * FROM users WHERE email = :email LIMIT 1";
    $userQuery = $dbh->prepare($userSql);
    $userQuery->bindParam(':email', $email, PDO::PARAM_STR);
    $userQuery->execute();
    $user = $userQuery->fetch(PDO::FETCH_OBJ);

    if (!$user) {
        throw new Exception("User not found.");
    }

    $_SESSION['user_id'] = $user->id;
    $initialBalance = $user->balance;
    $phoneNumber = $user->mobile;

    // Fetch service price
    $controlSql = "SELECT * FROM text_control LIMIT 1";
    $controlResult = mysqli_query($link, $controlSql);
    $controlSettings = mysqli_fetch_assoc($controlResult);
    $ssprice = $controlSettings['cc_Roket_price'];

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
        // Ensure sufficient balance
        if ($initialBalance < $ssprice) {
            $_SESSION['Error'] = "আপার পর্যাপ্ত পরিমাণ ব্যালেন্স নাই, পলিজ রিচার্জ করুন।";
        } else {
            // Sanitize and retrieve form inputs
            $name = mysqli_real_escape_string($link, $_POST['name']);
            $nid_num = mysqli_real_escape_string($link, $_POST['nid_num']);
            $note = mysqli_real_escape_string($link, $_POST['note']);
            $csrfPost = mysqli_real_escape_string($link, $_POST['csrf']);

            date_default_timezone_set('Asia/Dhaka');
            $date_flt = date("Ymd");

            // CSRF validation
            if ($_SESSION['csrf'] === $csrfPost) {
                // Insert order into the database
                $insertSql = "INSERT INTO roket_sub (sub_type, nfvb, Name, Sub_by, date_flt) 
                              VALUES (:name, :nid_num, :note, :user, :date_flt)";
                $insertQuery = $dbh->prepare($insertSql);
                $insertQuery->bindParam(':name', $name, PDO::PARAM_STR);
                $insertQuery->bindParam(':nid_num', $nid_num, PDO::PARAM_STR);
                $insertQuery->bindParam(':note', $note, PDO::PARAM_STR);
                $insertQuery->bindParam(':user', $email, PDO::PARAM_STR);
                $insertQuery->bindParam(':date_flt', $date_flt, PDO::PARAM_STR);
                $insertQuery->execute();

                // Update user balance
                $newBalance = $initialBalance - $ssprice;
                $balanceUpdateSql = "UPDATE users SET balance = :newBalance WHERE email = :email";
                $balanceUpdateQuery = $dbh->prepare($balanceUpdateSql);
                $balanceUpdateQuery->bindParam(':newBalance', $newBalance, PDO::PARAM_STR);
                $balanceUpdateQuery->bindParam(':email', $email, PDO::PARAM_STR);
                $balanceUpdateQuery->execute();

                // Send order details to Telegram
                $orderTime = date("Y-m-d h:i:s A");
                $adminMessage = <<<TEXT
রকেট ইনফরমশন অর্ডার সল হয়েছে।
নাম: $name
আইডি নম্বর: $nid_num
নোট: $note
ইমেইল: $email
ফোন নম্বর: $phoneNumber
সময়: $orderTime
অর্ডারকারী বর্তমান ব্যালেন্স: $newBalance টাকা।
TEXT;

                if ($telegramToken && $adminChatId) {
                    $telegramUrl = "https://api.telegram.org/bot$telegramToken/sendMessage";
                    $telegramData = [
                        'chat_id' => $adminChatId,
                        'text' => $adminMessage,
                        'parse_mode' => 'HTML'
                    ];

                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $telegramUrl);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($telegramData));
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $telegramResponse = curl_exec($ch);
                    $curlError = curl_error($ch);
                    curl_close($ch);

                    if ($telegramResponse === false) {
                        $_SESSION['Error'] = "Could not send message via Telegram. cURL Error: $curlError";
                    } else {
                        $responseDecoded = json_decode($telegramResponse, true);
                        if (isset($responseDecoded['ok']) && $responseDecoded['ok'] === true) {
                            $_SESSION['Success'] = "অর্ডার সফল হয়েছে। শিগ্রই অ্যাা্রুভ করা হব।";
                        } else {
                            $_SESSION['Error'] = "Telegram API Error: " . ($responseDecoded['description'] ?? "Unknown error");
                        }
                    }
                }
            } else {
                $_SESSION['Error'] = "Invalid CSRF token.";
            }
        }
    }
} catch (Exception $e) {
    $_SESSION['Error'] = $e->getMessage();
}

// Generate new CSRF token
$csrf = md5(rand(1111, 99990));
$_SESSION['csrf'] = $csrf;
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<body>
    <!--  Body Wrapper -->
    <div class="page-wrapper" id="main-wrapper" data-layout="vertical" data-navbarbg="skin6" data-sidebartype="full" data-sidebar-position="fixed" data-header-position="fixed">


        <?php

        //include sidebar
        require_once("includes/sidebar.php");

        ?>

        <!--  Main wrapper -->
        <div class="body-wrapper">


            <?php

            //include header
            require_once("includes/header.php");

            ?>



            <div class="container-fluid">
                <!-- notice -->
                <marquee class="alert alert-dark" onmouseover="this.stop()" onmouseout="this.start()" role="alert" style="font-size: 1rem;">
                    <?php $se = "SELECT * FROM notice";
                    $data = mysqli_query($link, $se);
                    $d = mysqli_fetch_assoc($data);
                    echo $d['notice']; ?>
                </marquee>
                <!-- notice end -->
                <div class="card">
                <div class="mb-3 text-center"></div>
                  
                    <div class="mb-3 text-center">
                        <div class="btn-group" role="group" aria-label="Action Buttons">
                            <a href="Locaion.php?" class="btn btn-outline-primary m-1">Location</a>
                            <a href="NIDToAllNumber.php?" class="btn btn-outline-primary m-1">NID 2 All Sim</a>
                            <a href="IMEIToActive.php" class="btn btn-outline-primary m-1">Imei Track</a>
                    </div>
                        <div class="btn-group" role="group" aria-label="Action Buttons">
                            <a href="NogodInfo.php?" class="btn btn-outline-danger m-1">Nogod Info</a>
                            <a href="Bikash.php?" class="btn btn-outline-danger m-1">Bikash Info</a>
                            <a href="Roket.php?" class="btn btn-danger m-1">Roket Info</a>
                    </div>
                        <div class="btn-group" role="group" aria-label="Action Buttons">
                        <a href="Bmet.php?" class="btn btn-outline-dark m-1">BMET Pending Varify</a>
                        <a href="BirthData.php?" class="btn btn-outline-dark m-1">Birth Certificate Data</a>
                        <a href="UserID.php?" class="btn btn-outline-dark m-1">NID User Id Pass</a>
                </div>
                </div>
                </div>
                <div class="card">
                <div class="mb-3 text-center"></div>
                    <h4 class="fw-semibold text-center">রকেট ইনফরমেশন অর্ডার করুন।</h4>
                    <div class="alert alert-primary" role="alert">
                         রকেট ইনরমেশন <?php echo $ssprice ?> টাকা।
                    </div>
                    <form method="POST">
                        <?php
                        if (isset($_SESSION['Error'])) {
                        ?>
                            <div class="alert alert-danger" role="alert">
                                <?php
                                echo $_SESSION['Error'];
                                $_SESSION['Error'] = null;

                                ?>
                            </div>
                        <?php
                        } elseif (isset($_SESSION['Success'])) {
                        ?>
                            <div class="alert alert-success" role="alert">
                                <?php
                                echo $_SESSION['Success'];
                                $_SESSION['Success'] = null;

                                ?>
                            </div>
                        <?php
                        }
                        ?>
                        <div class="mb-1 text-center"></div>
                        <select name="name" id="" class="form-select" required>
                            <option value="Roket Information ORDER">রকেট ইনফরমশন</option>
                        </select>
                        <div class="card"></div>
                        <div class="mb-1 text-center">
                            <label class="form-label">রকেট নম্বর লিখুনঃ</label>
                            <input type="text" name="nid_num" class="form-control" required>
                        </div>
                        <div class="mb-1 text-center" style="display: none;">
                            <label class="form-label">সাইন কপি সম্পর্কে বিস্তারি লিখুনঃ(যদি কিছু বলার থাকে)</label>
                            <textarea class="form-control" name="note" cols="30" rows="5"></textarea>
                        </div>
                        <input type="hidden" class="form-control" name="csrf" value="<?php echo $csrf ?>">

                        <?php
                        $se = 'SELECT * FROM text_control';
                        $data = mysqli_query($link, $se);
                        $d = mysqli_fetch_assoc($data);
                        $onOff = $d['cc_Roket_control'];

                        if ($onOff == 1) { ?>

                                <div class="card">
                                    <button type="submit" name="submit" class="btn btn-outline-primary m-1"> অর্ডার করুন।</button>


                            <?php } else { ?>

                                <div class="mb-3 text-center" style="margin-top: 17px;">
                                    <h3 style="color: blue"> নতুন অডার বন্ধ আছে। </h3>
                                </div>

                            <?php } ?>
                            </div>
                            </div>
                           <div class="card w-100">
                    <div class="card-body p-4 text-center">
                        <h5 class="card-title fw-semibold mb-4">পর্ববর্তী অর্ডার</h5>
                        <div class="table-responsive">
                        <table class="table text-nowrap mb-0 align-center">
                                                <tr>
                                                <div class="card w-100">
                                                    <th class="border-bottom-0">
                                                        <h6 class="fw-semibold mb-0"আইডি</h6>
                                                    </th>
                                                    <th class="border-bottom-0">
                                                        <h6 class="fw-semibold mb-0">অপারেটর নাম</h6>
                                                    </th>
                                                    <th class="border-bottom-0">
                                                        <h6 class="fw-semibold mb-0">অডার টাইম</h6>
                                                    </th>
                                                    <th class="border-bottom-0">
                                                        <h6 class="fw-semibold mb-0">স্ট্যাটাস</h6>
                                                    </th>
                                                    <th class="border-bottom-0">
                                                        <h6 class="fw-semibold mb-0">✅ডাউনলোড করতে কপি করন<h6>
                                                    </th>
                                                    <th class="border-bottom-0">
                                                        <h6 class="fw-semibold mb-0">ডেলিভারি টাইম</h6>
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody>

                                                <?php $sql = "SELECT * from roket_sub where Sub_by = (:email) ORDER BY id DESC;";

                                                $query = $dbh->prepare($sql);
                                                $query->bindParam(':email', $_SESSION['alogin'], PDO::PARAM_STR);

                                                $query->execute();
                                                $results = $query->fetchAll(PDO::FETCH_OBJ);
                                                if ($query->rowCount() > 0) {
                                                    foreach ($results as $result) {
                                                ?>
                                                        <tr>
                                                            <td class="border-bottom-0">
                                                                <h6 class="fw-semibold mb-0"><?php echo htmlentities($result->id); ?></h6>
                                                            </td>
                                                            <td class="border-bottom-0">
                                                                <h6 class="fw-semibold mb-1"><?php echo htmlentities($result->sub_type); ?></h6>
                                                                <span class="fw-normal"><?php echo htmlentities($result->nfvb); ?></span>
                                                            </td>
                                                            <td class="border-bottom-0">
                                                                <p class="mb-0 fw-normal"><?php echo htmlentities($result->sub_at); ?></p>
                                                            </td>

                                                            <td class="border-bottom-0">
                                                                <h6 class="fw-semibold mb-0 fs-4">

                                                                    <?php
                                                                    if ($result->status == 2) {
                                                                        echo '<p class="text-success">Approved</p>';
                                                                    } else if ($result->status == 1) {
                                                                        echo '<p class="text-warning">Pending</p>';
                                                                    } else if ($result->status == 3) {
                                                                        echo '<p class="text-danger">Canceled</p>';
                                                                    } else if ($result->status == 4) {
                                                                        echo '<p class="text-primary">Received</p>';
                                                                    }
                                                                    ?>

                                                                </h6>
                                                            </td>
                                                            <td class="border-bottom-0">
                                                                <?php
                                                                if ($result->status == 2) {
                                                                    echo '<p class="btn btn-warning" id="bioText' . $result->id . '" style="display:none;">' . htmlentities($result->roket_text) . '</p>';
																	echo '<p class="btn btn-warning">' . htmlentities(substr($result->roket_text, 0, 10)) . '...</p>';
                                                                    echo '<br>';
                                                                    echo '<button class="btn btn-success" onclick="copyTextToClipboard(\'bioText' . $result->id . '\')">Copy text</button>';
                                                                } else if ($result->status == 1) {
                                                                    echo '<p class="text-xs font-medium text-yellow-700">Pending</p>';
                                                                } else if ($result->status == 3) {
                                                                    echo '<p class="text-xs font-medium text-red-700">' . htmlentities($result->delivery_text) . '</p>';
                                                                }
                                                                ?>
                                                            </td>
                                                            <td class="border-bottom-0">
                                                                <p class="mb-0 fw-normal"><?php if ($result->fileup_at == $result->sub_at) {
                                                                                                echo "ডেলিভারি করা হয়নি";
                                                                                            } else {
                                                                                                echo $result->fileup_at;
                                                                                            } ?></p>
                                                            </td>
                                                        </tr>
                                                <?php
                                                    }
                                                } ?>



                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            </div>
                </div>
            </div>


            <script>
                function copyTextToClipboard(elementId) {
                    const textElement = document.getElementById(elementId);
                    if (textElement) {
                        const textToCopy = textElement.textContent || textElement.innerText;
                        navigator.clipboard.writeText(textToCopy).then(() => {
                            alert("Bio text copied to clipboard!");
                        }).catch(err => {
                            console.error("Failed to copy text: ", err);
                        });
                    } else {
                        alert("Text not found.");
                    }
                }
            </script>
            <script src="assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
            <script src="assets/js/sidebarmenu.js"></script>
            <script src="assets/js/app.min.js"></script>
            <script src="assets/libs/simplebar/dist/simplebar.js"></script>



</body>

</html>