<?php
// Recoded by Gh0Code
// Hargailah orang lain jika Anda ingin dihargai
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['edit'])) {
	                $post_poid = $_POST['poid'];
					$post_status = $_POST['status'];
					$post_start = $_POST['start_count'];
					$post_remains = $_POST['remains'];
					if ($post_status != "Pending" AND $post_status != "Processing" AND $post_status != "Error" AND $post_status != "Partial" AND $post_status != "Success") {
						$msg_type = "error";
						$msg_content = "<b>Gagal:</b> Input tidak sesuai.";
					} else {
						$update_order = mysqli_query($db, "UPDATE orders SET start_count = '$post_start', remains = '$post_remains', status = '$post_status' WHERE poid = '$post_poid'");
						if ($update_order == TRUE) {
							$msg_type = "success";
							$msg_content = "<b>Berhasil:</b> Pesanan berhasil diubah.<br /><b>Order ID:</b> $post_oid<br /><b>Status:</b> $post_status<br /><b>Start Count:</b> ".number_format($post_start,0,',','.')."<br /><b>Remains:</b> ".number_format($post_remains,0,',','.');
						} else {
							$msg_type = "error";
							$msg_content = "<b>Gagal:</b> Error system.";
						}
					}
				}


$current_date = date('Y-m-d'); // Hari ini
$data_tanggal = array();
$data_total = array();
for ($i = 29; $i >= 0; $i--) {
  $date = date('Y-m-d', strtotime("-$i days", strtotime($current_date)));
  $data_tanggal[] = date('d-m-Y', strtotime($date));
}

// Inisialisasi array total penjualan dengan nilai 0 pada awalnya untuk setiap status
$data_total = array(
  'Pending' => array_fill(0, count($data_tanggal), 0),
  'Processing' => array_fill(0, count($data_tanggal), 0),
  'Success' => array_fill(0, count($data_tanggal), 0),
  'Partial' => array_fill(0, count($data_tanggal), 0),
  'Error' => array_fill(0, count($data_tanggal), 0)
);

// Mendapatkan data penjualan untuk setiap status dalam 7 hari terakhir
$status_labels = array('Pending', 'Processing', 'Success', 'Partial', 'Error');
foreach ($status_labels as $status) {
  $query = "SELECT DATE(date) AS tanggal, COUNT(*) AS total FROM orders WHERE status='$status' AND date >= DATE(NOW()) - INTERVAL 30 DAY GROUP BY tanggal";
  $result = mysqli_query($db, $query);
  while ($data = mysqli_fetch_array($result)) {
    $tanggal_db = date('Y-m-d', strtotime($data['tanggal']));
    $index_tanggal = array_search(date('d-m-Y', strtotime($tanggal_db)), $data_tanggal);
    if ($index_tanggal !== false) {
      $data_total[$status][$index_tanggal] = $data['total'];
    }
  }
}

