<?php
include "../email/src/Exception.php";
include "../email/src/PHPMailer.php";
include "../email/src/SMTP.php";

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
session_start();
ob_start(); // Start output buffering
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";
$userlogin=$_SESSION['email'];
$intake=$_SESSION['department'];
if (isset($_SESSION['email'])){?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" href="../../boostrap/1.css">
    <link rel="stylesheet" href="../../boostrap/2.css">
      <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
   <link rel="icon" href="favicon.png" type="image/png">
    <meta name="theme-color" content="var(--primary)">
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300..700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="res/bootstrap@5.2.0.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
</head>
<style>
    body{
        padding: 0px;
        margin:0px;
        
  font-size:16px;
  width:100%;
  background:white;
    }
    nav{
        background:var(--primary);
        line-height: 60px;
    }
     nav a{
        
        color:white;
        text-decoration:none;
    }
    nav a:hover{
        color: orange;
    }
    .pro,.money{
        display: flex;
        justify-content:center;

    }
    .pro p{
     
      margin-left:30px;
   
    }
    @media only screen and (max-width:500px){
         nav a{
        margin-left:%;
        color:white;
        text-decoration:none;
    }
    nav a:hover{
        color: orange;
    }
    .header{
      
      width:100%;
    }
    }
    .iterm{
        justify-content: center;
        display: flex;
        flex-wrap: wrap;
        margin-top:10px;
        margin-top: 10px;
        color: white;
        overflow: scroll;
        height:100%;
        text-align: center;
    }
    .iterm1{
    
    padding:20px;
    padding-left:30px;
    padding-right:30px;
    }
    .iterm a{
        width:45%;
        height :%;
        box-shadow:rgba(99, 99, 99, 0.4) 0px 2px 8px 0px;
        padding: 10px;
        text-align: center;
        border-radius: 5px;
        margin: 5px;
        background: white;
        text-decoration: none;
        border:1px solid gray;
        
        
    }
    

    .header{
        margin-top:px;
        background:var(--primary);
        background-size:cover;
        background-blend-mode:darken;
        height: 200px;
       
       width:100%;
        
        color: white;
        padding: px;
        text-align: center ;
    
      
        
    }

    .header{
      
      width:100%;
    }
    part{
      margin-top: -50px;
      position: absolute;
      background: white;
      width:93%;
      height:210px;
      top: 60px;
      left: 50%;
      transform: translate(-50%);
      color: gray;
      display: block;
      border-radius: 6px;
    }
.header img{
  width:80px;
  height: 80px;
  border-radius: 50%;
  border: 5px solid white;
  float:right;
  margin-right:15px;
  
}
    
    .iterm_box img{
      
    }
    
    .iterm  i{
      font-size: 20px;
      background:var(--primary);
      padding: 9px;
      border-radius: 5px;
    }
    .iterm_box p{
      font-size: 13px;
      margin-top: 5px;
      color:var(--primary);
      margin-bottom: 10px;
    }
    .btn{
      background:var(--primary);
      border:none;
      border-radius:2px;
      outline:none;
      color: white;
      
    }
    .div .btn{
       
      background: transparent;
      border:;
      border-radius:0px;
      padding:7px;
      border-bottom: 2px solid white;
      outline:none;
    }  
    
     
    .dash{
      color: white;
      font-weight: 900px;
      text-align : center ;
    }
    .money{
        justify-content:;
        display:flex;
        flex-wrap:wrap;
        width:100%;
       
   
    }
    .money .card1{
        width:60px;
        margin-left:10px;
        box-shadow:2px 1px 10px 0px rgb(199, 235, 202);
        margin-top:-10px;
     
    }
    #btn{
    background: orange;
    }
   
   .in{
    justify-content:center;
    display:flex;
    flex-wrap:wrap;
    padding:px;
    font-weight:1000;
    
   }
   .in p{
   font-size:15px;
   margin-top:10px;
   }
   .in .card2{
    width:100%;
    margin:5px;
    text-align:center;
    padding:5px;
    box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px;
    border-radius:6px;
    background:;
    color:var(--primary);
    border:none;
    font-size:14px;
    height:100%;
    text-decoration:none;
   }
   .in a{
   width:46%;
    margin:5px;
    text-decoration:none;
   }
   .in .card2 img{
    font-size:30px;
    color:var(--primary);
    opacity:0.4;
   }
   .loading {
            display: none;
            text-align: center;
            margin: 1rem 0;
        }

    .content{
        margin-left:210px;
        padding:10px;
    }
    .btn{
    
    }
    .action-cards {
  display: flex;
  justify-content: center;
  gap: 30px;
  flex-wrap: wrap;
  margin-top: 50px;
}

