<?php 
include('session.php');
include('config.php');

// Handle sending notification to all users
if(isset($_POST['send_to_all'])) {
    $notification_title = mysqli_real_escape_string($db, $_POST['notification_title']);
    $notification_message = mysqli_real_escape_string($db, $_POST['notification_message']);
    $current_date = date("Y-m-d H:i:s");
    
    // Get all users except admin
    $users_query = "SELECT email FROM members WHERE email != 'admin@gmail.com'";
    $users_result = mysqli_query($db, $users_query);
    
    while($user = mysqli_fetch_assoc($users_result)) {
        $insert_query = "INSERT INTO notifications (email, title, message, date_created, status) 
                         VALUES ('".$user['email']."', '$notification_title', '$notification_message', '$current_date', 'unread')";
        mysqli_query($db, $insert_query);
    }
    
    echo "<script>alert('Notification sent to all users successfully!');</script>";
}
?>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
      <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ADMIN</title>
    <link rel="icon" type="image/png" href="images/logo_2.png"/>
    <!-- BOOTSTRAP STYLES-->
    <link href="assets/css/bootstrap.css" rel="stylesheet" />
     <!-- FONTAWESOME STYLES-->
    <link href="assets/css/font-awesome.css" rel="stylesheet" />
     <!-- MORRIS CHART STYLES-->
    <link href="assets/js/morris/morris-0.4.3.min.css" rel="stylesheet" />
        <!-- CUSTOM STYLES-->
    <link href="assets/css/custom.css" rel="stylesheet" />
     <!-- GOOGLE FONTS-->
   <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />

  <link rel="stylesheet" href="css/css/spinners.css" type="text/css">

   <style>
    /* The Modal (background) */
    .modal {
      display: none; /* Hidden by default */
      position: fixed; /* Stay in place */
      z-index: 10000000; /* Sit on top */
      padding-top: 100px; /* Location of the box */
      left: 0;
      top: 0;
      width: 100%; /* Full width */
      height: 100%; /* Full height */
      overflow: auto; /* Enable scroll if needed */
      background-color: rgb(0,0,0); /* Fallback color */
      background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
    }

    /* Modal Content */
    .modal-content {
      background-color: #fefefe;
      margin: auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
    }

    /* The Close Button */
    .close {
      color: #aaaaaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
    }

    .close:hover,
    .close:focus {
      color: #000;
      text-decoration: none;
      cursor: pointer;
    }

    /* Notification to All Modal */
    #notifyAllModal .modal-content {
      width: 50%;
      border-radius: 10px;
    }

    #notifyAllModal .form-group {
      margin-bottom: 15px;
    }

    #notifyAllModal label {
      font-weight: bold;
    }

    #notifyAllModal textarea {
      resize: vertical;
      min-height: 100px;
    }

    /* Table Styles */
    .table-responsive {
        overflow-x: auto;
    }

    .table {
        width: 100%;
        margin-bottom: 20px;
    }

    .table th {
        background-color: #f5f5f5;
        font-weight: bold;
        text-align: left;
        padding: 10px;
    }

    .table td {
        padding: 10px;
        border-bottom: 1px solid #ddd;
    }

    .table tr:hover {
        background-color: #f9f9f9;
    }
    
    .status-unread {
        color: #d9534f;
        font-weight: bold;
    }
    
    .status-read {
        color: #5cb85c;
    }
</style>

</head>
<body>
    
    <div id="wrapper">
        <nav class="navbar navbar-default navbar-cls-top " role="navigation" style="margin-bottom: 0">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-collapse" >
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="admin.php" style="background-color: orange;">ADMIN</a> 
            </div>
  <div style="color: white;
