<?php
$select = "--select--";
// Ensure sent_sms table exists
if (isset($connection)) {
    $connection->query("CREATE TABLE IF NOT EXISTS sent_sms (
        id INT AUTO_INCREMENT PRIMARY KEY,
        senderID VARCHAR(50) DEFAULT '',
        recipients TEXT,
        message TEXT,
        response TEXT,
        sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
}
if (file_exists(__DIR__ . '/../core/send_sms.php')) {
    require_once __DIR__ . '/../core/send_sms.php';
}
?>
<style>
  .sms-text {
    max-width: 250px; 
    word-wrap: break-word; 
    overflow-wrap: break-word; 
    white-space: pre-wrap; /* keep line breaks */
  }
</style>


<div class='page-title'>
    <div>
        <h1><i class='fa fa-laptop'></i> SMS</h1>
        <p>SMS Notifications</p>
    </div>
    <button class="btn btn-primary float-right" data-toggle="modal" data-target="#sendSmsModal">
        <i class="fa fa-paper-plane"></i> Send New SMS
    </button>
</div>


<div class='card mt-3'>
    <div class='card-header'>
        <h4 class='card-title text-center'>Sent SMS History</h4>
    </div>
    <div class='card-body'>
<div class="table-responsive">
            <table class="table table-bordered table-hover table-condensed table-export" cellspacing="0" width="100%" id="myTable">
    <thead>
        <tr>
            <th>#</th>
            <th>Sender ID</th>
            <th>Recipients</th>
            <th>Message</th>
            <th>Response</th>
            <th>Sent At</th>
        </tr>
    </thead>
    <tbody>
        <?php if (isset($result) && $result && ($result instanceof mysqli_result) && $result->num_rows > 0): $sn = 1; ?>
            <?php while ($row = $result->fetch_assoc()): ?>
                <?php 
                    // Decode JSON response safely
                    $responseData = json_decode($row['response'], true);
                    $msgs = isset($responseData['msg']) ? $responseData['msg'] : $row['response']; 
                ?>
                <tr>
                    <td><?= $sn++; ?></td>
                    <td><?= htmlspecialchars($row['senderID']); ?></td>

                    <td class="sms-text" title="<?= htmlspecialchars($row['recipients']); ?>">
                        <?= strlen($row['recipients']) > 15 
                            ? htmlspecialchars(substr($row['recipients'], 0, 15)) . '...' 
                            : htmlspecialchars($row['recipients']); ?>
                    </td>

                    <td class="sms-text" title="<?= htmlspecialchars($row['message']); ?>">
                        <?= strlen($row['message']) > 20 
                            ? htmlspecialchars(substr($row['message'], 0, 20)) . '...' 
                            : htmlspecialchars($row['message']); ?>
                    </td>

                    <td class="sms-text" title="<?= htmlspecialchars($msgs ?? ''); ?>">
                        <?= strlen($msgs ?? '') > 20 
                            ? htmlspecialchars(substr($msgs ?? '', 0, 20)) . '...' 
                            : htmlspecialchars($msgs ?? ''); ?>
                    </td>

                    <td><?= $row['sent_at']; ?></td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="6" class="text-center">No SMS sent yet.</td></tr>
        <?php endif; ?>
    </tbody>
</table>

    </div>
    </div>
</div>


<!-- SEND SMS MODAL -->
<!-- SMS Modal -->
<div class="modal fade" id="sendSmsModal" tabindex="-1" role="dialog" aria-labelledby="sendSmsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="sendSmsModalLabel">Send New SMS</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form method="POST" action="">
        <div class="modal-body">
            <div class="form-group">
                <label for="senderID">Sender ID:</label>
                <input type="text" name="senderID" id="senderID" value="<?php echo htmlspecialchars($senderID); ?>" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="recipients">Recipients (comma-separated):</label>
                <textarea name="recipients" id="recipients" class="form-control" rows="2" required></textarea>
            </div>
            <div class="form-group">
                <label for="message">Message:</label>
                <textarea name="message" id="message" class="form-control" rows="4" required></textarea>
            </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="send_sms" class="btn btn-primary">Send SMS</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class='card'>
	<div class="row">
		<div class="col-md-12">
			<div class='panel panel-primary'>
				<div class='panel-heading'>
					<h4 class='text-center'>Student Guardian's Contacts</h4>
				</div>
				<div class='panel-body'>
					<form method='POST' action=''>
						<div class='row'>
							<div class='col-md-8'>
								<div class='input-group'>
									<span class='input-group-addon' id='basic-addon2'>Student Class:</span>
									<select class='form-control' name='contact_class'>
										<option selected><?php echo htmlspecialchars($select); ?></option>
										<option>All</option>
										<?php
											$query = "SELECT * FROM `classes`";
											$run_query = mysqli_query($connection, $query);
											if (mysqli_num_rows($run_query) > 0) {
												while ($result = mysqli_fetch_assoc($run_query)) {
													$attendance = htmlspecialchars($result['classes']);
													echo "<option>{$attendance}</option>";
												}
											}
										?>
									</select>
								</div>
							</div>
							<div class='col-md-2'>
								<input type='submit' name='generate_contact_btn' value='SHOW CONTACT' class='btn btn-primary' />
							</div>
						</div>
					</form>
					<br />
				</div>
			</div>

			<?php
				if (isset($_POST['generate_contact_btn'])) {
					$contact_class = mysqli_real_escape_string($connection, $_POST['contact_class']);

					if ($contact_class === "All") {
						$query = "SELECT firstname, lastname, othername, guardian_phone FROM students";
					} else {
						$query = "SELECT firstname, lastname, othername, guardian_phone FROM students WHERE class = '$contact_class'";
					}

					$run_query = mysqli_query($connection, $query);

					if (mysqli_num_rows($run_query) > 0) {
						$allGuardianContacts = [];
						echo "<table class='table table-bordered' id='myTable'>
								<thead>
									<tr>
										<th class='text-center'>Student Name</th>
										<th class='text-center'>Guardian's Contact</th>
										<th class='text-center'>Action</th>
									</tr>
								</thead>
								<tbody>";

						while ($result = mysqli_fetch_assoc($run_query)) {
							$student_name = htmlspecialchars($result['firstname']) . ' ' . htmlspecialchars($result['othername']) . ' ' . htmlspecialchars($result['lastname']);
							$guardian_contacts = htmlspecialchars($result['guardian_phone']);
							$allGuardianContacts[] = $guardian_contacts;

							echo "<tr>
									<td class='text-center'>{$student_name}</td>
									<td class='text-center'>{$guardian_contacts}</td>
									<td class='text-center'>
										<button type='button' class='btn btn-sm btn-success send-sms-btn' data-contact='{$guardian_contacts}'>
											Send SMS
										</button>
									</td>
								  </tr>";
						}

						echo "</tbody></table>";

						if (!empty($allGuardianContacts)) {
							$guardianListStr = implode(',', $allGuardianContacts);
							echo "<div class='text-right'>
									<button type='button' class='btn btn-primary send-sms-btn' data-contact='{$guardianListStr}'>
										Send SMS to All
									</button>
								  </div>";
						}

					} else {
						 $_SESSION['msg']  = "No contacts found.";
						 $_SESSION['type'] = "error";
					}
				}
			?>
		</div>


        <div class="col-md-12">
            <div class='panel panel-primary'>
                <div class='panel-heading'>
                    <h4 class='text-center'>Staff Contacts</h4>
                </div>
                <div class='panel-body'>
                    <form method='POST' action=''>
                        <div class='row'>
                            <div class='col-md-2'>
                                <input type='submit' name='generate_teachers_contact_btn' value='SHOW CONTACT' class='btn btn-primary' />
                            </div>
                        </div>
                    </form>
                    <br />
                </div>
            </div>

			<?php
				if (isset($_POST['generate_teachers_contact_btn'])) {
					$query = "SELECT staff.*, role.role_name FROM staff 
							  LEFT JOIN role ON staff.role = role.id";
					$run_query = mysqli_query($connection, $query);

					if (mysqli_num_rows($run_query) > 0) {
						$allStaffContacts = [];
						echo "<table class='table table-bordered' id='myTable'>
								<thead>
									<tr>
										<th class='text-center'>Name</th>
										<th class='text-center'>Role</th>
										<th class='text-center'>Contact</th>
										<th class='text-center'>Action</th>
									</tr>
								</thead>
								<tbody>";

						while ($result = mysqli_fetch_assoc($run_query)) {
							$staff_name = htmlspecialchars($result['name']);
							$staff_role = htmlspecialchars($result['role_name']);
							$staff_contact = htmlspecialchars($result['phone']);
							$allStaffContacts[] = $staff_contact;

							echo "<tr>
									<td class='text-center'>{$staff_name}</td>
									<td class='text-center'>{$staff_role}</td>
									<td class='text-center'>{$staff_contact}</td>
									<td class='text-center'>
										<button type='button' class='btn btn-sm btn-success send-sms-btn' data-contact='{$staff_contact}'>
											Send SMS
										</button>
									</td>
								  </tr>";
						}

						echo "</tbody></table>";

						if (!empty($allStaffContacts)) {
							$staffListStr = implode(',', $allStaffContacts);
							echo "<div class='text-right'>
									<button type='button' class='btn btn-primary send-sms-btn' data-contact='{$staffListStr}'>
										Send SMS to All
									</button>
								  </div>";
						}

					} else {
						$_SESSION['msg']  = "No contacts found.";
   						$_SESSION['type'] = "error";
					}
				}
			?>
		</div>
    </div>
</div>

<!-- JavaScript to populate modal -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.send-sms-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const contactNumbers = this.getAttribute('data-contact');
            document.getElementById('recipients').value = contactNumbers;
            $('#sendSmsModal').modal('show');
        });
    });
});
</script>