.action-card {
    margin-top:-15px;
  background: #fff;
  padding: 40px 30px;
  border-radius: 12px;
  text-align: center;
  width: 220px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  transition: 0.3s ease;
  cursor: pointer;
}
.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 25px rgba(0,0,0,0.2);
}
.action-card i {
  font-size: 40px;
  margin-bottom: 15px;
  color: var(--primary);
}
.action-card h5 {
  margin: 10px 0 0;
  color: #333;
  font-weight: bold;
}

/* Alerts */
.alert-success {
  background: #d4edda;
  color: #155724;
  border: none;
}
.alert-danger {
  background: #f8d7da;
  color: var(--primary);
  border: none;
}

</style>
<body>
        <?php include "../include/nav.php";?>

  
      
<div class="content" style="">
<<?php
// Use correct PHPMailer autoload or manual includes


include "../include/config.php";

if (isset($_POST['email'])) {
    $message = mysqli_real_escape_string($conn, $_POST['message']); 
    $subject = mysqli_real_escape_string($conn, $_POST['subject'] ?? 'NOTIFICATION');
    
    // Get school name from admin
    $school_query = mysqli_query($conn, "SELECT sname FROM admin LIMIT 1");
    $school = mysqli_fetch_assoc($school_query);
    $school_name = $school['sname'] ?? 'Unicohs University';

    $query = mysqli_query($conn, "SELECT email, studentname FROM students WHERE status='active'");
    if (!$query) {
        die("Query failed: " . mysqli_error($conn));
    }

    $sent_count = 0;
    $failed_count = 0;
    $total_students = mysqli_num_rows($query);
    
    while ($row = mysqli_fetch_assoc($query)) {
        $to   = $row['email'];
        $name = $row['studentname'];

        $mail = new PHPMailer(true);
        try {
            // SMTP Configuration
            $mail->isSMTP();
            $mail->Host       = 'unicohsuniversity.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'portal@unicohsuniversity.com';
            $mail->Password   = '@mypass1996';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = 587;
            
            // Sender
            $mail->setFrom('portal@unicohsuniversity.com', $school_name);
            $mail->addAddress($to, $name);
            $mail->addReplyTo('portal@unicohsuniversity.com', $school_name);

            // Email content
            $mail->isHTML(true);
            $mail->Subject = $subject;
            
            // Create professional HTML email
            $mail->Body = "
                <p>Dear <strong>$name</strong>,</p>
                <p>$message</p>
                <p>Best regards,<br>$school_name Administration</p>
            ";
            
            // Plain text version
            $mail->AltBody = "Dear $name,\n\n$message\n\nBest regards,\n$school_name Administration";

            if ($mail->send()) {
                $sent_count++;
            } else {
                $failed_count++;
            }
            
            // Add small delay to prevent server overload
            usleep(100000);
            
        } catch (Exception $e) {
            $failed_count++;
            continue;
        }
    }
    
    header("Location: send.php?success=Email sent to $sent_count students");
    exit();
}
?>

    <div style="padding:20px">
          <?php if (isset($_GET['success'])): ?>
    <div class="alert alert-warning py-1 mt-2"><?php echo $_GET['success']; ?></div>
  <?php endif; ?>

  <?php if (isset($_GET['error'])): ?>
    <div class="alert alert-danger py-1 mt-2"><?php echo $_GET['error']; ?></div>
  <?php endif; ?>
  
  
<?php