padding: 15px 50px 5px 50px;
float: right;
font-size: 16px;"> 


        <!-- LOGOUT -->
        <?php echo $_SESSION['login_user']; ?> &nbsp; <a id="myBtn" class="btn btn-danger square-btn-adjust">Logout</a> </div>
        
        <!-- The Modal -->
        <div id="myModal" class="modal">

        <!-- Modal content -->
        <div class="modal-content" style="border-radius: 20px; height: 235px; width: 300px;">
        <span class="close">&times;</span>
        <h3>Logout</h3>
        <h4>Are you sure you want to logout?</h4>
        <br><br><br>
        <a onclick="document.getElementById('myModal').style.display='none'" class="logout" style="cursor: pointer; width: 100px; float:right; width: 70px; padding: 10px; color:white; margin-top:-20px; text-align: center; background-color: gray; border-radius: 5px; width: 100px;">No</a>
        <a href="logout.php" id="myBtn" class="logout"  style="cursor: pointer; width: 70px; padding: 10px; color:white; text-align: center; float:right; margin-top:-20px; margin-right: 5px; background-color: #4c9be1; border-radius: 5px; width: 100px;">Yes</a>

        </div>
        </div>
        </nav>   
           <!-- /. NAV TOP  -->
                <nav class="navbar-default navbar-side" role="navigation" style="height: 150%;">
            <div class="sidebar-collapse">
                <ul class="nav" id="main-menu">
                <li class="text-center">
                    <img src="images/logo_1.jpg" class=" img-responsive" style="border-radius: 50%; width: 230px; padding: 20px;"/>
                    </li>
                
                    
                    <li>
                        <a class="active-menu"  href="admin.php" ><i class="fa fa-dashboard fa-3x" ></i> Dashboard</a>
                    </li>
                    <li>
                        <a href="data_analytics.php" style="height: 80px; padding-top:35px;"><img src="images/monitoring.png" width="71px" height="50px" style="margin-left: -18px; margin-top: -18px; float: left;"/><i class="fa fa-3x"></i> <span style="margin-left: -10px;">Data Analytics</span></a>
                    </li>
                    <li><a class="" href="bill_list.php" style="height: 80px; padding-top:35px;"><img src="images/bill.png" width="60px" height="63px" style="margin-left: -10px; margin-top: -20px; float: left;"/><i class="fa fa-3x"></i> Bill Management</a></li> 
                    <li><a class="" href="demand_forecasting.php" style="height: 80px; padding-top:35px;"><img src="images/forecasting_icon.png" width="80px" height="58px" style="margin-left: -20px; margin-top: -20px; float: left;"/><i class="fa fa-3x"></i> Demand Forecasting</a></li>  
                    <li><a class="" href="prioritization.php" style="height: 80px; padding-top:35px;"><img src="images/a.png" width="60px" height="58px" style="margin-left: -10px; margin-top: -20px; float: left; border-radius: 50%;"/><i class="fa fa-3x"></i>Prioritization</a></li>  
                    <!-- <li>-->
                    <!--    <a  href="messages.php" style="height: 80px; padding-top:35px;"><img src="images/message_white.jpg" width="50px" height="50px" style="margin-left: -5px; margin-top: -17px; float: left;"><i class="fa fa-3x"></i> Messages</a>-->
                    <!--</li>-->
                    <li>
                        <a  href="complaints.php" style="height: 80px; padding-top:35px;"><img src="images/task_gray.png" width="61px" height="50px" style="margin-left: -11px; margin-top: -18px; float: left;"/><i class="fa fa-3x"></i> Complaints</a>
                    </li>
                    <li>
                        <a href="announcements-admin.php" style="height: 80px; padding-top:35px;"><img src="images/announcement.png" width="61px" height="50px" style="margin-left: -11px; margin-top: -18px; float: left;"/> &nbsp &nbspAnnouncements</a>
                    </li> 
                    <li>
                        <a  href="notifications.php" style="height: 80px; padding-top:35px;"><img src="images/notification_white.png" width="50px" height="50px" style="margin-left: -9px; margin-top: -18px; float: left;"/><i class="fa fa-3x"></i> Notifications</a>
                    </li>  
                    <li>
                        <a  href="accounts.php" style="height: 80px; padding-top:35px;"><img src="images/accounts_white1.png" width="60px" height="63px" style="margin-left: -10px; margin-top: -20px; float: left;"/><i class="fa fa-3x"></i> Accounts</a>
                    </li>     
                    <li>
                        <a href="vmc-su.php"><i class="fa fa-sitemap fa-3x"></i> &nbsp VMC</a>
                    </li>       
                </ul>
               
            </div>
            
        </nav>  
        <!-- /. NAV SIDE  -->
        <div id="page-wrapper" style="min-height: 30px;">
            <div id="page-inner" style="min-height: 30px; height: 600px;">
                    <h2 style="color: white; background-color: gray; padding: 18px; margin-top: -0.1px; font-family: Arial; font-weight: bold; font-size: 27px;">&nbsp DASHBOARD</h2>  
            <hr />         
                 <!-- /. ROW  -->
                <div class="row">
            <a href="accounts.php">  
                <div class="col-md-4 col-sm-6 col-xs-6">         
            <div class="panel panel-back noti-box" style="background-color: #f1f1f1;">
            <center><img src="images/users_icon.png" alt="Reports" style="width:140px; height:95px;"></center>
            <center><div class="text-box">
            <?php 
            $sql_users = mysqli_query($db, "SELECT * FROM members WHERE email='admin@gmail.com'");
                $users = 0;
                while($DB_ROW = mysqli_fetch_array($sql_users)) {
                    $users++;
                }
                if($users > 1){
                    $user_lbl = "Users";
                }
                else{
                    $user_lbl = "User";
                }
            ?>
                    <p class="main-text"><?php echo $users; ?> <?php echo $user_lbl; ?></p>
                    <p class="text-muted">Active</p>
                </div></center>
             </div>
             </div>
            </a>
            
            <a href="complaints.php">  
                <div class="col-md-4 col-sm-6 col-xs-6">         
            <div class="panel panel-back noti-box" style="background-color: #f1f1f1;">
            <center><img src="images/complaint_icon.png" alt="Reports" style="width:120px; height:95px;"></center>
            <center><div class="text-box">
            <?php 
            $sql_users = mysqli_query($db, "SELECT * FROM complaints WHERE `Status`='Pending' ");
                $users = 0;
                while($DB_ROW = mysqli_fetch_array($sql_users)) {
                    $users++;
                }
                if($users > 1){
                    $user_lbl = "Complaints";
                }
                else{
                    $user_lbl = "Complaint";
                }
            ?>
                    <p class="main-text"><?php echo $users; ?> <?php echo $user_lbl; ?></p>
                    <p class="text-muted">Pending</p>
                </div></center>
             </div>
             </div>
            </a>

            <a href="announcements-admin.php">  
                    <div class="col-md-4 col-sm-6 col-xs-9">           
            <div class="panel panel-back noti-box" style="background-color: #f1f1f1;">
            <center><img src="images/announce-dash.png" alt="Announcements" style="width:105px;height:90px;"></center>
                <center><div class="text-box" >
                <?php 
                $sql_ann = mysqli_query($db, "SELECT * FROM announcements");
                    $ann_num = 0;
                    while($DB_ROW = mysqli_fetch_array($sql_ann)) {
                        $ann_num++;
                    }
                ?>
                    <p class="main-text"><?php echo $ann_num; ?> Total</p>
                    <p class="text-muted">Announcements</p>
                </div></center>
             </div>
             </div>
            </a>                                             
                        
        </div>
                 <!-- /. ROW  -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                Notification Management
                                <button class="btn btn-primary pull-right" onclick="document.getElementById('notifyAllModal').style.display='block'">
                                    <i class="fa fa-bell"></i> Send Notification to All Users
                                </button>
                            </div>
