<?php session_start(); ?>
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title id="shopname"></title>
  <link rel="shortcut icon" type="image/png" href="./assets/images/logos/favicon.png" />
  <link rel="stylesheet" href="./assets/css/styles.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" crossorigin="anonymous" />
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

</head>

<body>
  <!--  Body Wrapper -->
  <div class="page-wrapper" id="main-wrapper" data-layout="vertical" data-navbarbg="skin6" data-sidebartype="full"
    data-sidebar-position="fixed" data-header-position="fixed">
    <!-- Sidebar Start -->
    <aside class="left-sidebar">
      <!-- Sidebar scroll-->
      <div>
        <div class="brand-logo d-flex align-items-center justify-content-between">
          <a href="./index.html" class="text-nowrap logo-img">
            <img src="./assets/images/logos/dark-logo.svg" width="180" alt="" />
          </a>
          <div class="close-btn d-xl-none d-block sidebartoggler cursor-pointer" id="sidebarCollapse">
            <i class="ti ti-x fs-8"></i>
          </div>
        </div>
        <!-- Sidebar navigation-->
        <nav class="sidebar-nav scroll-sidebar" data-simplebar="">
          <ul id="sidebarnav">
            <li class="nav-small-cap">
              <i class="ti ti-dots nav-small-cap-icon fs-4"></i>
              <span class="hide-menu">Home</span>
            </li>
            <li class="sidebar-item">
              <a class="sidebar-link" href="./index.php" aria-expanded="false">
                <span>
                  <i class="ti ti-layout-dashboard"></i>
                </span>
                <span class="hide-menu">Dashboard</span>
              </a>
            </li>
            <li class="nav-small-cap">
            <span>
           <i class="fa-solid fa-briefcase  fa-2x"></i></span>
              <span class="hide-menu"> Accounting</span>
            </li>
            <li class="sidebar-item">
              <a class="sidebar-link" href="./overall.php" aria-expanded="false">
                <span>
                  <i class="ti ti-article"></i>
                </span>
                <span class="hide-menu">Overall  Reports</span>
              </a>
            </li>
            <li class="sidebar-item">
              <a class="sidebar-link" href="balancesheet.php" aria-expanded="false">
                <span>
                  <i class="fa-regular fa-file fa-2x"></i>
                </span>
                <span class="hide-menu">Balance Sheet</span>
              </a>
            </li>
            <li class="sidebar-item">
              <a class="sidebar-link" href="income.php" aria-expanded="false">
                <span>
                 <i class="fa-solid fa-calculator fa-2x"></i>
                </span>
                <span class="hide-menu">Income Statement</span>
              </a>
            </li>
            <li class="sidebar-item">
              <a class="sidebar-link" href="gledger.php" aria-expanded="false">
                <span>
                  <i class="fa-solid fa-book fa-2x"></i>
                </span>
                <span class="hide-menu">General Ledger</span>
              </a>
            </li>
             <li class="sidebar-item">
              <a class="sidebar-link" href="" aria-expanded="false">
                <span>
                  <i class="fa-solid fa-chart-pie fa-2x"></i>
                </span>
                <span class="hide-menu">Budgeting</span>
              </a>
            </li>
          
          </ul>
          
        </nav>
        <!-- End Sidebar navigation -->
      </div>
      <!-- End Sidebar scroll-->
    </aside>
    <!--  Sidebar End -->
    <!--  Main wrapper -->
    <div class="body-wrapper">
      <!--  Header Start -->
      <header class="app-header">
        <nav class="navbar navbar-expand-lg navbar-light">
          <ul class="navbar-nav">
            <li class="nav-item d-block d-xl-none">
              <a class="nav-link sidebartoggler nav-icon-hover" id="headerCollapse" href="javascript:void(0)">
                <i class="ti ti-menu-2"></i>
              </a>
            </li>
            <li class="nav-item">
              <a class="nav-link nav-icon-hover" href="javascript:void(0)">
                <i class="ti ti-bell-ringing"></i>
                <div class="notification bg-primary rounded-circle"></div>
              </a>
            </li>
          </ul>
          <div class="navbar-collapse justify-content-end px-0" id="navbarNav">
            <ul class="navbar-nav flex-row ms-auto align-items-center justify-content-end">
            
              <li class="nav-item dropdown">
                <a class="nav-link nav-icon-hover" href="javascript:void(0)" id="drop2" data-bs-toggle="dropdown"
                  aria-expanded="false">
                  <img src="./assets/images/profile/user-1.jpg" alt="" width="35" height="35" class="rounded-circle">
                </a>
                <div class="dropdown-menu dropdown-menu-end dropdown-menu-animate-up" aria-labelledby="drop2">
                  <div class="message-body">
                                       
                    <a href="./logout.php" class="btn btn-outline-primary mx-3 mt-2 d-block">Logout</a>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </nav>
      </header>
      <!--  Header End -->
      <div class="container-fluid">
        <!--  Row 1 -->
         <div class="row">
            <div class="col-lg-8 col-sm-8 d-flex align-items-stretch">
              <div class="card w-100 bg-primary-subtle overflow-hidden shadow-none">
                <div class="card-body position-relative">
                  <div class="row">
                    <div class="col-sm-7">
                      <div class="d-flex align-items-center mb-7">
                        <div class="rounded-circle overflow-hidden me-6">
                          <img src="./assets/images/profile/user-1.jpg" alt="" width="40" height="40">
                        </div>
                        <h5 class="fw-semibold mb-0 fs-5">Welcome back <?php echo $_SESSION['user'] ?>!</h5>
                      </div>
                      <div class="d-flex align-items-center">
                        <div class="border-end pe-4 border-muted border-opacity-10">
                          <h3 class="mb-1 fw-semibold fs-8 d-flex align-content-center">Ksh: <span id="daily-sales"></span><i
                              class="ti ti-arrow-up-right fs-5 lh-base text-success"></i></h3>
                          <p class="mb-0 text-dark">Today’s Sales</p>
                        </div>
                        
                      </div>
                    </div>
                    <div class="col-sm-5">
                      <div class="welcome-bg-img mb-n7 text-end">
                        <img src="./assets/images/backgrounds/welcome-bg.svg" alt="" class="img-fluid">
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-sm-4 col-lg-4  d-flex align-items-stretch">
              <div class="card w-100">
                <div class="card-body p-4">
                  <h4 class="fw-semibold"><span id="daily-expense"></span></h4>
                  <p class="mb-2 fs-3">Daily Overall Expense</p>
                  <div id="expense"></div>
                </div>
              </div>
            </div>
        </div>
            <div class="row">
          <div class="col-lg-8 d-flex align-items-strech">
            <div class="card w-100">
              <div class="card-body">
                <div class="d-sm-flex d-block align-items-center justify-content-between mb-9">
                  <div class="mb-3 mb-sm-0">
                    <h5 class="card-title fw-semibold">Sales Overview</h5>
                  </div>
                  <div>
                    <select class="form-select">
                      
                    </select>
                  </div>
                </div>
                <div id="chartz"></div>
              </div>
            </div>
          </div>
          <div class="col-lg-4">
            <div class="row">
            
              <div class="col-lg-12">
                <!-- Monthly Earnings -->
               <div class="card w-100">
                <div class="card-body">
                  <h5 class="card-title fw-semibold">Payment Gateways</h5>
                  <p class="card-subtitle mb-7">Weekely Totals</p>
                  <div class="position-relative">
                    <div class="d-flex align-items-center justify-content-between mb-4">
                      <div class="d-flex">
                        <div
                          class="p-8 bg-primary-subtle rounded-2 d-flex align-items-center justify-content-center me-6">
                          <img src="./assets/images/svgs/icon-paypal2.svg" alt="" class="img-fluid" width="24"
                            height="24">
                        </div>
                        <div>
                          <h6 class="mb-1 fs-4 fw-semibold">Paybill/Till</h6>
                        </div>
                      </div>
                      <h6 class="mb-0 fw-semibold"><span id="till"></span></h6>
                    </div>
                    <div class="d-flex align-items-center justify-content-between mb-4">
                      <div class="d-flex">
                        <div
                          class="p-8 bg-success-subtle rounded-2 d-flex align-items-center justify-content-center me-6">
                          <img src="./assets/images/svgs/icon-wallet.svg" alt="" class="img-fluid" width="24"
                            height="24">
                        </div>
                        <div>
                          <h6 class="mb-1 fs-4 fw-semibold">Cash</h6>
                        </div>
                      </div>
                      <h6 class="mb-0 fw-semibold text-muted"><span id="cash"></span></h6>
                    </div>
                    <div class="d-flex align-items-center justify-content-between mb-4">
                      <div class="d-flex">
                        <div
                          class="p-8 bg-warning-subtle rounded-2 d-flex align-items-center justify-content-center me-6">
                          <img src="./assets/images/svgs/icon-credit-card.svg" alt="" class="img-fluid" width="24"
                            height="24">
                        </div>
                        <div>
                          <h6 class="mb-1 fs-4 fw-semibold">Merchant</h6>
                        </div>
                      </div>
                      <h6 class="mb-0 fw-semibold"><span id="merchant"></span></h6>
                    </div>
                   </div>
                  <button class="btn btn-outline-primary w-100">View all transactions</button>
                </div>
              </div>
              </div>
            </div>
          </div>
        </div>
           <div class="row">
             <div class="col-md-6 col-lg-4  d-flex align-items-stretch">
              <div class="card w-100">
                <div class="card-body">
                  <div class="d-sm-flex d-block align-items-center justify-content-between mb-3">
                    <div class="mb-3 mb-sm-0">
                      <h5 class="card-title fw-semibold">Product Performances</h5>
                      <p class="card-subtitle">Top 5 selling product current month</p>
                    </div>
                    <div>
                      <select class="form-select fw-semibold">
                        <option value="1">March 2024</option>
                        <option value="2">April 2024</option>
                        <option value="3">May 2024</option>
                        <option value="4">June 2024</option>
                      </select>
                    </div>
                  </div>
                  <div class="table-responsive">
                  <table id="topSellingTable" class="table align-middle text-nowrap mb-0">
   <thead>
      <tr class="text-muted fw-semibold">
         <th scope="col" class="ps-0">Product Name</th>
         <th scope="col">Quantity</th>
         <th scope="col">Progress</th>
         <th scope="col">Budget</th>
      </tr>
   </thead>
   <tbody class="border-top"></tbody>