if (isset($_POST['sms'])) {
    $message = trim($_POST['message']);

    if (empty($message)) {
        $_SESSION['sms_error'] = "Message cannot be empty.";
        header("Location: sms.php");
        exit;
    }

    $email = 'zamatechnologyandgeneraldealer@gmail.com';
    $password = '@Jasperjere2020';
    $sender = 'UNICOHS';

    function mtn_login($email, $password) {
        $url = "https://cpassmessaging.mtn.zm:443/api/v1/accounts/users/login";
        $data = json_encode(["email" => $email, "password" => $password]);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false
        ]);
        $response = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($code == 200) {
            $json = json_decode($response, true);
            return $json['access_token'] ?? null;
        }
        return null;
    }

    function send_mtn_sms($token, $recipient, $sender, $message) {
        $url = "https://cpassmessaging.mtn.zm:443/api/v1/sms/send";
        $payload = json_encode([
            "msg" => $message,
            "name" => "ZAMA Bulk SMS",
            "category" => "PROMO",
            "sender" => $sender,
            "recipient" => $recipient,
            "clientTxnId" => "ZAMA_" . uniqid(),
            "country" => "ZM"
        ]);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "Authorization: Bearer $token"
            ],
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false
        ]);

        $res = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return ($code == 200 || $code == 202) ? json_decode($res, true) : null;
    }

    $res = mysqli_query($conn, "SELECT studentname, mobile FROM students WHERE mobile != ''");
    if (!$res || mysqli_num_rows($res) == 0) {
        $_SESSION['sms_error'] = "No students with phone numbers found.";
        header("Location: sms.php");
        exit;
    }

    $token = mtn_login($email, $password);
    if (!$token) {
        $_SESSION['sms_error'] = "Network Error. Check SMS login credentials.";
        header("Location: sms.php");
        exit;
    }

    $smsSent = false;
    while ($row = mysqli_fetch_assoc($res)) {
        $name = $row['studentname'];
        $phone = preg_replace("/[^0-9]/", "", $row['mobile']);
        if (strpos($phone, "26") !== 0) $phone = "26" . $phone;

        $resp = send_mtn_sms($token, $phone, $sender, $message);
        $status = $resp && ($resp['statusMsg'] ?? '') === "SUCCESS" ? "Sent" : "Failed";

        if ($status === "Sent") {
            $sent_time = date("Y-m-d H:i:s");
            $escaped_msg = mysqli_real_escape_string($conn, $message);
            mysqli_query($conn, "INSERT INTO sms_logs (sent_time, student_name, phone, message)
                                 VALUES ('$sent_time', '".mysqli_real_escape_string($conn, $name)."', '$phone', '$escaped_msg')");
            $smsSent = true;
        }
    }

    mysqli_close($conn);

    if ($smsSent) {
        $_SESSION['sms_success'] = "Bulk SMS Successfully Sent!";
    } else {
        $_SESSION['sms_error'] = "No SMS were sent. Check numbers or network.";
    }

    header("Location: send.php");
    exit;
}
?>
<?php
if(isset($_SESSION['sms_success'])){
    echo "<div class='alert alert-success'>".$_SESSION['sms_success']."</div>";
    unset($_SESSION['sms_success']);
}

if(isset($_SESSION['sms_error'])){
    echo "<div class='alert alert-danger'>".$_SESSION['sms_error']."</div>";
    unset($_SESSION['sms_error']);
}
?>


  </div>
  
  
 <div class="action-cards">
  <div class="action-card" data-toggle="modal" data-target="#email">
    <i class="fa fa-envelope" style="color:var(--primary)"></i>
    <h5>Bulk Email</h5>
  </div>

  <div class="action-card" data-toggle="modal" data-target="#sms">
    <i class="fa fa-comment" style="color:var(--primary)"></i>
    <h5>Bulk SMS</h5>
  </div>
</div>
<br>

</body>
</html>



<!-- sycn -->
<div class="modal fade" id="email" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">SEND BULK EMAILS</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
         <form style="background:white; border:none;padding:15px; margin-top:5px; margin-bottom:5px; border-radius:4px;" class=" bg" action="send.php" method="post">
  <h6> <I class="fa fa-edit"> </I> Fill in all required field</h6>
  <hr>
 <p>
            <span style="color:red">Note:</span> If the network connection is interrupted during the transmission, do not refresh the page.
          </p>

          
 <textarea class="form-control" name="message" placeholder="Message..." rows="6"></textarea>

          <!-- Submit Button -->
          <div class="modal-footer">
            <button type="submit" name="email" class="btn btn-success">Send</button>
          </div>
 
 
 
 </form>
      </div>

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



<!-- filter class -->

<div class="modal fade" id="sms" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">

  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">SEND BULK SMS</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
       <form style="background:white; border:none;padding:15px; margin-top:5px; margin-bottom:5px; border-radius:4px;" class=" bg" action="send.php" method="post">
  <h6> <I class="fa fa-edit"> </I> Fill in all required field</h6>
  <hr>
 

 <span style="color:red">Note:</span> If the network connection is interrupted during the transmission, do not refresh the page.
          </p>

          
 <textarea class="form-control" name="message" placeholder="Message..." rows="6"></textarea>

          <!-- Submit Button -->
          <div class="modal-footer">
            <button type="submit" name="sms" class="btn btn-success">Send</button>
          </div>
 
        </form>
      </div>
    </div>
  </div>
</div>
<?php

}else {

  header("location:../index.php");
}
?>







