<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['Student']);
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }

    $userDetails_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$_SESSION[uid]' ");
    if($userDetails_row = mysqli_fetch_assoc($userDetails_sql)){
        $userName = $userDetails_row["uname"];
        $userState_id = $userDetails_row["state"];
        $userDist_id = $userDetails_row["dist"];
        $admin_ref = $userDetails_row["admin_ref"];
    }
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
</head>

<body>
    <!--  Header -->
    <?php 
    include "include/header.php"; 
    ?>
    <!-- #header -->

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <div class="card rounded p-3 m-1">
                    <h5>What is it all about?</h5>
                    <form action="" method="POST">
                        <div class="control-group mb-3">
                            <textarea class="form-control" rows="5" placeholder="Please enter your query"
                                required="required" name="con_message"></textarea>
                        </div>
                        <div class="form-group mb-3" style="position:relative;">
                            <input type="text" class="form-control" id="capcha" name="capcha"
                                placeholder="Enter Captcha" required="required" />
                            <?php $random_code = rand(1000, 9999); ?>
                            <p style="position: absolute;right: 0;top: 7px;">
                                <span
                                    style="background: #084e30;padding: 8px 40px;color: #fff;border-radius: 0px 8px 8px 0px;"><?php echo $random_code;?></span>
                            </p>
                            <input type="hidden" value="<?php echo $random_code;?>" name="or_code">
                        </div>
                        <div class="text-center">
                            <input type="hidden" name="q_client" value="<?php echo $_SESSION["uid"];?>">
                            <button class="btn btn-primary" type="submit" name="form_submit">Send
                                Message</button>
                        </div>
                    </form>
                </div>
                <?php
                $query_sql = mysqli_query($con, "SELECT * FROM query_table WHERE q_client = '{$_SESSION["uid"]}' ORDER BY q_id DESC");
                if (mysqli_num_rows($query_sql) > 0) {
                ?>
                <div class="card mt-3 p-2">
                    <h5>Recent Queries:</h5>
                    <div class="accordion" id="queryAccordion">
                        <?php 
                        $counter = 1; // Unique ID counter for accordion
                        while ($q_row = mysqli_fetch_assoc($query_sql)) {
                            // Determine status text
                            $statusText = '';
                            switch ($q_row["q_status"]) {
                                case 0:
                                    $statusText = "Pending";
                                    break;
                                case 1:
                                    $statusText = "Ongoing";
                                    break;
                                case 2:
                                    $statusText = "Solved";
                                    break;
                                case 3:
                                    $statusText = "Rejected";
                                    break;
                                default:
                                    $statusText = "Unknown";
                            }
                        ?>
                        <div class="accordion-item">
                            <h2 class="accordion-header" id="heading<?php echo $counter; ?>">
                                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
                                    data-bs-target="#collapse<?php echo $counter; ?>" aria-expanded="false"
                                    aria-controls="collapse<?php echo $counter; ?>">
                                    Query No: <?php echo $q_row["q_code"]; ?> (<?php echo $statusText; ?>)
                                </button>
                            </h2>
                            <div id="collapse<?php echo $counter; ?>" class="accordion-collapse collapse"
                                aria-labelledby="heading<?php echo $counter; ?>" data-bs-parent="#queryAccordion">
                                <div class="accordion-body">
                                    <p><strong>Query:</strong> <?php echo $q_row["query"]; ?></p>
                                    <p><strong>Solution:</strong>
                                        <?php echo $q_row["q_solution"] ?: "No solution yet."; ?></p>
                                    <p><strong>Status:</strong> <?php echo $statusText; ?></p>
                                </div>
                            </div>
                        </div>
                        <?php
                            $counter++;
                            }
                         ?>
                    </div>
                </div>
                <?php 
                } else { 
                    echo "<p>No previous queries found.</p>";
                } 
                ?>

            </div>
        </div>

        <?php include "include/footer.php"; ?>
    </section>

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>


</body>

</html>

<?php
if (isset($_POST["form_submit"])) {
    // Escape user inputs for security
    $q_client = $con->real_escape_string($_POST['q_client']);
    $con_message = $con->real_escape_string($_POST['con_message']);
    $newCode = generateUniqueCode($con);

    $capcha = $_POST['capcha'];
    $or_code = $_POST['or_code'];

    if($capcha == $or_code){

    // Insert into database
    $sql = "INSERT INTO query_table (q_client, q_code, query, q_date, q_status)
    VALUES ('$q_client', '$newCode', '$con_message', '$currentTime', '0')";

    if ($con->query($sql) === TRUE) {
        echo "<script>alert('Query submitted successfully. We will shortly notify you.'); window.location.href = 'contact.php';</script>";
    } else {
        echo "Error: " . $sql . "<br>" . $con->error;
    }
}
}
function generateUniqueCode($con) {
    $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $uniqueCode = '';
    do {
        // Generate 3 random alphabets
        $alphabets = '';
        for ($i = 0; $i < 3; $i++) {
            $alphabets .= $alphabet[rand(0, 25)];
        }

        // Generate 6 random digits
        $numbers = '';
        for ($i = 0; $i < 6; $i++) {
            $numbers .= rand(0, 9);
        }

        // Combine and shuffle
        $combined = str_shuffle($alphabets . $numbers);

        // Ensure uniqueness
        $query = "SELECT COUNT(*) as count FROM query_table WHERE q_code = '" . mysqli_real_escape_string($con, $combined) . "'";
        $result = mysqli_query($con, $query);
        $row = mysqli_fetch_assoc($result);

        $uniqueCode = $combined;
    } while ($row['count'] > 0); // Repeat if code already exists

    return $uniqueCode;
}
?>