</table>

                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-6 col-lg-4 d-flex align-items-stretch">
              <div class="card w-100">
                <div class="card-body">
                  <h5 class="card-title fw-semibold">Sales Overview</h5>
                  <p class="card-subtitle mb-2">Every Month</p>
                  
                  <div id="sales-overview" class="mb-4"></div>
                  
                  <div class="d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-center">
                      <div class="bg-primary-subtle text-primary rounded-2 me-8 p-8 d-flex align-items-center justify-content-center">
                        <i class="ti ti-grid-dots fs-6"></i>
                      </div>
                      <div>
                        <h6 class="fw-semibold text-dark fs-4 mb-0">Sales  </h6>
                        <p class="fs-3 mb-0 fw-normal"><span class="sal"></span></p>
                      </div>
                    </div>
                    <div class="d-flex align-items-center">
                      <div
                        class="bg-secondary-subtle text-secondary rounded-2 me-8 p-8 d-flex align-items-center justify-content-center">
                        <i class="ti ti-grid-dots fs-6"></i>
                      </div>
                      <div>
                        <h6 class="fw-semibold text-dark fs-4 mb-0">Expense
</h6>
                        <p class="fs-3 mb-0 fw-normal"><span class="exp"></span></p>
                      </div>
                    </div>
                    
                  </div>
                  <div class="mb-4"></div>
                   <div class="d-flex align-items-center justify-content-between">
                     <div class="d-flex align-items-center  justify-content-between">
                      <div
                        class="bg-secondary-subtle text-warning rounded-2 me-8 p-8 d-flex align-items-center justify-content-center">
                        <i class="ti ti-grid-dots fs-6"></i>
                      </div>
                      <div>
                        <h6 class="fw-semibold text-dark fs-4 mb-0">   Profit 
                        </h6>
                        <p class="fs-3 mb-0 fw-normal"><span id="prof"></span></p>
                      </div>
                    </div>
                    </div>
                </div>
              </div>
            </div>
            <div class="col-lg-4">
              <div class="row">
                <div class="col-sm-6 d-flex align-items-stretch">
                  <div class="card w-100">
                    <div class="card-body">
                      <div class="p-2 bg-primary-subtle rounded-2 d-inline-block mb-3">
                        <img src="./assets/images/svgs/icon-cart.svg" alt="" class="img-fluid" width="24" height="24">
                      </div>
                      <div id="sales-two" class="mb-3"></div>
                      <h4 class="mb-1 fw-semibold d-flex align-content-center">Sales<i
                          class="ti ti-arrow-up-right fs-5 text-success"></i></h4>
                      <p class="mb-0"><span class="sal"></span></p>
                    </div>
                  </div>
                </div>
                <div class="col-sm-6 d-flex align-items-stretch">
                  <div class="card w-100">
                    <div class="card-body">
                      <div class="p-2 bg-info-subtle rounded-2 d-inline-block mb-3">
                        <img src="./assets/images/svgs/icon-bar.svg" alt="" class="img-fluid" width="24" height="24">
                      </div>
                      <div id="growths" class="mb-3"></div>
                      <h4 class="mb-1 fw-semibold d-flex align-content-center">
        <span id="percentage"></span>
        <i class="ti fs-5" id="arrowIcon"></i>
    </h4>
                      <p class="mb-0">Growth</p>
                    </div>
                  </div>
                </div>
              </div>
              <div class="card">
                <div class="card-body">
                  <div class="row alig n-items-start">
                    <div class="col-8">
                      <h5 class="card-title mb-9 fw-semibold"> Monthly Earnings </h5>
                      <div class="d-flex align-items-center mb-3">
                        <h4 class="fw-semibold mb-0 me-8">$6,820</h4>
                        <div class="d-flex align-items-center">
                          <span
                            class="me-2 rounded-circle bg-success-subtle text-success round-20 d-flex align-items-center justify-content-center">
                            <i class="ti ti-arrow-up-left"></i>
                          </span>
                          <p class="text-dark me-1 fs-3 mb-0">+9%</p>
                        </div>
                      </div>
                    </div>
                    <div class="col-4">
                      <div class="d-flex justify-content-end">
                        <div class="p-2 bg-primary-subtle rounded-2 d-inline-block">
                          <img src="./assets/images/svgs/icon-master-card-2.svg" alt="" class="img-fluid" width="24"
                            height="24">
                        </div>
                      </div>
                    </div>
                  </div>
                  <div id="monthly-earning"></div>
                </div>
              </div>
            </div>
         <div class="col-lg-8 col-md-6 d-flex align-items-stretch">
            <div class="card w-100">
              <div class="card-body p-4">
                <h5 class="card-title fw-semibold mb-4">Recent Transactions</h5>
                <div class="table-responsive">
       <table class="table text-nowrap mb-0 align-middle" id="vendorTable">
        <thead class="text-dark fs-4">
            <tr>
                <th class="border-bottom-0">
                    <h6 class="fw-semibold mb-0">Vendor Name</h6>
                </th>
                <th class="border-bottom-0">
                    <h6 class="fw-semibold mb-0">Company</h6>
                </th>
                <th class="border-bottom-0">
                    <h6 class="fw-semibold mb-0">Debt Amount</h6>
                </th>
                <th class="border-bottom-0">
                    <h6 class="fw-semibold mb-0">Phone Number</h6>
                </th>
            </tr>
        </thead>
        <tbody>
            <!-- Data will be dynamically inserted here -->
        </tbody>
    </table>
                </div>
              </div>
            </div>
          </div>
            <div class="col-md-6 col-lg-4 d-flex align-items-stretch">
              <div class="card w-100">
                <div class="card-body">
                  <div>
                    <h5 class="card-title fw-semibold">Yearly Sales</h5>
                    <p class="card-subtitle mb-0">Every month</p>
                    <div id="salary" class="mb-7 pb-8"></div>
                    <div class="d-flex align-items-center justify-content-between">
                      <div class="d-flex align-items-center">
                        <div
                          class="bg-primary-subtle text-primary rounded-2 me-8 p-8 d-flex align-items-center justify-content-center">
                          <i class="ti ti-grid-dots fs-6"></i>
                        </div>
                        <div>
                          <p class="fs-3 mb-0 fw-normal"><span id="totalExpenses"></span></p>
                          <h6 class="fw-semibold text-dark fs-4 mb-0">Total Sales</h6>
                        </div>
                      </div>
                      <div class="d-flex align-items-center">
                        <div class="bg-light-subtle text-muted rounded-2 me-8 p-8 d-flex align-items-center justify-content-center">
                          <i class="ti ti-grid-dots fs-6"></i>
                        </div>
                        <div>
                          <p class="fs-3 mb-0 fw-normal"><span id="totalSales"></span></p>
                          <h6 class="fw-semibold text-dark fs-4 mb-0">Total Expenses</h6>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
        </div>  
          
        <div class="py-6 px-6 text-center">
          <p class="mb-0 fs-4">Design and Developed by <a href="" target="_blank" class="pe-1 text-primary text-decoration-underline">Kakashi Tech Solutions </a></p>
        </div>
      </div>
    </div>
  </div>
 <script src="./assets/libs/jquery/dist/jquery.min.js"></script>