// Output data untuk masing-masing status
 $status_labels = array('Pending', 'Processing', 'Success', 'Partial', 'Error');
	include("../lib/header.php");
	// widget
	$check_worder = mysqli_query($db, "SELECT SUM(price) AS total FROM orders");
	$data_worder = mysqli_fetch_assoc($check_worder);
	$check_worder = mysqli_query($db, "SELECT * FROM orders");
	$count_worder = mysqli_num_rows($check_worder);
	
	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">
          <div class="col-xxl-7 col-md-7 box-col-7">
            <div class="appointment">
              <div class="card">
                <div class="col-xl-12">
                  <div id="chart">
                    <div id="total-chart"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
              <div class="col-xxl-12">
            <div class="card">
  <div class="card-body">
    <div class="input-group mb-3">
                           <input type="text" id="search-orders" class="form-control" placeholder="Search Orders">
                        </div>
    <div class="table-responsive">
      <table class="table table-hover" id="order-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-order">
        <!-- 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 = $("#order-table");
    const pagination = $("#pagination-order");
    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 and search input
    function updateTableData(page, searchQuery = '') {
      $.ajax({
        url: "get_orders_data.php",
        method: "GET",
        data: { page: page, recordsPerPage: recordsPerPage, search: searchQuery },
        dataType: "json",
        success: function(data) {
          // Clear existing table rows
          table.empty();

          // Add table header
          table.append("<thead><tr><th>Tanggal</th><th>PO ID</th><th>User</th><th>Service</th><th>Link</th><th>Quantity</th><th>Remains</th><th>Start Count</th><th>Price</th><th>Status</th><th>Providers</th><th>Refund</th><th>Action</th></tr></thead>");

          // Add table body with fetched data
          const tbody = $("<tbody></tbody>");
          $.each(data.orders, function(index, item) {
            const row = $("<tr class='border-bottom-success'></tr>");
            row.append("<td>" + item.date + "</td>");
            row.append("<td>" + item.poid + "</td>");
            row.append("<td>" + item.user + "</td>");
            row.append("<td>" + item.service + "</td>");
            row.append("<td>" + item.link + "</td>");
            row.append("<td>" + item.quantity + "</td>");
            row.append("<td>" + item.remains + "</td>");
            row.append("<td>" + item.start_count + "</td>");
            row.append("<td>" + formatCurrency(item.price) + "</td>"); // Format the price as currency
            if (item.status == 'Pending') {
            row.append("<td align='center'><span class='badge badge-warning'>"+item.status+"</span></td>");
          } else if (item.status == 'Processing') {
            row.append("<td align='center'><span class='badge badge-primary'>"+item.status+"</span></td>");
          } else if (item.status == 'Error') {
            row.append("<td align='center'><span class='badge badge-danger'>"+item.status+"</span></td>");
          } else if (item.status == 'Partial') {
            row.append("<td align='center'><span class='badge badge-danger'>"+item.status+"</span></td>");
          } else if (item.status == 'Success') {
            row.append("<td align='center'><span class='badge badge-success'>"+item.status+"</span></td>");
          } else {
            row.append("<td></td>"); // Handle other cases, if needed
          }
            row.append("<td>" + item.provider + "</td>");
            
            // Check the value of "refund" and display the appropriate badge
          if (item.refund === '0') {
            row.append("<td align='center'><span class='badge badge-danger'><i class='fa fa-times'></i></span></td>");
          } else if (item.refund === '1') {
            row.append("<td align='center'><span class='badge badge-success'><i class='fa fa-check'></i></span></td>");
          } else {
            row.append("<td></td>"); // Handle other cases, if needed
          }
            
            row.append("<td align='center'>" +
              "<a class='btn btn-xs btn-warning' data-bs-toggle='modal' data-bs-target='#editordernya" + item.poid + "'><i class='fa fa-edit'></i></a> " +
              "<div class='modal fade' id='editordernya" + item.poid + "' 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'>Order ID</label> <input type='text' class='form-control' value='" + item.poid + "' name='poid' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>User</label> <input type='text' class='form-control' name='user' placeholder='User' value='" + item.user + "' readonly> </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>Service</label> <input class='form-control' id='exampleFormControlInput1' type='text' name='service' value='" + item.service + "' readonly> </div> <div class='col-md-12'> <label class='form-label' for='exampleFormControlInput1'>Link</label> <input class='form-control' id='exampleFormControlInput1' type='text' name='link' value='" + item.link + "' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Quantity</label> <input type='text' class='form-control' name='quantity' placeholder='Quantity' value='" + item.quantity + "' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Remains</label> <input type='text' class='form-control' name='remains' placeholder='Remains' value='" + item.remains + "' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Start Count</label> <input type='text' class='form-control' name='start_count' placeholder='Start Count' value='" + item.start_count + "' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Price</label> <input type='text' class='form-control' name='price' placeholder='Price' value='" + item.price + "' readonly> </div> <div class='col-md-6'> <label class='form-label' for='validationCustom02'>Status</label> <select class='form-control' name='status'> <option value='"+item.status+"'>"+item.status+"</option> <option value='Pending'>Pending</option> <option value='Processing'>Processing</option><option value='Success'>Success</option> <option value='Partial'>Partial</option><option value='Error'>Error</option></select> </div> <div class='col-md-6'> <label class='form-label' for='exampleFormControlInput1'>Providers</label> <input class='form-control' id='exampleFormControlInput1' type='text' name='providers' value='" + item.provider + "' readonly> </div> <div class='col-md-12'> <button class='btn btn-secondary' type='button' data-bs-dismiss='modal'>Close</button> <button class='btn btn-primary' type='submit' name='edit'>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, $("#search-orders").val().trim());
      }
    }

    // Function to handle search input
    $("#search-orders").on("input", function() {
      const searchQuery = $(this).val().trim();
      currentPage = 1; // Reset to the first page when performing a new search
      updateTableData(currentPage, searchQuery);
    });

    // 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, $("#search-orders").val().trim());
      }
    });

    // Initial table data fetch for the first page
    updateTableData(currentPage);
  });

  // Function to format the number as currency (Rp)
  function formatCurrency(num) {
    return "Rp " + num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }
</script>
<?php
	include("../../lib/footer.php");
	}
} else {
	header("Location: ".$cfg_baseurl);
}
?>