<div class="panel-body">
    <div class="table-responsive">
        <table class="table table-striped table-bordered table-hover">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Title</th>
                    <th>Message</th>
                    <th>Recipients</th>
                    <th>Date Sent</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php
                // Query to get distinct notifications grouped by title and message
                $notifications_query = "SELECT 
                    title, 
                    message, 
                    COUNT(*) as recipient_count,
                    GROUP_CONCAT(DISTINCT email) as recipients,
                    MAX(date_created) as last_sent,
                    MIN(status) as overall_status
                    FROM notifications 
                    GROUP BY title, message 
                    ORDER BY last_sent DESC";
                
                $notifications_result = mysqli_query($db, $notifications_query);
                
                $counter = 1;
                if(mysqli_num_rows($notifications_result) > 0) {
                    while($notification = mysqli_fetch_assoc($notifications_result)) {
                        $status_class = ($notification['overall_status'] == 'unread') ? 'status-unread' : 'status-read';
                        $recipient_count = $notification['recipient_count'];
                        $recipients_text = ($recipient_count > 1) ? 
                            $recipient_count." users" : 
                            htmlspecialchars($notification['recipients']);
                        
                        echo "<tr>";
                        echo "<td>".$counter."</td>";
                        echo "<td>".htmlspecialchars($notification['title'])."</td>";
                        echo "<td>".htmlspecialchars($notification['message'])."</td>";
                        echo "<td>".$recipients_text."</td>";
                        echo "<td>".$notification['last_sent']."</td>";
                        echo "<td class='".$status_class."'>".ucfirst($notification['overall_status'])."</td>";
                        echo "</tr>";
                        $counter++;
                    }
                } else {
                    echo "<tr><td colspan='6' class='text-center'>No notifications sent yet</td></tr>";
                }
                ?>
            </tbody>
        </table>
    </div>
