<?php
// Include database connection file
include("connection.php");

function generateUniqueId($conn) {
    do {
        // Generate a random report ID (you can customize this format)
        $reportId = 'REP' . rand(1000, 9999);

        // Check if this report ID already exists in the database
        $checkQuery = "SELECT Report_ID FROM report WHERE Report_ID = '$reportId'";
        $result = mysqli_query($conn, $checkQuery);
    } while (mysqli_num_rows($result) > 0); // Repeat until a unique ID is found

    return $reportId;
}

if (isset($_POST['submit'])) {
    // Capture values from HTML form
    $rentid = $_POST['renterid'];
    $dept = $_POST['department'];
    $fback = $_POST['feedback'];

    // Generate a unique Report ID
    $repid = generateUniqueId($conn);

    // Insert into report table
    $sql = "INSERT INTO report (Report_ID, Renter_ID, Department, Feedback) 
            VALUES ('$repid', '$rentid', '$dept', '$fback')";

    if (mysqli_query($conn, $sql)) {
        echo "<script>alert('Data Been Saved.');</script>";
        echo "<script>window.location = 'sentFeedback.php'</script>";
        exit();
    } else {
        echo "Error: " . mysqli_error($conn);
        echo "<script>window.location = 'sentFeedback.php'</script>";
        exit();
    }
    mysqli_close($conn); // Close the database connection
}
?>