<script src="./assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="./assets/js/sidebarmenu.js"></script>
<script src="./assets/js/app.min.js"></script>
<script src="./assets/libs/apexcharts/dist/apexcharts.min.js"></script>
<script src="./assets/libs/simplebar/dist/simplebar.min.js"></script>
<script src="./assets/js/dashboard.js"></script>
<script src="./assets/js/app.dark.init.js"></script>
   <script src="./assets/js/dashboards/dashboard2.js"></script>

   <script>
     $(document).ready(function () {
            // Function to get total sales
            function getTotalSales() {
                $.ajax({
                    url: './assets/accounting/dailysales.kts.php', // Your server-side script
                    method: 'GET',
                    data: { action: 'getTotalSales' }, // Add any additional parameters if needed
                    dataType: 'json',
                    success: function (response) {
                        // Update the span with the total sales
                        $('#daily-sales').text(response.totalSales);
                    },
                    error: function (xhr, status, error) {
                        console.error(xhr.responseText);
                    }
                });
            }

            // Call the function on document ready
            getTotalSales();
 });

$(document).ready(function () {
    // Fetch data using AJAX
    $.ajax({
      url: './assets/accounting/dailyexpense.kts.php',
      type: 'GET',
      dataType: 'json',
      success: function(response) {
        // Display the total in the span
        $('#daily-expense').text(response.totalDailyExpense);
      },
      error: function(xhr, status, error) {
        console.error(xhr.responseText);
      }
    });
   
   
  });   
    </script>
    
