<?php
if(!defined('BASEPATH')) {
   die('Direct access to the script is not allowed');
}

session_start();

$dailyLimit = 5;

if(!isset($_SESSION['feedback_submissions'])) {
    $_SESSION['feedback_submissions'] = 0;
}

$remainingSubmissions = $dailyLimit - $_SESSION['feedback_submissions'];
$remainingSubmissions = max(0, $remainingSubmissions);

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if ($_SESSION['feedback_submissions'] >= $dailyLimit) {
        $errorMessage = "You have reached the daily limit for feedback submissions.";
    } else {

        $title = htmlspecialchars($_POST["title"]);
        $type = htmlspecialchars($_POST["type"]);
        $messageContent = htmlspecialchars($_POST["message"]);

        $tme = $conn->prepare("SELECT * FROM admins");
        $tme->execute(array());
        $the = $tme->fetch(PDO::FETCH_ASSOC);
        $username = $the["username"];

        $panel = $_SERVER['HTTP_HOST'];

        $telegramBotToken = '7806882980:AAGq_gBBNgJxepZNm8CiSQCbKzR_Xv7R6n4';
        $telegramChatId = '2112039019';

        $message = "<b>Feedback from:</b> <b>$panel</b>\n";
        $message .= "<b>Admin username is:</b> <b>$username</b>\n";
        $message .= "<b>Title:</b> $title\n";
        $message .= "<b>Feedback type:</b> $type\n";
        $message .= "<b>Message:</b> $messageContent";

        $url = "https://api.telegram.org/bot$telegramBotToken/sendMessage";
        $data = [
            'chat_id' => $telegramChatId,
            'text' => $message,
            'parse_mode' => 'HTML'
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);

        if ($response) {
            $errorMessage = "Feedback successfully sent to the owner.";
        } else {
            $errorMessage = "Failed to send feedback. Please try again.";
        }

        $_SESSION['feedback_submissions']++;
        $remainingSubmissions = $dailyLimit - $_SESSION['feedback_submissions'];
        $remainingSubmissions = max(0, $remainingSubmissions);
    }
}

require admin_view('feedback');
?> 