</div>
                        </div>
                    </div>
                </div>
                          
    </div>
             <!-- /. PAGE INNER  -->
            </div>
         <!-- /. PAGE WRAPPER  -->
        </div>
     <!-- /. WRAPPER  -->
     
    <!-- Notification to All Modal -->
    <div id="notifyAllModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="document.getElementById('notifyAllModal').style.display='none'">&times;</span>
            <h3>Send Notification to All Users</h3>
            <form method="POST" action="">
                <div class="form-group">
                    <label for="notification_title">Title:</label>
                    <input type="text" class="form-control" id="notification_title" name="notification_title" required>
                </div>
                <div class="form-group">
                    <label for="notification_message">Message:</label>
                    <textarea class="form-control" id="notification_message" name="notification_message" required></textarea>
                </div>
                <div class="form-group">
                    <button type="submit" name="send_to_all" class="btn btn-primary">Send Notification</button>
                    <button type="button" class="btn btn-default" onclick="document.getElementById('notifyAllModal').style.display='none'">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- SCRIPTS -AT THE BOTOM TO REDUCE THE LOAD TIME-->
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<script type="text/javascript">
      var ctx = document.getElementById("chartjs_bar").getContext('2d');
                var myChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels:<?php echo json_encode($dept_off); ?>,
                        datasets: [{
                            backgroundColor: [
                               "#5969ff",
                                "#ff407b",
                                "#25d5f2",
                                "#ffc750",
                                "#2ec551",
                                "#7040fa",
                                "#ff004e"
                            ],
                            data:<?php echo json_encode($area); ?>,
                        }]
                    },
                    options: {
                           legend: {
                        display: false,
                        position: 'bottom',
 
                        labels: {
                            fontColor: '#71748d',
                            fontFamily: 'Circular Std Book',
                            fontSize: 14,
                        }
                    },
 
 
                }
                });
    </script>
    <!-- JQUERY SCRIPTS -->
    <script src="assets/js/jquery-1.10.2.js"></script>
      <!-- BOOTSTRAP SCRIPTS -->
    <script src="assets/js/bootstrap.min.js"></script>
    <!-- METISMENU SCRIPTS -->
    <script src="assets/js/jquery.metisMenu.js"></script>
     <!-- MORRIS CHART SCRIPTS -->
     <script src="assets/js/morris/raphael-2.1.0.min.js"></script>
    <script src="assets/js/morris/morris.js"></script>
      <!-- CUSTOM SCRIPTS -->
    <script src="assets/js/custom.js"></script>
    
        <script>
    // Get the modal
    var modal = document.getElementById("myModal");

    // Get the button that opens the modal
    var btn = document.getElementById("myBtn");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal 
    btn.onclick = function() {
    modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
    modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
    }
    </script>
   
</body>
</html>