<script>
    $(document).ready(function () {
        // Chart configuration
        var chartOptions = {
            series: [
                { name: 'Sales', data: [] },
                { name: 'Expenses', data: [] },
            ],
            chart: {
                type: 'bar',
                height: 345,
                offsetX: -15,
                toolbar: { show: true },
                foreColor: "#adb0bb",
                fontFamily: 'inherit',
                sparkline: { enabled: false },
            },
            colors: ["#5D87FF", "#49BEFF"],
            plotOptions: {
                bar: {
                    horizontal: false,
                    columnWidth: "15%",
                    borderRadius: [6],
                    borderRadiusApplication: 'end',
                    borderRadiusWhenStacked: 'all',
                },
            },
            markers: { size: 0 },
            dataLabels: {
                enabled: false,
            },
            legend: {
                show: false,
            },
            grid: {
                borderColor: "rgba(0,0,0,0.1)",
                strokeDashArray: 3,
                xaxis: {
                    lines: {
                        show: false,
                    },
                },
            },
            xaxis: {
                type: "category",
                categories: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
                labels: {
                    style: { cssClass: "grey--text lighten-2--text fill-color" },
                },
            },
            yaxis: {
                show: true,
                min: 0,
                tickAmount: 4,
                labels: {
                    style: {
                        cssClass: "grey--text lighten-2--text fill-color",
                    },
                },
            },
            stroke: {
                show: true,
                width: 3,
                lineCap: "butt",
                colors: ["transparent"],
            },
            tooltip: { theme: "light" },
            responsive: [
                {
                    breakpoint: 600,
                    options: {
                        plotOptions: {
                            bar: {
                                borderRadius: 3,
                            },
                        },
                    },
                },
            ],
        };

        // Create the chart using ApexCharts
        var chart = new ApexCharts(document.getElementById("chartz"), chartOptions);
         chart.render();
        // Fetch data when the page is loaded
        $.ajax({
            url: './assets/accounting/weeklysales.kts.php',
            type: 'GET',
            data: { action: 'getWeeklySalesExpenses' },
            dataType: 'json',
            success: function (response) {
                // Log the response to the console
                console.log(response);

                // Check if data is present in the response
                if (response && response.dailySales && response.dailyExpenses) {
                    // Convert dailySales to numbers
                    response.dailySales = response.dailySales.map(Number);

                    // Update the chart data with the fetched data
                    chart.updateSeries([
                        { name: 'Sales', data: response.dailySales },
                        { name: 'Expenses', data: response.dailyExpenses },
                    ]);

                   
                } else {
                    console.error('Invalid or missing data in the response:', response);
                }
            },
            error: function (xhr, status, error) {
                // Log the error to the console
                console.error('AJAX Error:', xhr.responseText);
            }
        });
    });
