<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once '../auth/auth.php';
require_once '../models/db_connection.php';

// Fetch received messages
$receiver_id = $_SESSION['user'];  // Get the logged-in user's ID

// Prepare the SQL statement to retrieve received messages
$query = "SELECT m.id, m.message, m.read_status, m.sendtime, u.username 
          FROM messages m 
          JOIN users u ON m.sender_id = u.id 
          WHERE m.receiver_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $receiver_id);
$stmt->execute();
$result = $stmt->get_result();

// Store received messages in an array
$allReceivedMessages = [];
while ($row = $result->fetch_assoc()) {
  $allReceivedMessages[] = $row;
}

// Fetch sent messages
$sender_id = $_SESSION['user'];  // Get the logged-in user's ID

// Prepare the SQL statement to retrieve sent messages
$querySent = "SELECT m.message, m.sendtime, u.username 
              FROM messages m 
              JOIN users u ON m.receiver_id = u.id 
              WHERE m.sender_id = ?";
$stmtSent = $conn->prepare($querySent);
$stmtSent->bind_param("i", $sender_id);
$stmtSent->execute();
$resultSent = $stmtSent->get_result();

// Store sent messages in an array
$allSentMessages = [];
while ($rowSent = $resultSent->fetch_assoc()) {
  $allSentMessages[] = $rowSent;
}

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

<head>
  <title>Student | Add Student </title>
  <?php include("../templates/header.php"); ?>
</head>

<body>
  <?php
  if (isset($_GET["message"])) {
    $message = $_GET["message"];
    echo "<script>alert('" . $message . "')</script>";
  }
  ?>
  <div class="container-scroller">
    <!-- partial:partials/_navbar.html -->
    <?php include("../templates/nav.php"); ?>
    <!-- partial -->
    <div class="container-fluid page-body-wrapper">
      <!-- partial:partials/_sidebar.html -->
      <?php include("../templates/sidenav.php"); ?>
      <!-- partial -->
      <div class="main-panel">
        <div class="content-wrapper">
          <div class="col-md-6 grid-margin stretch-card">
            <div class="card">
              <div class="card-body">
                <h4 class="card-title">Send Message</h4>
                <p class="card-description">
                  Create <code>Message</code>
                </p>
                <form action="" method="POST" id="messageForm">
                  <div class="form-group">
                    <label for="exampleFormControlSelect2">Send To</label>
                    <select name="receiver" id="receiver" class="form-control">
                      <?php
                      $getuser = mysqli_query($conn, "SELECT * FROM users");
                      while ($getuserdata = mysqli_fetch_array($getuser)) {
                      ?>
                        <option value="<?= $getuserdata['id'] ?>"><?= htmlspecialchars($getuserdata['username']) ?></option>
                      <?php } ?>
                    </select>
                  </div>
                  <label for="exampleFormControlSelect2">message</label>
                  <textarea name="message" id="message" class="form-control" cols="10" rows="10">

                  </textarea>
                  <br>

                  <div class="col-sm-9 mt-6">
                    <input type="submit" name="sendMessage" class="btn btn-dark btn-lg" value="Send Message">
                  </div>
              </div>
              </form>
            </div>
          </div>
          <!-- mesages table -->
          <div class="row">
            <div class="col-md-6 grid-margin stretch-card">
              <div class="card">
                <div class="card-body">
                  <h4 class="card-title">Received Messages</h4>

                  <table class="table table-responsive table-bordered display" id="example" style="width:100%">
                    <thead>
                      <tr>
                        <th>Received From</th>
                        <th> Message</th>
                        <th>DateTime</th>
                        <th>Status</th>

                      </tr>
                      </tr>
                    </thead>
                    <tbody>
                      <?php if (!empty($allReceivedMessages)) : ?>
                        <?php foreach ($allReceivedMessages as $receivedMessage) : ?>
                          <tr class="message-row">
                            <td><?= htmlspecialchars($receivedMessage['username']) ?></td>
                            <td><?= htmlspecialchars($receivedMessage['message']) ?></td>
                            <td><?= htmlspecialchars($receivedMessage['sendtime']) ?></td>
                            <td>
                              <?php
                              $stat = $receivedMessage['read_status'];
                                if($stat == 0) {
                                  ?>
                                  <a href="up_message.php?id=<?php echo $receivedMessage['id']; ?>" class="btn btn-dark btn-lg "> Mark as read</a>
                                  <?php
                                }      
                                else{
                                  echo "Read";
                                }                     
                              ?>
                            </td>
                          </tr>
                        <?php endforeach; ?>
                      <?php else : ?>
                        <tr>
                          <td colspan="3" class="text-center">No messages received.</td>
                        </tr>
                      <?php endif; ?>
                    </tbody>
                  </table>
                </div>
              </div>
              
             
            </div>
            <div class="col-md-6 grid-margin stretch-card">
              <div class="card">
                <div class="card-body">
                  <h4 class="card-title">Sent Messages</h4>

                  <table class="table table-responsive table-bordered display" id="example" style="width:100%">
                    <thead>
                      <tr>
                        <th>Sent To</th>
                        <th> Message</th>
                        <th>DateTime</th>

                      </tr>
                      </tr>
                    </thead>
                    <tbody>
                      <?php if (!empty($allSentMessages)) : ?>
                        <?php foreach ($allSentMessages as $sentMessage) : ?>
                          <tr>
                            <td><?= htmlspecialchars($sentMessage['username']) ?></td>
                            <td><?= htmlspecialchars($sentMessage['message']) ?></td>
                            <td><?= htmlspecialchars($sentMessage['sendtime']) ?></td>
                          </tr>
                        <?php endforeach; ?>
                      <?php else : ?>
                        <tr>
                          <td colspan="3" class="text-center">No messages sent.</td>
                        </tr>
                      <?php endif; ?>
                    </tbody>
                  </table>
                </div>
              </div>

            </div>

          </div>
          <!-- content-wrapper ends -->
          <!-- partial:partials/_footer.html -->
          <?php include("../templates/footer.php"); ?>

          <!-- partial -->
        </div>
        <!-- main-panel ends -->
      </div>
      <!-- page-body-wrapper ends -->
    </div>
    <?php include("../templates/inc_scripts.php"); ?>
    
    <script>
      $(document).ready(function() {
        $('#messageForm').on('submit', function(e) {
          e.preventDefault();
          const receiver = $('#receiver').val();
          const message = $('#message').val();

          $.ajax({
            url: 'send_message.php',
            method: 'POST',
            data: {
              receiver: receiver,
              message: message
            },
            success: function(response) {
              $('#messageStatus').html(response);
              $('#messageForm')[0].reset(); // Clear form after message sent
            }
          });
        });
      });

      function loadMessages() {
        $.ajax({
          url: 'get_messages.php',
          method: 'GET',
          success: function(data) {
            $('#messages').html(data); // Display fetched messages
          }
        });
      }

      setInterval(loadMessages, 3000); // Fetch new messages every 3 seconds
    </script>
</body>

</html>