



<style>
  .sms-text {
    max-width: 250px; 
    word-wrap: break-word; 
    overflow-wrap: break-word; 
    white-space: pre-wrap; /* keep line breaks */
  }
</style>





<?php


require_once('public/connection.php');

// =================== FETCH CLASSES FOR MODAL ===================
$classes = [];
$query = "SELECT * FROM `classes` ORDER BY classes ASC";
$run_query = mysqli_query($connection, $query);
if ($run_query && mysqli_num_rows($run_query) > 0) {
    while ($row = mysqli_fetch_assoc($run_query)) {
        $classes[] = $row['classes'] ?? '';
    }
}

// =================== HANDLE SEND RESULT SMS ===================
if (isset($_POST['send_result_sms'])) {
    $class = $_POST['res_class'] ?? '';
    $term = $_POST['res_term'] ?? '';
    $session = $_POST['res_session'] ?? '';

    if ($class && $term && $session) {

        // Format session from "2025/2026" to "25/26"
        $sessionShort = substr($session, 2, 2) . "/" . substr($session, 7, 2);

        // Fetch students and results
        $query = "
            SELECT 
                s.firstname, s.lastname, s.othername, s.reg_number, s.guardian_phone,
                r.subject_total
            FROM students s
            JOIN results1 r ON s.reg_number = r.reg_number
            WHERE s.class = '$class'
              AND r.class = '$class'
              AND r.term = '$term'
              AND r.session = '$session'
            ORDER BY s.reg_number
        ";
        $run_query = mysqli_query($connection, $query);

        if (mysqli_num_rows($run_query) > 0) {

            $students_scores = [];

            // Collect total per student
            while ($row = mysqli_fetch_assoc($run_query)) {
                $reg = $row['reg_number'] ?? '';
                if (!isset($students_scores[$reg])) {
                    $students_scores[$reg] = [
                        'name' => trim(($row['firstname'] ?? '') . ' ' . ($row['othername'] ?? '') . ' ' . ($row['lastname'] ?? '')),
                        'guardian_phone' => $row['guardian_phone'] ?? '',
                        'total_score' => 0,
                        'num_subjects' => 0
                    ];
                }
                $students_scores[$reg]['total_score'] += $row['subject_total'] ?? 0;
                $students_scores[$reg]['num_subjects']++;
            }

            // Send SMS to each student
            foreach ($students_scores as $reg => $student) {
                $total_score = $student['total_score'];
                $average = $student['num_subjects'] > 0 ? round($total_score / $student['num_subjects'], 2) : 0;

                $msg = "Dear Parent, " . $student['name'] . " ($class • $term • $sessionShort)\n";
                $msg .= "Total: $total_score, Average: $average\n";

                // Automated server-based result link using reg number
                $serverURL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") 
                             . "://{$_SERVER['HTTP_HOST']}";
                $resultLink = $serverURL . "/result.php?reg=" . urlencode($reg);
                $msg .= "Check full result: $resultLink";

                $phone = $student['guardian_phone'];

                if (!empty($phone) && !empty($senderID)) {
                    $curl = curl_init();
                    curl_setopt_array($curl, [
                        CURLOPT_URL => 'https://my.kudisms.net/api/sms',
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_CUSTOMREQUEST => 'POST',
                        CURLOPT_POSTFIELDS => [
                            'token' => $token ?? '',
                            'senderID' => $senderID,
                            'recipients' => $phone,
                            'message' => $msg,
                            'gateway' => '2',
                            'messageEncoding' => 2
                        ],
                    ]);
                    $response = curl_exec($curl);
                    curl_close($curl);

                    // Save SMS to DB
                    $stmt = $connection->prepare("INSERT INTO sent_sms (senderID, recipients, message, response) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("ssss", $senderID, $phone, $msg, $response);
                    $stmt->execute();
                    $stmt->close();
                }
            }

            $_SESSION['msg'] = "Result SMS sent successfully.";
            $_SESSION['type'] = "success";
            header("Location: send_sms");
            exit();

        } else {
            $_SESSION['msg'] = "No results found for class: $class, $term, $session.";
            $_SESSION['type'] = "error";
            header("Location: send_sms");
            exit();
        }
    }
}



// =================== HANDLE NORMAL SEND SMS ===================
if (isset($_POST['send_sms'])) {
    $senderID = $_POST['senderID'] ?? '';
    $recipients = $_POST['recipients'] ?? '';
    $message = $_POST['message'] ?? '';

    $token = $token ?? '';

    if ($senderID && $recipients && $message && $token) {
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://my.kudisms.net/api/sms',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => [
                'token' => $token,
                'senderID' => $senderID,
                'recipients' => $recipients,
                'message' => $message,
                'gateway' => '2'
            ],
        ]);
        $response = curl_exec($curl);
        curl_close($curl);

        $stmt = $connection->prepare("INSERT INTO sent_sms (senderID, recipients, message, response) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssss", $senderID, $recipients, $message, $response);
        $stmt->execute();
        $stmt->close();

        $_SESSION['msg'] = "SMS sent successfully.";
        $_SESSION['type'] = "success";
        header("Location: send_sms");
        exit();
    }
}
// =================== HANDLE SEND WHATSAPP RESULTS ===================
// =================== HANDLE SEND WHATSAPP RESULTS ===================
$waParents = [];