</script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Fetch data from the server
        fetch('./assets/accounting/get_paymentdata.kts.php')
            .then(response => response.json())
            .then(data => {
                // Check if data is empty, display 0 in each span
                if (data.length === 0) {
                    updateSpanContent('till', 0);
                    updateSpanContent('cash', 0);
                    updateSpanContent('merchant', 0);
                } else {
                    // Iterate through the data and update the content of the spans
                    data.forEach(entry => {
                        updateSpanContent(entry.payment_method, entry.total_amount);
                    });
                }
            })
            .catch(error => console.error('Error fetching data:', error));
    });

    function updateSpanContent(paymentMethod, totalAmount) {
        // Format the total amount with comma separation for thousands
        const formattedAmount = totalAmount !== null
            ? `${parseFloat(totalAmount.replace(',', '')).toLocaleString('en-US', { maximumFractionDigits: 2 })}`
            : '$0.00';

        document.getElementById(paymentMethod).innerText = formattedAmount;
    }
</script>

<script>
  
document.addEventListener('DOMContentLoaded', function () {
   // Fetch data from the server
   fetch('./assets/accounting/top_sellingitem.kts.php')
      .then(response => response.json())
      .then(data => {
         // Iterate through the data and update the table
         const tableBody = document.querySelector('#topSellingTable tbody');
         data.forEach(entry => {
            const row = document.createElement('tr');
            row.innerHTML = `
               <td class="ps-0 border-bottom-0">
                  <div class="d-flex align-items-center">
                     <div>
                        <h6 class="fw-semibold mb-1">${entry.productName}</h6>
                     </div>
                  </div>
               </td>
               <td class="border-bottom-0">
                  <p class="mb-0 fs-3 text-dark">${entry.quantity}</p>
               </td>
               <td class="border-bottom-0">
                  <span class="badge fw-semibold py-1 w-85 bg-danger-subtle text-danger">${entry.progress}%</span>
               </td>
               <td class="border-bottom-0">
                  <p class="fs-3 text-dark mb-0">${entry.budget}</p>
               </td>`;
            tableBody.appendChild(row);
         });
      })
      .catch(error => console.error('Error fetching data:', error));
});

