<?php
$datetime = new DateTime( "now", new DateTimeZone( "Asia/Jakarta" ) );
session_start();
require("../../mainconfig.php");
$msg_type = "nothing";

if (isset($_SESSION['user'])) {
	$sess_username = $_SESSION['user']['username'];
	$check_user = mysqli_query($db, "SELECT * FROM users WHERE username = '$sess_username'");
	$data_user = mysqli_fetch_assoc($check_user);
	if (mysqli_num_rows($check_user) == 0) {
		header("Location: ".$cfg_baseurl."logout.php");
	} else if ($data_user['status'] == "Suspended") {
		header("Location: ".$cfg_baseurl."logout.php");
	} else if ($data_user['level'] != "Developers") {
		header("Location: ".$cfg_baseurl);
	} else {
		if (isset($_POST['add'])) {
			$post_content = $_POST['content'];

			if (empty($post_content)) {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Mohon mengisi semua input.";
			} else {
			    $date = $datetime->format( 'Y-m-d H:i:s' );
				$insert_news = mysqli_query($db, "INSERT INTO news (date, content) VALUES ('$date', '$post_content')");
				if ($insert_news == TRUE) {
					$msg_type = "success";
					$msg_content = "<b>Berhasil:</b> Berita berhasil ditambahkan.<br /><b>Konten:</b> $post_content<br /><b>Tanggal:</b> $date";
				} else {
					$msg_type = "error";
					$msg_content = "<b>Gagal:</b> Error system.";
				}
			}
		} else if (isset($_POST['edit'])) {
		            $post_id = $_POST['id'];
					$post_content = $_POST['content'];
					if (empty($post_content)) {
						$msg_type = "error";
						$msg_content = "<b>Gagal:</b> Mohon mengisi semua input.";
					} else {
						$update_news = mysqli_query($db, "UPDATE news SET content = '$post_content' WHERE id = '$post_id'");
						if ($update_news == TRUE) {
							$msg_type = "success";
							$msg_content = "<b>Berhasil:</b> Berita berhasil diubah.";
						} else {
							$msg_type = "error";
							$msg_content = "<b>Gagal:</b> Error system.";
						}
					}
				} else if (isset($_POST['delete'])) {
			$post_id = $_POST['id'];
			$checkdb_news = mysqli_query($db, "SELECT * FROM news WHERE id = '$post_id'");
			if (mysqli_num_rows($checkdb_news) == 0) {
				$msg_type = "error";
				$msg_content = "<b>Gagal:</b> Berita tidak ditemukan.";
			} else {
				$delete_news = mysqli_query($db, "DELETE FROM news WHERE id = '$post_id'");
				if ($delete_news == TRUE) {
					$msg_type = "success";
					$msg_content = "<b>Berhasil:</b> Berita deleted.";
				}
			}
		}

	include("../../lib/header.php");
?>
<div class="page-body"> 
<?php include('../../lib/partial/breadcrumb.php') ?>
   <!-- Container-fluid starts-->
   <div class="container-fluid">
            <div class="row justify-content-center">
                <?php 
											if ($msg_type == "success") {
											?>
											<div class="alert alert-success dark" role="alert">
                      <p><?php echo $msg_content; ?></p>
                    </div>
											<?php
											} else if ($msg_type == "error") {
											?>
											<div class="alert alert-secondary dark" role="alert">
                          <p><?php echo $msg_content; ?></p>
                        </div>
											<?php
											}
											?>
                <div class="col-xxl-3">
                    <div class="card">
                <button type="submit" class="btn btn-primary" data-bs-toggle='modal' data-bs-target='#tambahingfo'><i class="fa fa-plus"></i> Add News </button>
                <div class='modal fade' id='tambahingfo' tabindex='-1' role='dialog' aria-labelledby='exampleModalgetbootstrap' aria-hidden='true'>
  <div class='modal-dialog' role='document'>
  <div class='modal-content'>
    <div class='modal-toggle-wrapper social-profile text-start dark-sign-up'>
      <h3 class='modal-header justify-content-center border-0'>Add News</h3>
      <div class='modal-body'>
        <form class='row g-3' method='POST'>
          <div class='col-md-12'>
          <div class='col-md-12'>
            <label class="form-label" for="badgeDropdown" style="color: #808080;">Pilih Badge</label>
            <select class='form-select' id='badgeDropdown' onchange='updateBadge(this.value)'>
              <option value='' selected disabled>Pilih Badge</option>
              <option value='<span class="badge badge-info">LAYANAN REKOMENDASI</span>'>LAYANAN REKOMENDASI</option>
              <option value='<span class="badge badge-warning text-dark">UPDATE LAYANAN</span>'>UPDATE LAYANAN</option>
              <option value='<span class="badge badge-success">INFORMASI</span>'>INFORMASI</option>
              <option value='<span class="badge badge-primary">EVENT</span>'>EVENT</option>
              <option value='<span class="badge badge-danger">PENTING</span>'>PENTING</option>
              
              <option value='<span class="badge badge-primary">Primary</span>'>Primary</option>
              <option value='<span class="badge badge-secondary">Secondary</span>'>Secondary</option>
              <option value='<span class="badge badge-warning text-dark">Warning</span>'>Warning</option>
              <option value='<span class="badge badge-danger">Danger</span>'>Danger</option>
              <option value='<span class="badge badge-light text-dark">Light</span>'>Light</option>
              <option value='<span class="badge badge-dark tag-pills-sm-mb">Dark</span>'>Dark</option>
            </select>
          </div>
            <label class='form-label' for='exampleFormControlInput1'style="color: #808080;">Konten</label>
            <textarea class='form-control' id='exampleFormControlInput1' type='text' name="content" placeholder='isi beritanya apa gan'></textarea>
          </div>
          <div class='col-md-12'>
            <button class='btn btn-primary' type='submit' name="add">Submit Gan</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
  function updateBadge(selectedBadge) {
    // Mengambil elemen textarea
    var textareaContent = document.getElementById('exampleFormControlInput1');

    // Menetapkan nilai textarea dengan badge yang dipilih
    textareaContent.value = selectedBadge;
    
    // Menambahkan dua kali enter
    textareaContent.value += '\n\n';
  }
</script>

  
</div>
                </div>
            </div>
        
              <div class="col-xxl-12">
            <div class="card">
  <div class="card-body">
    <div class="table-responsive">
      <table class="table table-hover" id="news-table">
        <!-- Table data will be loaded dynamically using JavaScript -->
      </table>
    </div>
    <br>
    <div class="d-flex justify-content-center">
      <ul class="pagination justify-content-end mb-0" id="pagination-news">
        <!-- Pagination links will be loaded dynamically using JavaScript -->
      </ul>
    </div>
  </div>
</div>
          </div>
              </div>
   </div>
   <!-- Container-fluid Ends-->
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function() {
  const table = $("#news-table");
  const pagination = $("#pagination-news");
  const maxVisiblePages = 5; // Maximum number of visible pagination links

  // Constants to keep track of current page and records per page
  let currentPage = 1;
  const recordsPerPage = 10; // Number of records to show per page

  // Function to fetch and update table data based on the current page
  function updateTableData(page) {
    $.ajax({
      url: "get_news_data.php",
      method: "GET",
      data: { page: page, recordsPerPage: recordsPerPage },
      dataType: "json",
      success: function(data) {
        // Clear existing table rows
        table.empty();

        // Add table header
        table.append("<thead><tr><th>No.</th><th>Content</th><th>Date</th></tr></thead>");

        // Add table body with fetched data
        const tbody = $("<tbody></tbody>");
        $.each(data.news, function(index, item) {
          const row = $("<tr></tr>");
          row.append("<td>" + (index + 1) + "</td>");
          row.append("<td>" + nl2br(item.content) + "</td>");
          row.append("<td>" + item.date + "</td>");
          row.append("<td align='center'>" +
              "<a class='btn btn-xs btn-warning' data-bs-toggle='modal' data-bs-target='#editnews" + item.id + "'><i class='fa fa-edit'></i></a> " +
              "<div class='modal fade' id='editnews" + item.id + "' tabindex='-1' role='dialog' aria-labelledby='exampleModalgetbootstrap' aria-hidden='true'> <div class='modal-dialog' role='document'> <div class='modal-content'> <div class='modal-toggle-wrapper social-profile text-start dark-sign-up'> <h3 class='modal-header justify-content-center border-0'>Order Edit</h3> <div class='modal-body'> <form class='row g-3' method='POST'> <div class='col-md-6'> <label class='form-label' for='validationCustom01'>ID</label> <input type='text' class='form-control' value='" + item.id + "' name='id' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Date</label> <input type='text' class='form-control' name='date' placeholder='User' value='" + item.date + "' readonly> </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>Konten</label> <textarea class='form-control' id='exampleFormControlInput1' type='text' name='content'>" + item.content + "</textarea> </div>  <div class='col-md-12'> <button class='btn btn-primary' type='submit' name='edit'>Submit Gan</button> </div> </form> </div> </div> </div> </div> </div>" +
              "<a class='btn btn-xs btn-danger' data-bs-toggle='modal' data-bs-target='#deletenews" + item.id + "'><i class='fa fa-trash-o'></i></a> " +
              "<div class='modal fade' id='deletenews" + item.id + "' tabindex='-1' role='dialog' aria-labelledby='exampleModalgetbootstrap' aria-hidden='true'> <div class='modal-dialog' role='document'> <div class='modal-content'> <div class='modal-toggle-wrapper social-profile text-start dark-sign-up'> <h3 class='modal-header justify-content-center border-0'>Order Edit</h3> <div class='modal-body'> <form class='row g-3' method='POST'> <div class='col-md-6'> <label class='form-label' for='validationCustom01'>ID</label> <input type='text' class='form-control' value='" + item.id + "' name='id' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Date</label> <input type='text' class='form-control' name='date' placeholder='User' value='" + item.date + "' readonly> </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>Konten</label> <textarea class='form-control' id='exampleFormControlInput1' type='text' name='content'>" + item.content + "</textarea> </div>  <div class='col-md-12'> <button class='btn btn-primary' type='submit' name='delete'>Submit Gan</button> </div> </form> </div> </div> </div> </div> </div>" +
              "</td>");
          tbody.append(row);
        });
        table.append(tbody);

        // Update pagination links
        pagination.empty();
        const totalPages = data.totalPages;
        let startPage = 1;
        let endPage = totalPages;

        if (totalPages > maxVisiblePages) {
          const halfMaxVisiblePages = Math.floor(maxVisiblePages / 2);
          startPage = Math.max(currentPage - halfMaxVisiblePages, 1);
          endPage = startPage + maxVisiblePages - 1;

          if (endPage > totalPages) {
            endPage = totalPages;
            startPage = Math.max(endPage - maxVisiblePages + 1, 1);
          }
        }

        for (let i = startPage; i <= endPage; i++) {
          pagination.append(
            '<li class="page-item' + (i === currentPage ? ' active' : '') + '"><a class="page-link" href="#" data-page="' + i + '">' + i + '</a></li>'
          );
        }

        // Add navigation arrows for previous and next
        if (currentPage > 1) {
            pagination.prepend(
              '<li class="page-item' + (1 === currentPage ? ' disabled' : '') + '"><a class="page-link" href="#" data-page="1">First</a></li>'+
              '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage - 1) + '">&#171;</a></li>'
            );
          }

          if (currentPage < totalPages) {
            pagination.append(
              '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage + 1) + '">&#187;</a></li>'+
              '<li class="page-item' + (totalPages === currentPage ? ' disabled' : '') + '"><a class="page-link" href="#" data-page="' + totalPages + '">Last</a></li>'
            );
          }
      },
      error: function(xhr, status, error) {
        console.error("Error fetching data:", error);
      }
    });
  }

  // Function to handle page navigation click
  function handlePaginationClick(event) {
    event.preventDefault();
    const newPage = parseInt($(this).data("page"));
    if (newPage !== currentPage) {
      currentPage = newPage;
      updateTableData(currentPage);
    }
  }

  // Attach pagination click event for individual page numbers
  pagination.on("click", "li.page-item:not(.active) a.page-link", handlePaginationClick);

  // Attach click event for previous and next arrows
  pagination.on("click", "li.page-item a.page-link[data-page]", function(event) {
    event.preventDefault();
    const newPage = parseInt($(this).data("page"));
    if (newPage !== currentPage) {
      currentPage = newPage;
      updateTableData(currentPage);
    }
  });
    
    function nl2br(str) {
    return str.replace(/(?:\r\n|\r|\n)/g, "<br>");
  }
  
  // Initial table data fetch for the first page
  updateTableData(currentPage);
});
</script>
<?php
	include("../../lib/footer.php");
	}
} else {
	header("Location: ".$cfg_baseurl);
}
?>