<?php
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['status'] == "Waiting") {
		header("Location: ".$cfg_baseurl."logout.php");
	}

//////////////////////////HITUNG ORDERAN
// Query untuk menghitung total seluruh orderan user '$sess_username' sejak pertama kali membuat akun
$query_total_order_user = "SELECT COUNT(*) AS total_order FROM orders WHERE user='$sess_username'";
$result_total_order_user = mysqli_query($db, $query_total_order_user);
$data_total_order_user = mysqli_fetch_assoc($result_total_order_user)['total_order'];

// Query untuk menghitung total orderan user '$sess_username' berdasarkan status
$query_total_order_status = "SELECT status, COUNT(*) AS total_status FROM orders WHERE user='$sess_username' GROUP BY status";
$result_total_order_status = mysqli_query($db, $query_total_order_status);

// Inisialisasi array total orderan user untuk setiap status dengan nilai 0 pada awalnya
$data_total_order_status = array(
  'Pending' => 0,
  'Processing' => 0,
  'Success' => 0,
  'Error/Partial' => 0
);

// Menghitung total orderan untuk setiap status
while ($data = mysqli_fetch_assoc($result_total_order_status)) {
  $status = $data['status'];
  $total_status = $data['total_status'];

  // Jika status adalah 'Error' atau 'Partial', tambahkan total ke 'Error/Partial'
  if ($status === 'Error' || $status === 'Partial') {
    $status = 'Error/Partial';
  }

  $data_total_order_status[$status] = $total_status;
}
//////////////////////////HITUNG ORDERAN
    
    
//////////////////////////GRAFIK ORDERAN
    // Inisialisasi array tanggal dalam 7 hari terakhir (termasuk hari kosong)
$current_date = date('Y-m-d'); // Hari ini
$data_tanggal = array();
$data_total = array();
for ($i = 6; $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 user='$sess_username' AND status='$status' AND date >= DATE(NOW()) - INTERVAL 7 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');
// foreach ($status_labels as $status) {
//   echo "Status: $status<br>";
//   for ($i = 0; $i < count($data_tanggal); $i++) {
//     echo "Tanggal: " . $data_tanggal[$i] . " | Total Order: " . $data_total[$status][$i] . "<br>";
//   }
//   echo "<br>";
// }
//////////////////////////GRAFIK ORDERAN


	$count_users = mysqli_num_rows(mysqli_query($db, "SELECT * FROM users"));
} else {
  header("Location: ".$cfg_baseurl."pages/landing.html");
}

$ua = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('#Mozilla/4.05 [fr] (Win98; I)#',$ua) || preg_match('/Java1.1.4/si',$ua) || preg_match('/MS FrontPage Express/si',$ua) || preg_match('/HTTrack/si',$ua) || preg_match('/IDentity/si',$ua) || preg_match('/HyperBrowser/si',$ua) || preg_match('/Lynx/si',$ua)) 
{
header('Location:http://shafou.com');
die();
}

date_default_timezone_set('Asia/Jakarta');
$tanggal = date("l, d M Y");

