<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['master_admin']);
    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">
                <?php
                $query_sql = mysqli_query($con, "SELECT q.*, u.uname FROM query_table q LEFT JOIN users u ON q.q_client = u.uid ORDER BY q.q_id DESC");
                if (mysqli_num_rows($query_sql) > 0) {
                ?>
                <div class="card mt-3 p-2">
                    <h5>Recent Queries:</h5>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Query No</th>
                                    <th>Client Name</th>
                                    <th>Query</th>
                                    <th>Solution</th>
                                    <th>Remarks</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                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";
                                    }
                                ?>
                                <tr>
                                    <td><?php echo $q_row["q_code"]; ?></td>
                                    <td><?php echo $q_row["uname"] ?: "Unknown"; ?></td>
                                    <td><?php echo $q_row["query"]; ?></td>
                                    <td><?php echo $q_row["q_solution"] ?: "No solution yet."; ?></td>
                                    <td><?php echo $q_row["q_remarks"] ?: "No remarks yet."; ?></td>
                                    <td>
                                        <select class="form-select form-select-sm status-select"
                                            data-id="<?php echo $q_row["q_id"]; ?>">
                                            <option value="0" <?php echo $q_row["q_status"] == 0 ? 'selected' : ''; ?>>
                                                Pending</option>
                                            <option value="1" <?php echo $q_row["q_status"] == 1 ? 'selected' : ''; ?>>
                                                Ongoing</option>
                                            <option value="2" <?php echo $q_row["q_status"] == 2 ? 'selected' : ''; ?>>
                                                Solved</option>
                                            <option value="3" <?php echo $q_row["q_status"] == 3 ? 'selected' : ''; ?>>
                                                Rejected</option>
                                        </select>
                                    </td>
                                    <td>
                                        <button class="btn btn-primary btn-sm" data-bs-toggle="modal"
                                            data-bs-target="#solutionModal"
                                            onclick="openSolutionModal(<?php echo $q_row['q_id']; ?>, '<?php echo addslashes($q_row['q_solution']); ?>')">
                                            Solution</button>
                                        <button class="btn btn-secondary btn-sm" data-bs-toggle="modal"
                                            data-bs-target="#remarkModal"
                                            onclick="openRemarkModal(<?php echo $q_row['q_id']; ?>, '<?php echo addslashes($q_row['q_remarks']); ?>')">
                                            Remark</button>

                                    </td>
                                </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </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"; ?>

    <!-- Solution Modal -->
    <div class="modal fade" id="solutionModal" tabindex="-1" aria-labelledby="solutionModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="solutionModalLabel">Update Solution</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="solutionQueryId">
                    <div class="mb-3">
                        <textarea id="solutionText" class="form-control" rows="5"
                            placeholder="Enter solution"></textarea>
                    </div>
                    <button type="button" class="btn btn-primary" onclick="updateSolution()">Save</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Remark Modal -->
    <div class="modal fade" id="remarkModal" tabindex="-1" aria-labelledby="remarkModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="remarkModalLabel">Update Remark</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="remarkQueryId">
                    <div class="mb-3">
                        <textarea id="remarkText" class="form-control" rows="5" placeholder="Enter remark"></textarea>
                    </div>
                    <button type="button" class="btn btn-primary" onclick="updateRemark()">Save</button>
                </div>
            </div>
        </div>
    </div>

    <script>
    // Handle status update
    document.querySelectorAll('.status-select').forEach(select => {
        select.addEventListener('change', function() {
            const queryId = this.getAttribute('data-id');
            const newStatus = this.value;
            fetch('update_query_status.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        q_id: queryId,
                        q_status: newStatus
                    })
                })
                .then(response => response.text())
                .then(data => alert(data));
        });
    });

    function openSolutionModal(queryId, solution) {
        document.getElementById("solutionQueryId").value = queryId;
        document.getElementById("solutionText").value = solution || "";
    }

    function openRemarkModal(queryId, remark) {
        document.getElementById("remarkQueryId").value = queryId;
        document.getElementById("remarkText").value = remark || "";
    }

    function updateSolution() {
        const queryId = document.getElementById("solutionQueryId").value;
        const solution = document.getElementById("solutionText").value;

        fetch("update_solution.php", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    q_id: queryId,
                    q_solution: solution
                }),
            })
            .then((response) => response.text())
            .then((result) => {
                alert(result);
                location.reload(); // Reload to see the updated data
            })
            .catch((error) => console.error("Error:", error));
    }

    function updateRemark() {
        const queryId = document.getElementById("remarkQueryId").value;
        const remark = document.getElementById("remarkText").value;

        fetch("update_remark.php", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    q_id: queryId,
                    q_remarks: remark
                }),
            })
            .then((response) => response.text())
            .then((result) => {
                alert(result);
                location.reload(); // Reload to see the updated data
            })
            .catch((error) => console.error("Error:", error));
    }
    </script>

</body>

</html>