<?php
// Include your database connection
include('includes/dbconnection.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Required files
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
require_once 'vendor/autoload.php';

use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$school_name = $_ENV['SCHOOL_NAME'];
$school_address = $_ENV['SCHOOL_ADDRESS'];
$prefix = $_ENV['registration_prefix'];
$url = $_ENV['BASE_URL'];

// Check if reply is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $feedback_id = $_POST['feedback_id'];
    $reply = mysqli_real_escape_string($con, $_POST['reply']);

    // Get the user's email from the feedback table
    $query = "SELECT email, name FROM feedback WHERE id = '$feedback_id'";
    $result = mysqli_query($con, $query);
    $feedback = mysqli_fetch_assoc($result);

    $user_email = $feedback['email'];
    $user_name = $feedback['name'];

    // Insert the admin's reply into the conversation table
    $query_conversation = "INSERT INTO conversation (message_id, sender, message_content) 
                           VALUES ('$feedback_id', 'admin', '$reply')";

    if (mysqli_query($con, $query_conversation)) {
        // Update the feedback status to 'replied'
        $query_update = "UPDATE feedback SET reply='$reply', status='replied' WHERE id='$feedback_id'";

        if (mysqli_query($con, $query_update)) {
            // Send an email to the user
            $mail = new PHPMailer(true);

            try {
                // SMTP configuration from .env
                $mail->isSMTP();
                $mail->Host = $_ENV['SMTP_HOST'];
                $mail->SMTPAuth = true;
                $mail->Username = $_ENV['SMTP_NO_REPLY'];
                $mail->Password = $_ENV['SMTP_NO_REPLY_PASSWORD'];
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                $mail->Port = $_ENV['SMTP_PORT'];
                $mail->Timeout = 10;

                $mail->setFrom($_ENV['SMTP_NO_REPLY'], $_ENV['SCHOOL_NAME']);
                $mail->addAddress($user_email, $user_name);  // Add the user email

                // Content
                $mail->isHTML(true);
                $mail->Subject = 'Admin Reply to Your Feedback';
                $mail->Body    = "<h3>Dear $user_name,</h3>
                                  <p>Your feedback has been reviewed, and the admin has replied:</p>
                                  <blockquote>$reply</blockquote>
                              <p>Click <a href='$url/portal/user_reply.php?feedback_id=$feedback_id'>here</a> to reply back to the admin.</p>
                                  <p>Thank you for your feedback!</p>";

                    $mail->send();
                    echo "
                    <script>
                        alert('Message was sent successfully');
                        window.location.href = 'feedback1.php';
                    </script>
                    ";
                    exit();

                } catch (Exception $e) {
                    echo "
                    <script>
                        alert('Message could not be sent. Mailer Error: " . addslashes($mail->ErrorInfo) . "');
                        window.location.href = 'feedback1.php';
                    </script>
                    ";
                    exit();
                }
            }
        }
    }