include("lib/header.php");
if (isset($_SESSION['user'])) {
?>

    <!-- Popup Container -->
    <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModal" aria-hidden="true">
                      <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                          <div class="modal-header">
                            <h4 class="modal-title" id="myExtraLargeModal">Top 5 News</h4>
                          </div>
                          <div class="modal-body" style="max-height: 400px overflow: auto;">
                
														<?php
														$check_news = mysqli_query($db, "SELECT * FROM news ORDER BY id DESC LIMIT 5");
														$no = 1;
														while ($data_news = mysqli_fetch_assoc($check_news)) {
														?>
					  <div class="card shadow mb-0" style="border: 50px">
                   <div class="card-body">
                      <span class="float-right"><i class="fas fa-fw fa-calendar"></i><?php echo $data_news['date']; ?></span>
                      <div class="mt-2 mb-2">
                         <blockquote class="blockquote">
                            <p><?php echo nl2br($data_news['content']); ?>
                            </p>
                            </blockquote>
                            </div>
                   </div>
                </div>
                            <?php
														$no++;
														}
														?>
                <br>
                <button type="button" data-bs-dismiss="modal" id="close-btn" style="background-color: #4CAF50;color: white;padding: 10px 20px;border: none;border-radius: 5px;cursor: pointer;">Saya Sudah Membacanya</button>
            </div>
                        </div>
                      </div>
                    </div>
<div class="page-body">
  <div class="container-fluid">
    <div class="page-title">
      <div class="row">
        <div class="col-6">
          <h4> Dashboard</h4>
          <button class="btn btn-success" type="button" data-bs-toggle="modal" id="modal-trigger-btn" data-bs-target=".bd-example-modal-lg" style="display: none">Large Modal</button>
        </div>
        <div class="col-6">
          <ol class="breadcrumb">
            <li class="breadcrumb-item">
              <a href="/">
                <svg class="stroke-icon">
                  <use href="../assets/svg/icon-sprite.svg#stroke-home"></use>
                </svg>
              </a>
            </li>
            <li class="breadcrumb-item">Dashboard</li>
          </ol>
        </div>
      </div>
    </div>
  </div>
  <!-- Container-fluid starts-->
  <div class="container-fluid">
      <? if (empty($data_user['email']) || empty($data_user['nohp'])){ ?>
      <div class="alert alert-secondary dark" role="alert">
                          <p>Mohon melengkapi <a class="alert-link text-white" href="/pages/settings">EMAIL & NO. WHATSAPP</a> pada menu <u><a class="alert-link text-white" href="/pages/settings">AKUN</a></u> demi keamanan akun anda, dan mempermudah untuk melakukan reset password.</p>
                        </div>
                        <? } ?>
    <div class="alert alert-primary" role="alert">
                          <center><p>Silahkan Join Grup WhatsApp untuk mendapatkan informasi dan berita terupdate dari Kami!</p>
                          <p><b><i class="fa fa-angle-double-right"></i><i class="fa fa-angle-double-right"></i>
                          <a class="alert-link text-white" href="https://chat.whatsapp.com/GQDHUgyamHu4gwPa0OG5GV" target="blank"><u>LINK GRUP WHATSAPP</u></a>
                          <i class="fa fa-angle-double-left"></i><i class="fa fa-angle-double-left"></i>
                          </b></p></center>
                        </div>
                        
<div class="alert alert-info">
          
<marquee>
<?php
$qslider = mysqli_query($db, "SELECT * FROM orders ORDER BY id DESC LIMIT 5");
$possible_users = ["Jessi", "Amrullaha", "jokifollo", "kepoyaa", "jasaallso"]; // Daftar nama pengguna yang mungkin
$possible_products = ["TKF52 Tiktok Followers (10/500K) [NR]", "Instagram Followers Indonesia [2K] [LOW DROP] AUTO+BONUS [REFILL 7 HARI] [PERDAYS 2K] INSTANT MASUK ♻️🔥", "TIKTOK FOLLOWERS INDONESIA [1K] [NON DROP] [100/DAYS ]🔥♻️⚡", "IGL33 Instagram LQ Likes (10/400K) [NR]", "Instagram Followers Indonesia [2K] [LOW DROP] [REFILL 5 HARI] ♻️ ⚡🔥 ⭐"]; // Daftar produk yang mungkin

while($slider = mysqli_fetch_assoc($qslider)) {
	$slider_userstr = "-".strlen($slider['user']);
	$slider_usersensor = substr($slider['user'], $slider_userstr, -4);
	echo "<span style='margin-right: 30px;'><b>".$slider_usersensor."****</b> telah melakukan pembelian ".$slider['quantity']." ".$slider['service']."</span>";
}

// Generate and display random user
for ($i = 0; $i < 5; $i++) {
    $random_user = $possible_users[array_rand($possible_users)];
    $random_quantity = rand(100, 500);
    $random_product = $possible_products[array_rand($possible_products)];
    echo "<span style='margin-right: 30px;'><b>".$random_user."****</b> telah melakukan pembelian ".$random_quantity." ".$random_product."</span>";
}
?>
</marquee>

</div>


    <div class="row size-column">
      <div class="col-xxl-10 col-md-12 box-col-8 grid-ed-12">
        <div class="row">
          <div  class="col-sm-12 col-xl-5">
            <div class="row">
              <div class="col-sm-12">
                <div class="card o-hidden">
                  <div class="card-body balance-widget">
                    <span class="f-w-500 f-light">Total Saldo</span>
                    <h4 class="mb-3 mt-1 f-w-500 mb-0 f-22">Rp <? echo number_format($data_user['balance'],0,',','.'); ?> <span class="f-light f-14 f-w-400 ms-1"></span>
                    </h4>
                    <a class="purchase-btn btn btn-primary btn-hover-effect f-w-500" href="/pages/history_balance">Riwayat Saldo</a>
                    <div class="mobile-right-img">
                      <img class="left-mobile-img" src="../assets/images/dashboard-2/widget-img.png" alt="">
                      <img class="mobile-img" src="../assets/images/dashboard-2/mobile.gif" alt="mobile with coin">
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-6">
                <div class="card small-widget">
                  <div class="card-body warning">
                    <span class="f-light">Orders Pending</span>
                    <div class="d-flex align-items-end gap-1">
                      <h4> <?= $data_total_order_status['Pending'] ?> </h4>
                    </div>
                    <div class="bg-gradient">
                      <svg class="stroke-icon svg-fill">
                        <use href="../assets/svg/icon-sprite.svg#cart"></use>
                      </svg>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-6">
                <div class="card small-widget">
                  <div class="card-body primary">
                    <span class="f-light">Orders Procesing</span>
                    <div class="d-flex align-items-end gap-1">
                      <h4> <?= $data_total_order_status['Processing'] ?> </h4>
                    </div>
                    <div class="bg-gradient">
                      <svg class="stroke-icon svg-fill">
                        <use href="../assets/svg/icon-sprite.svg#stroke-to-do"></use>
                      </svg>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-6">
                <div class="card small-widget">
                  <div class="card-body success">
                    <span class="f-light">Orders Success</span>
                    <div class="d-flex align-items-end gap-1">
                      <h4> <?= $data_total_order_status['Success'] ?> </h4>
                    </div>
                    <div class="bg-gradient">
                      <svg class="stroke-icon svg-fill">
                        <use href="../assets/svg/icon-sprite.svg#new-order"></use>
                      </svg>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-6">
                <div class="card small-widget">
                  <div class="card-body secondary">
                    <span class="f-light">Orders Error/Partial</span>
                    <div class="d-flex align-items-end gap-1">
                      <h4> <?= $data_total_order_status['Error/Partial'] ?> </h4>
                    </div>
                    <div class="bg-gradient">
                      <svg class="stroke-icon svg-fill">
                        <use href="../assets/svg/icon-sprite.svg#return-box"></use>
                      </svg>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col-sm-12 col-xl-7">
            <div class="appointment">
              <div class="card">
                <div class="col-xl-12">
                  <div id="chart">
                    <div id="timeline-chart"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xxl-12">
            <div class="card">
              <div class="card-body">
                <h4 class="card-title">Berita</h4>
                <div class="table-responsive">
                  <table class="table table-hover" id="ingfo-table">
                    <!-- Tabel data akan dimuat secara dinamis menggunakan JavaScript -->
                  </table>
                </div>
                <br>
                <div class="d-flex justify-content-center">
                  <ul class="pagination" id="pagination-ingfo">
                    <!-- Navigasi halaman akan dimuat secara dinamis menggunakan JavaScript -->
                  </ul>
                </div>
              </div>
            </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.addEventListener('DOMContentLoaded', function () {
    // Check if the user has clicked the close button in the last 24 hours
    var lastCloseTime = localStorage.getItem('lastCloseTime');
    if (!lastCloseTime || Date.now() - lastCloseTime > 24 * 60 * 60 * 1000) {
      // If the user hasn't clicked the close button in the last 24 hours, trigger the modal
      document.getElementById('modal-trigger-btn').click();
    }

    // Add click event listener to the close button
    document.getElementById('close-btn').addEventListener('click', function () {
      // Set the current time in local storage when the close button is clicked
      localStorage.setItem('lastCloseTime', Date.now());
    });
  });
</script>
<script>
  $(document).ready(function() {
    const table = $("#ingfo-table");
    const pagination = $("#pagination-ingfo");
    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 = 5; // 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>Date</th><th>Content</th></tr></thead>");

          // Add table body with fetched data
          const tbody = $("<tbody></tbody>");
          $.each(data.news, function(index, item) {
            const row = $("<tr></tr>");

            // Split the datetime into date and time parts
            const dateTimeParts = item.date.split(" ");
            const datePart = dateTimeParts[0];
            const timePart = dateTimeParts[1];

            // Modify the date cell to include the vertical-align property
            const dateCell = $("<td style='vertical-align: top;'></td>");
            dateCell.append("<h10>" + datePart + "<br>" + timePart + "</h10>");
            row.append(dateCell);

            row.append("<td>" + nl2br(item.content) + "</td>"); // Use nl2br here
            tbody.append(row);
          });
          table.append(tbody);

          // Update pagination links
          pagination.empty();
          const totalPages = Math.ceil(data.totalPages / recordsPerPage);
          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);
            }
          }

          // Add "First Page" link
          //pagination.append('<li class="page-item' + (1 === currentPage ? ' disabled' : '') + '"><a class="page-link" href="#" data-page="1">First</a></li>');

          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 "Last Page" link
          //pagination.append('<li class="page-item' + (totalPages === currentPage ? ' disabled' : '') + '"><a class="page-link" href="#" data-page="' + totalPages + '">Last</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 convert newlines to <br> tags
    function nl2br(str) {
      return str.replace(/(?:\r\n|\r|\n)/g, "<br>");
    }

    // 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);
      }
    });

    // Initial table data fetch for the first page
    updateTableData(currentPage);
  });
</script>
<?php
}
include("lib/footer.php");
?>