</script>
<script>
// Fetch data from the server
fetch('./assets/accounting/monthlyprofit.kts.php?action=getMonthlyData')
    .then(response => response.json())
    .then(data => {
        // Extract data from the JSON response
        var monthlySales = data.monthlySales;
        var monthlyExpenses = data.monthlyExpenses;
        var monthlyProfit = data.monthlyProfit;

        // Chart options
        var options = {
            color: ["#ffdb58", "#5f5f5f", "#20b2aa"],
            series: [monthlySales, monthlyExpenses, monthlyProfit],
            labels: ["Sales", "Expenses", "Profit"],
            chart: {
                type: "donut",
                fontFamily: "Plus Jakarta Sans', sans-serif",
                foreColor: "#adb0bb",
            },
            plotOptions: {
                pie: {
                    donut: {
                        size: '88%',
                        background: 'transparent',
                        labels: {
                            show: true,
                            name: {
                                show: true,
                                offsetY: 7,
                            },
                            value: {
                                show: false,
                            },
                            total: {
                                show: true,
                                color: '#7C8FAC',
                                fontSize: '20px',
                                fontWeight: "600",
                                label: '' + monthlyProfit.toFixed(2),
                            },
                        },
                    },
                },
            },
            stroke: {
                show: false,
            },
            dataLabels: {
                enabled: false,
            },
            legend: {
                show: false,
            },
            colors: ["#ffdb58", "#3498db", "#001f3f"],
            tooltip: {
                theme: "dark",
                fillSeriesColor: false,
            },
        };

        // Create or update the chart
        var chart = new ApexCharts(document.querySelector("#sales-overview"), options);
        chart.render();

        // Display data in span divs
        $('.sal').text(': ' + monthlySales.toFixed(2));
        $('.exp').text(': ' + monthlyExpenses.toFixed(2));
        $('#prof').text(': ' + monthlyProfit.toFixed(2));
       
    })
    .catch(error => console.error('Error fetching data:', error));
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Fetch data from the server
    fetch('./assets/accounting/weeksum.kts.php?action=getWeekSum') // Replace with your actual server endpoint
        .then(response => response.json())
        .then(data => {
            // Extract data from the JSON response
            const weeklySales = data.weeklyTotalSales;

            // Chart options
            const options = {
                series: [
                    {
                        name: "Total Sales",
                        data: Object.values(weeklySales)
                    },
                ],
                chart: {
                    type: 'bar',
                    height: 80, // Adjust height as needed
                    fontFamily: "Plus Jakarta Sans', sans-serif",
                    toolbar: {
                        show: false
                    },
                    sparkline: {
                        enabled: true
                    }
                },
                colors: ["var(--bs-primary)"],
                grid: {
                    show: false
                },
                plotOptions: {
                    bar: {
                        horizontal: false,
                        columnWidth: '25%',
                        borderRadius: 4,
                        distributed: true,
                    }
                },
                dataLabels: {
                    enabled: false
                },
                stroke: {
                    show: true,
                    width: 5,
                    colors: ['rgba(0,0,0,0.01)']
                },
                xaxis: {
                    categories: Object.keys(weeklySales),
                    axisBorder: {
                        show: false
                    },
                    axisTicks: {
                        show: false
                    },
                    labels: {
                        show: true
                    }
                },
                yaxis: {
                    labels: {
                        show: true
                    }
                },
                axisBorder: {
                    show: false
                },
                fill: {
                    opacity: 1
                },
                tooltip: {
                    theme: 'dark'
                },
            };

            // Create or update the chart
            const chart = new ApexCharts(document.querySelector("#sales-two"), options);
            chart.render();
        })
        .catch(error => console.error('Error fetching data:', error));
});
</script>
<script>
  