if (isset($_POST['send_whatsapp_results'])) {

    $class   = $_POST['wa_class'] ?? '';
    $term    = $_POST['wa_term'] ?? '';
    $session = $_POST['wa_session'] ?? '';

    if ($class && $term && $session) {

        $query = "SELECT firstname, lastname, othername, reg_number, guardian_phone
                  FROM students
                  WHERE class = '$class'
                  AND guardian_phone != ''";

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

        while ($row = mysqli_fetch_assoc($run)) {

            $phone = preg_replace('/[^0-9]/', '', $row['guardian_phone']);
            if (substr($phone, 0, 1) === '0') {
                $phone = '234' . substr($phone, 1);
            }

            $studentName = trim(
                ($row['firstname'] ?? '') . ' ' .
                ($row['othername'] ?? '') . ' ' .
                ($row['lastname'] ?? '')
            );

            $resultLink = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}/result.php?" .
    "reg=" . urlencode($row['reg_number']) .
    "&class=" . urlencode($class) .
    "&term=" . urlencode($term) .
    "&session=" . urlencode($session) .
    "&name=" . urlencode($row['firstname'] . ' ' . $row['othername'] . ' ' . $row['lastname']);


            $message =
                "Dear Parent of {$studentName},\n\n" .
                "Class: {$class}\n" .
                "Term: {$term}\n" .
                "Session: {$session}\n\n" .
                "Click to view/download result:\n{$resultLink}";

            $waParents[] = [
                'name'  => $studentName,
                'phone' => $phone,
                'link'  => "https://wa.me/{$phone}?text=" . urlencode($message)
            ];
        }
    }
}




// =================== FETCH SENT SMS HISTORY ===================
$sresult = $connection->query("SELECT * FROM sent_sms ORDER BY sent_at DESC");
?>
<?php if (!empty($waSingleLink)): ?>
<script>
if (confirm("This will open WhatsApp Web with all prefilled messages. Continue?")) {
    window.open("<?= $waSingleLink ?>", "_blank");
}
</script>
<?php endif; ?>


<!-- =================== PAGE CONTENT =================== -->
<div class='page-title'>
    <div>
        <h1><i class='fa fa-laptop'></i> SMS</h1>
        <p>SMS Notifications</p>
    </div>
    <div class="d-flex flex-column flex-sm-row justify-content-end gap-2 mb-3">
    <!-- Send Result -->
    <button class="btn btn-success" data-toggle="modal" data-target="#sendResultModal">
        <i class="fa fa-envelope"></i> Send Result
    </button>

    <!-- Send New SMS -->
    <button class="btn btn-primary" data-toggle="modal" data-target="#sendSmsModal">
        <i class="fa fa-paper-plane"></i> Send New SMS
    </button>

    <!-- Send Result via WhatsApp -->
    <button class="btn btn-success" data-toggle="modal" data-target="#sendResultWhatsAppModal">
        <i class="fa-brands fa-whatsapp"></i> Send Result via WhatsApp
    </button>
</div>


</div>
<!-- =================== WHATSAPP RESULT MODAL =================== -->
<?php if (!empty($waParents)): ?>
<div class="card mt-4">
    <div class="card-header bg-success text-white">
        <h5 class="mb-0">
            <i class="fa-brands fa-whatsapp"></i> WhatsApp Result Messages
        </h5>
    </div>

    <div class="card-body">
        <p class="text-muted">
            Click <b>SEND</b> for each parent. WhatsApp will open for that parent only.
        </p>

        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Student</th>
                        <th>Parent Phone</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $sn = 1; foreach ($waParents as $parent): ?>
                    <tr>
                        <td><?= $sn++ ?></td>
                        <td><?= htmlspecialchars($parent['name']) ?></td>
                        <td><?= htmlspecialchars($parent['phone']) ?></td>
                        <td>
                            <a href="<?= $parent['link'] ?>"
                               target="_blank"
                               class="btn btn-success btn-sm">
                                <i class="fa-brands fa-whatsapp"></i> Send
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>