document.addEventListener('DOMContentLoaded', function () {
    // Fetch data from the server
    fetch('./assets/accounting/last18.kts.php?action=get18Data')
        .then(response => response.json())
        .then(data => {
            // Extract data from the JSON response
            var monthlySales = data.monthlySales;
            var sumMonthlySales = data.sumMonthlySales;
            var percentageChange = data.percentageChange;

            // Update the series data in the ApexCharts options
            var chartOptions = {
                chart: {
                    id: "growth",
                    type: "area",
                    height: 80,
                    sparkline: {
                        enabled: true,
                    },
                    group: "growth",
                    fontFamily: "Plus Jakarta Sans', sans-serif",
                    foreColor: "#adb0bb",
                },
                series: [
                    {
                        colors: ["var(--bs-primary)"],
                        data: monthlySales
                    },
                ],
                stroke: {
                    curve: "smooth",
                    width: 2,
                },
                fill: {
                    colors: ["#f3feff"],
                    type: "solid",
                    opacity: 0,
                },
                markers: {
                    size: 0,
                },
                tooltip: {
                    enabled: false,
                },
            };

            // Render the chart with updated options
            new ApexCharts(document.querySelector("#growths"), chartOptions).render();
             $('#centage').text(': ' + percentageChange.toFixed(2));
        var percentageChange = data.percentageChange;
    var percentageSpan = $('#percentage').text(': ' + percentageChange.toFixed(2));
    var arrowIcon = $('#arrowIcon');

    arrowIcon.removeClass(percentageChange < 0 ? 'text-success ti-arrow-up-right' : 'text-danger ti-arrow-down-right')
        .addClass(percentageChange < 0 ? 'text-danger ti-arrow-down-right' : 'text-success ti-arrow-up-right');
        })
        .catch(error => console.error('Error fetching data:', error));
});

</script>