<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" 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 ($sresult->num_rows > 0): $sn = 1; ?>
                        <?php while ($row = $sresult->fetch_assoc()): ?>
                            <?php
                                $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>


<!-- =================== MODALS (Send Result & Send SMS) =================== -->
<!-- Modal for WhatsApp Result -->
<!-- =================== SEND RESULT VIA WHATSAPP MODAL =================== -->
<div class="modal fade" id="sendResultWhatsAppModal" tabindex="-1" role="dialog" aria-labelledby="sendResultWhatsAppModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title" id="sendResultWhatsAppModalLabel">
          <i class="fa-brands fa-whatsapp"></i> Send Result via WhatsApp
        </h5>
        <button type="button" class="close text-white" data-dismiss="modal">
          <span>&times;</span>
        </button>
      </div>

      <!-- Modal Form -->
      <form method="POST" action="">
        <div class="modal-body">

          <div class="alert alert-warning">
            ⚠️ This will prepare WhatsApp messages for <b>each parent individually</b>.
            You will click <b>SEND</b> for each parent.
          </div>

          <div class="row">

            <!-- Class -->
            <div class="col-md-4 mb-3">
              <label><strong>Select Class</strong></label>
              <select name="wa_class" class="form-control" required>
                <option value="">-- Select Class --</option>
                <?php foreach ($classes as $cls): ?>
                  <option value="<?= htmlspecialchars($cls) ?>">
                    <?= htmlspecialchars($cls) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <!-- Term -->
            <div class="col-md-4 mb-3">
              <label><strong>Select Term</strong></label>
              <select name="wa_term" class="form-control" required>
                <option value="">-- Select Term --</option>
                <option value="First Term">First Term</option>
                <option value="Second Term">Second Term</option>
                <option value="Third Term">Third Term</option>
              </select>
            </div>

            <!-- Session -->
            <div class="col-md-4 mb-3">
              <label><strong>Select Session</strong></label>
              <select name="wa_session" class="form-control" required>
                <option value="">-- Select Session --</option>
                <option value="2025/2026">2025/2026</option>
                <option value="2024/2025">2024/2025</option>
              </select>
            </div>

          </div>
        </div>

        <!-- Footer -->
        <div class="modal-footer">
          <button type="submit"
                  name="send_whatsapp_results"
                  class="btn btn-success">
            <i class="fa-brands fa-whatsapp"></i> Generate WhatsApp Messages
          </button>
        </div>

      </form>

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



<!-- SEND RESULT MODAL -->
<div class="modal fade" id="sendResultModal" tabindex="-1" role="dialog" aria-labelledby="sendResultModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title" id="sendResultModalLabel">Send Result SMS to Guardians</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="row">
            <div class="col-md-4 mb-3">
              <label for="res_class">Select Class:</label>
              <select name="res_class" id="res_class" class="form-control" required>
                  <option value="">--Select Class--</option>
                  <?php
                  foreach($classes as $cls){
                      echo "<option value='".htmlspecialchars($cls ?? '')."'>".htmlspecialchars($cls ?? '')."</option>";
                  }
                  ?>
              </select>
            </div>

            <div class="col-md-4 mb-3">
              <label for="res_term">Select Term:</label>
              <select name="res_term" id="res_term" class="form-control" required>
                  <option value="">--Select Term--</option>
                  <option value="First Term">First Term</option>
                  <option value="Second Term">Second Term</option>
                  <option value="Third Term">Third Term</option>
              </select>
            </div>

            <div class="col-md-4 mb-3">
              <label for="res_session">Select Session:</label>
              <select name="res_session" id="res_session" class="form-control" required>
                  <option value="">--Select Session--</option>
                  <option value="2025/2026">2025/2026</option>
                  <option value="2024/2025">2024/2025</option>
              </select>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="submit" name="send_result_sms" class="btn btn-success">
              <i class="fa fa-paper-plane"></i> Send Result SMS
          </button>
        </div>
      </form>
    </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>
<?php if (!empty($waLinks)): ?>
<script>
document.addEventListener('DOMContentLoaded', function () {

    const waLinks = <?= json_encode($waLinks); ?>;
    if (!waLinks.length) return;

    if (!confirm(
        "This will open WhatsApp chats for ALL parents.\n\n" +
        "You must click SEND in each chat.\n\nContinue?"
    )) {
        return;
    }

    let index = 0;

    function openNext() {
        if (index >= waLinks.length) return;

        window.open(waLinks[index], '_blank');
        index++;

        // Wait before opening next chat
        setTimeout(openNext, 1200);
    }

    openNext();
});
</script>
<?php endif; ?>