<script>
 document.addEventListener("DOMContentLoaded", function() {
    // Fetch data from the server
    fetch('./assets/accounting/last8.kts.php?action=getLastSevenMonthsProfit')
        .then(response => response.json())
        .then(data => {
            // Extracting data for chart
            const monthNames = data.monthNames;
            const seriesData = Object.entries(data.monthlyProfits).map(([month, profit]) => ({ x: month, y: profit }));

            // Chart options
            const options = {
                chart: {
                    id: "monthly-earning",
                    type: "area",
                    height: 300,
                },
                xaxis: {
                    categories: monthNames,
                },
                series: [{
                    name: 'Monthly Earnings',
                    data: seriesData,
                }],
                stroke: {
                    curve: "smooth",
                    width: 2,
                },
                fill: {
                    type: "gradient",
                    gradient: {
                        shadeIntensity: 0,
                        inverseColors: false,
                        opacityFrom: 0.10,
                        opacityTo: 0,
                        stops: [20, 180],
                    },
                },
                markers: {
                    size: 0,
                },
                tooltip: {
                    theme: "dark",
                    fixed: {
                        enabled: true,
                        position: "right",
                    },
                    x: {
                        show: false,
                    },
                },
            };

            // Render the chart
            const chart = new ApexCharts(document.querySelector("#monthly-earning"), options);
            chart.render();

            // Display percentage change on the page
            const percentageChangeElement = document.getElementById("percentage-change");
            if (percentageChangeElement) {
                const percentageChange = data.percentageChange.toFixed(2); // Format to two decimal places
                percentageChangeElement.innerText = `Percentage Change: ${percentageChange}%`;
            }
        })
        .catch(error => console.error('Error fetching data:', error));
});

  
  </script>
 
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            // Fetch data from the server
            fetch('./assets/accounting/vendors.kts.php?action=getVendors')
                .then(response => response.json())
                .then(data => {
                    // Extracting data for table
                    const tableData = data;

                    // Get the table body
                    const tableBody = document.querySelector('#vendorTable tbody');

                    // Loop through the data and populate the table
                    tableData.forEach(row => {
                        const tableRow = document.createElement('tr');
                        tableRow.innerHTML = `
                            <td>${row.vendor_name}</td>
                            <td>${row.company}</td>
                            <td>${row.amount_owed}</td>
                            <td>${row.vendor_phone}</td>
                        `;
                        tableBody.appendChild(tableRow);
                    });

                    // Initialize DataTable
                    $('#vendorTable').DataTable();
                })
                .catch(error => console.error('Error fetching data:', error));
        });
    </script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    // Fetch data from the server
    fetch('./assets/accounting/annualsales.kts.php?action=getYearlyTotals')
        .then(response => response.json())
        .then(data => {
            // Update the spans with the fetched data
            const totalExpensesSpan = document.getElementById('totalExpenses');
            const totalSalesSpan = document.getElementById('totalSales');

            if (totalExpensesSpan && totalSalesSpan) {
                totalExpensesSpan.innerText = ` ${data.totalExpenses}`;
                totalSalesSpan.innerText = ` ${data.totalSales}`;
            }
        })
        .catch(error => console.error('Error fetching data:', error));
});
</script>
    
<script>
    // JavaScript code to fetch data and display it
    function fetchBusinessDetails() {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', './database/fetch_business.kts.php', true);
        xhr.onload = function() {
            if (this.status === 200) {
                var data = JSON.parse(this.responseText);
                
                console.log(data);  // Check if contact2 is present in the response
                
                // Check if no error
                if (!data.error) {
                    // Update the span elements with the fetched data
                    document.getElementById('shopname').innerText = data.shop_name || '';
                    document.getElementById('shopname1').innerText = data.shop_name || '';
                    document.getElementById('location').innerText = data.location || '';
                    document.getElementById('quote').innerText = data.quote || '';
                    document.getElementById('street').innerText = data.street || '';
                    document.getElementById('address').innerText = data.address || '';
                    document.getElementById('pin').innerText = data.pin || '';
                    document.getElementById('contact1').innerText = data.contact1 || '';
                    document.getElementById('contact2').innerText = data.contact2 || ''; // This should populate contact2
                } else {
                    console.error("Error: " + data.error);
                }
            } else {
                console.error("Failed to fetch data");
            }
        };
        xhr.send();
    }

    // Call the function as soon as the DOM is fully loaded
    document.addEventListener('DOMContentLoaded', fetchBusinessDetails);
</script>
</body>

</html>