<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
   header('location:login.php');
}
?>
<!doctype html>
<html lang="en">

<head>
   <!-- Required meta tags -->
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
   <title>Vito</title>
   <!-- Favicon -->
   <link rel="shortcut icon" href="images/favicon.ico" />
   <!-- Bootstrap CSS -->
   <link rel="stylesheet" href="css/bootstrap.min.css">
   <!-- Chart list Js -->
   <link rel="stylesheet" href="js/chartist/chartist.min.css">
   <!-- Typography CSS -->
   <link rel="stylesheet" href="css/typography.css">
   <!-- Style CSS -->
   <link rel="stylesheet" href="css/style.css">
   <!-- Responsive CSS -->
   <link rel="stylesheet" href="css/responsive.css">
</head>

<body class="sidebar-main-active right-column-fixed header-top-bgcolor">
   <!-- loader Start -->
   <div id="loading">
      <div id="loading-center">
      </div>
   </div>
   <!-- loader END -->
   <!-- Wrapper Start -->
   <div class="wrapper">
      <!-- Sidebar  -->
      <?php include 'includes/sidebar.php'; ?>
      <!-- TOP Nav Bar -->
      <?php include 'includes/header.php'; ?>
      <!-- TOP Nav Bar END -->
      <!-- Page Content  -->
      <div id="content-page" class="content-page">
         <div class="container-fluid" >
            <div class="row">
               <div class="col-lg-12 mb-4">
                  <!-- <h3><u>Welcome To Afghan Dry Fruits </u></h3> -->
               </div>
               <div class="col-lg-7">

               </div>
               <div class="col-lg-11 mb-3">
                  <a class="btn btn-primary" href="#" role="button" data-filter="today">Today</a>
                  <a class="btn btn-primary" href="#" role="button" data-filter="this_week">This Week</a>
                  <a class="btn btn-primary" href="#" role="button" data-filter="this_month">This Month</a>
                  <a class="btn btn-primary" href="#" role="button" data-filter="financial_year">This Financial Year</a>
               </div>
               <div class="col-sm-6 col-md-6 col-lg-3">
                  <div class="iq-card iq-card-block iq-card-stretch">
                     <div class="iq-card-body">
                        <div class="d-flex align-items-center justify-content-between">
                           <div class="rounded-circle iq-card-icon dark-icon-light iq-bg-primary">
                              <ion-icon style="font-size:30px; margin-top:15px;" name="cash-outline"></ion-icon>
                           </div>
                           <div>
                              <p class="fontsize-sm m-0">TOTAL PURCHASE</p>
                              <h2 class="total-purchase" style="font-size:20px">0.00 RS</h2>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
               <div class="col-sm-6 col-md-6 col-lg-3">
                  <div class="iq-card iq-card-block iq-card-stretch">
                     <div class="iq-card-body">
                        <div class="d-flex align-items-center justify-content-between">
                           <div class="rounded-circle iq-card-icon dark-icon-light iq-bg-primary">
                              <ion-icon style="font-size:30px; margin-top:15px;" name="cart-outline"></ion-icon>
                           </div>
                           <div>
                              <p class="fontsize-sm m-0">TOTAL SALES</p>
                              <h2 class="total-sales" style="font-size:20px">0.00 RS</h2>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>

               <script>
document.addEventListener("DOMContentLoaded", function () {
   function fetchData(filter) {
      fetch(`get_totals.php?filter=${filter}`)
         .then(response => response.json())
         .then(data => {
            if (data.error) {
               console.error(data.error);
            } else {
               // ✅ Update total values
               document.querySelector('.total-purchase').textContent = `${data.totalPurchases} RS`;
               document.querySelector('.total-sales').textContent = `${data.totalSales} RS`;
               document.querySelector('.total-expense').textContent = `${data.totalExpenses} RS`;
               document.querySelector('.total-returns').textContent = `${data.totalReturns} RS`;
               document.querySelector('.gross-profit').textContent = `${data.totalGrossProfit} RS`; 

               // ✅ Calculate and update Gross Profit distribution
               const grossProfit = parseFloat(data.totalGrossProfit) || 0;
               document.querySelector('.profit-haji').textContent = `${(grossProfit * 0.60).toFixed(2)} RS`;
               document.querySelector('.profit-israr').textContent = `${(grossProfit * 0.35).toFixed(2)} RS`;
               document.querySelector('.profit-expense').textContent = `${(grossProfit * 0.05).toFixed(2)} RS`;
            }
         })
         .catch(error => console.error('Error fetching data:', error));
   }

   // ✅ Load "Today" data on page load
   fetchData("today");

   // ✅ Add event listeners for button clicks
   document.querySelectorAll('.btn').forEach(button => {
      button.addEventListener('click', function() {
         const filter = this.getAttribute('data-filter');
         fetchData(filter);
      });
   });
});
</script>



               <!-- <div class="col-sm-6 col-md-6 col-lg-3">
                  <div class="iq-card iq-card-block iq-card-stretch ">
                     <div class="iq-card-body">
                        <div class="d-flex d-flex align-items-center justify-content-between">
                           <div class="rounded-circle iq-card-icon dark-icon-light iq-bg-primary "> <ion-icon style="font-size:30px; margin-top:15px;" name="alert-outline"></ion-icon></div>
                           <div>
                              <p class="fontsize-sm m-0">PURCHASE DUE </p>
                              <h2 style="font-size:20px">0.00 RS</h2>
                           </div>

                        </div>
                     </div>
                  </div>
               </div> -->
               <!-- <div class="col-sm-6 col-md-6 col-lg-3">
                  <div class="iq-card iq-card-block iq-card-stretch ">
                     <div class="iq-card-body">
                        <div class="d-flex d-flex align-items-center justify-content-between">
                           <div class="rounded-circle iq-card-icon dark-icon-light iq-bg-primary "> <ion-icon style="font-size:25px; margin-top:15px;" name="newspaper-outline"></ion-icon><span><ion-icon style="font-size:20px; margin-top:15px; margin-left:-8px" name="alert-outline"></ion-icon></span></div>
                           <div>
                              <p class="fontsize-sm m-0">INVOICE DUE </p>
                              <h2 style="font-size:20px">0.00 RS</h2>
                           </div>

                        </div>
                     </div>
                  </div>
               </div> -->
               <div class="col-sm-6 col-md-6 col-lg-3">
                  <div class="iq-card iq-card-block iq-card-stretch ">
                     <div class="iq-card-body">
                        <div class="d-flex d-flex align-items-center justify-content-between">
                           <div class="rounded-circle iq-card-icon dark-icon-light iq-bg-primary "> <ion-icon style="font-size:30px; margin-top:15px;" name="remove-circle-outline"></ion-icon></div>
                           <div>
                              <p class="fontsize-sm m-0">EXPENSE </p>
                              <h2 class="total-expense" style="font-size:20px">0.00 RS</h2>
                           </div>

                        </div>
                     </div>
                  </div>
               </div>

               <div class="col-sm-6 col-md-6 col-lg-3">
   <div class="iq-card iq-card-block iq-card-stretch">
      <div class="iq-card-body">
         <div class="d-flex align-items-center justify-content-between">
            <div class="rounded-circle iq-card-icon iq-bg-primary">
               <ion-icon style="font-size:30px;" name="remove-circle-outline"></ion-icon>
            </div>
            <div>
               <p class="fontsize-sm m-0">Return Sale</p>
               <h2 class="total-returns" style="font-size:20px">0.00 RS</h2>
            </div>
         </div>
      </div>
   </div>
</div>

<!-- <div class="col-sm-6 col-md-6 col-lg-3">
   <div class="iq-card iq-card-block iq-card-stretch">
      <div class="iq-card-body">
         <div class="d-flex align-items-center justify-content-between">
            <div class="rounded-circle iq-card-icon iq-bg-primary">
               <ion-icon style="font-size:30px;" name="remove-circle-outline"></ion-icon>
            </div>
            <div>
               <p class="fontsize-sm m-0">Gross Profit</p>
               <h2 class="gross-profit" style="font-size:20px">0.00 RS</h2>
            </div>
         </div>
      </div>
   </div>
</div>


<div class="col-sm-6 col-md-6 col-lg-3">
   <div class="iq-card iq-card-block iq-card-stretch">
      <div class="iq-card-body">
         <div class="d-flex d-flex align-items-center justify-content-between">
            <div class="rounded-circle iq-card-icon dark-icon-light iq-bg-primary"> 
               <ion-icon style="font-size:30px; margin-top:15px;" name="remove-circle-outline"></ion-icon>
            </div>
            <div>
               <p class="fontsize-sm m-0">Haji Sab 60 %</p>
               <h2 class="profit-haji" style="font-size:20px">0.00 RS</h2>
            </div>
         </div>
      </div>
   </div>
</div>

<div class="col-sm-6 col-md-6 col-lg-3">
   <div class="iq-card iq-card-block iq-card-stretch">
      <div class="iq-card-body">
         <div class="d-flex d-flex align-items-center justify-content-between">
            <div class="rounded-circle iq-card-icon dark-icon-light iq-bg-primary"> 
               <ion-icon style="font-size:30px; margin-top:15px;" name="remove-circle-outline"></ion-icon>
            </div>
            <div>
               <p class="fontsize-sm m-0">Israr Sab 35 %</p>
               <h2 class="profit-israr" style="font-size:20px">0.00 RS</h2>
            </div>
         </div>
      </div>
   </div>
</div>

<div class="col-sm-6 col-md-6 col-lg-3">
   <div class="iq-card iq-card-block iq-card-stretch">
      <div class="iq-card-body">
         <div class="d-flex d-flex align-items-center justify-content-between">
            <div class="rounded-circle iq-card-icon dark-icon-light iq-bg-primary"> 
               <ion-icon style="font-size:30px; margin-top:15px;" name="remove-circle-outline"></ion-icon>
            </div>
            <div>
               <p class="fontsize-sm m-0">Expense 5 %</p>
               <h2 class="profit-expense" style="font-size:20px">0.00 RS</h2>
            </div>
         </div>
      </div>
   </div>
</div> -->



               
            </div>

            <!-------------------------------------------Cheque status --------------------------------------------->

            <div class="row">
               <div class="col-lg-6">
                  <div class="iq-card iq-card-block iq-card-stretch iq-card-height" style="border-top: 3px solid #ffc107;">
                     <div class="iq-card-header d-flex justify-content-between">
                        <div class="iq-header-title">
                           <h6 class="card-title" style="font-size: 20px;">
                              <span><ion-icon name="warning-outline" Style=" Color:#fad14c; font-size:25px;"></ion-icon>
                                 Receivable Hold Cheque Notifcations
                                 <ion-icon name="information-circle-outline" Style="margin-bottom:-5px; Color:blue;font-size:25px;"></ion-icon></span>
                           </h6>
                        </div>
                        <!-- <div class="iq-card-header-toolbar d-flex align-items-center">
                           <div class="dropdown">
                              <span class="dropdown-toggle text-primary" id="dropdownMenuButton5" data-toggle="dropdown">
                                 <i class="ri-more-fill"></i>
                              </span>
                              <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton5">
                                 <a class="dropdown-item" href="#"><i class="ri-eye-fill mr-2"></i>View</a>
                                 <a class="dropdown-item" href="#"><i class="ri-delete-bin-6-fill mr-2"></i>Delete</a>
                                 <a class="dropdown-item" href="#"><i class="ri-pencil-fill mr-2"></i>Edit</a>
                                 <a class="dropdown-item" href="#"><i class="ri-printer-fill mr-2"></i>Print</a>
                                 <a class="dropdown-item" href="#"><i class="ri-file-download-fill mr-2"></i>Download</a>
                              </div>
                           </div>
                        </div> -->
                     </div>
                     <div class="iq-card-body">
                        <div class="table-responsive">
                        <?php
include 'includes/config.php';

$currentDate = date('Y-m-d');
$nextDate = date('Y-m-d', strtotime('+1 day'));

$sql = "
    SELECT `id`, `customer_id`, `bank_name`, `clearance_date`, `cheque_number`, `amount`, `hold_until`, `status`
    FROM `cheque_payments` 
    WHERE (`status` = 'hold' AND (`hold_until` <= :currentDate OR `hold_until` = :nextDate))
    OR (`status` = 'clearance')
    ORDER BY `id` DESC
";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':currentDate', $currentDate);
$stmt->bindParam(':nextDate', $nextDate);
$stmt->execute();

// Fetch customer names for display
$customerQuery = "SELECT `id`, `name` FROM `contacts`";
$customerStmt = $conn->query($customerQuery);
$customers = [];
while ($row = $customerStmt->fetch(PDO::FETCH_ASSOC)) {
    $customers[$row['id']] = $row['name'];
}
?>

<style>
   .table {
      width: 100%;
      border-collapse: collapse;
   }

   .table th,
   .table td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: center;
   }

   .table th {
      background-color: #f4f4f4;
   }

   .highlight-warning {
      background-color: #f9c6c6; /* Light red for overdue */
   }

   .highlight-safe {
      background-color: #d4edda; /* Light green for today */
   }

   .highlight-next-day {
      background-color: #e0e0e0; /* Light gray for next day */
   }
   .highlight-clearance {
      background-color: #fff3cd; /* Light yellow for clearance */
   }
</style>

<table class="table mb-0 table-borderless">
    <thead>
        <tr>
            <th scope="col">Customer <br>Name</th>
            <th scope="col">Bank <br>Name</th>
            <th scope="col">Check No</th>
            <th scope="col">Amount</th>
            <th scope="col">Hold <br>Until</th>
            <th scope="col">Clearance <br>Until</th>
        </tr>
    </thead>
    <tbody>
        <?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
            <?php
            $customerName = isset($customers[$row['customer_id']]) ? htmlspecialchars($customers[$row['customer_id']]) : 'N/A';
            // Add new class for next day
            $rowClass = $row['status'] == 'clearance' ? 'highlight-clearance' : 

            $rowClass = ($row['hold_until'] < $currentDate) ? 'highlight-warning' : 
                        ($row['hold_until'] == $nextDate ? 'highlight-next-day' : 'highlight-safe');
            ?>
            <tr class="<?php echo $rowClass; ?>">
                <td><?php echo $customerName; ?></td>
                <td><?php echo htmlspecialchars($row['bank_name']); ?></td>
                <td><?php echo htmlspecialchars($row['cheque_number']); ?></td>
                <td><?php echo htmlspecialchars($row['amount']); ?></td>
                <td><?php echo htmlspecialchars($row['hold_until']); ?></td>
                <td><?php echo htmlspecialchars($row['clearance_date']); ?></td>
            </tr>
        <?php } ?>
    </tbody>
</table>



                        </div>
                     </div>
                  </div>
               </div>
               <div class="col-lg-6">
                  <div class="iq-card iq-card-block iq-card-stretch iq-card-height" style="border-top: 3px solid #ffc107;">
                     <div class="iq-card-header d-flex justify-content-between">
                        <div class="iq-header-title">
                           <h6 class="card-title" style="font-size: 20px;">
                              <span><ion-icon name="warning-outline" Style=" Color:#fad14c; font-size:25px;"></ion-icon>
                                 Payable Hold Cheque Notifcations
                                 <ion-icon name="information-circle-outline" Style="margin-bottom:-5px; Color:blue;font-size:25px;"></ion-icon></span>
                           </h6>
                        </div>
                        <!-- <div class="iq-card-header-toolbar d-flex align-items-center">
                           <div class="dropdown">
                              <span class="dropdown-toggle text-primary" id="dropdownMenuButton5" data-toggle="dropdown">
                                 <i class="ri-more-fill"></i>
                              </span>
                              <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton5">
                                 <a class="dropdown-item" href="#"><i class="ri-eye-fill mr-2"></i>View</a>
                                 <a class="dropdown-item" href="#"><i class="ri-delete-bin-6-fill mr-2"></i>Delete</a>
                                 <a class="dropdown-item" href="#"><i class="ri-pencil-fill mr-2"></i>Edit</a>
                                 <a class="dropdown-item" href="#"><i class="ri-printer-fill mr-2"></i>Print</a>
                                 <a class="dropdown-item" href="#"><i class="ri-file-download-fill mr-2"></i>Download</a>
                              </div>
                           </div>
                        </div> -->
                     </div>
                     <div class="iq-card-body">
                        <div class="table-responsive">
  

<style>
   .table {
      width: 100%;
      border-collapse: collapse;
   }

   .table th,
   .table td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: center;
   }

   .table th {
      background-color: #f4f4f4;
   }

   .highlight-warning {
      background-color: #f9c6c6;
      /* Light red for overdue */
   }

   .highlight-safe {
      background-color: #d4edda;
      /* Light green for today */
   }

   .highlight-gray {
      background-color: #e0e0e0;
      /* Light gray for next day */
   }
</style>
<?php
include 'includes/config.php';

$currentDate = date('Y-m-d');
$nextDate = date('Y-m-d', strtotime('+1 day'));

$sql = "
    SELECT `id`, `supplier_id`, `bank_name`, `cheque_number`, `amount`, `hold_until` 
    FROM `payable_cheque` 
    WHERE `status` = 'hold' AND (`hold_until` <= :currentDate OR `hold_until` = :nextDate)
    ORDER BY `id` DESC
";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':currentDate', $currentDate);
$stmt->bindParam(':nextDate', $nextDate);
$stmt->execute();

// Check if records exist
$hasRecords = $stmt->rowCount() > 0;

// Fetch customer names for display
$customerQuery = "SELECT `id`, `name` FROM `contacts`";
$customerStmt = $conn->query($customerQuery);
$customers = [];
while ($row = $customerStmt->fetch(PDO::FETCH_ASSOC)) {
    $customers[$row['id']] = $row['name'];
}
?>

<style>
   .table {
      width: 100%;
      border-collapse: collapse;
   }

   .table th,
   .table td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: center;
   }

   .table th {
      background-color: #f4f4f4;
   }

   .highlight-warning {
      background-color: #f9c6c6;
      /* Light red for overdue */
   }

   .highlight-safe {
      background-color: #d4edda;
      /* Light green for today */
   }

   .highlight-gray {
      background-color: #e0e0e0;
      /* Light gray for next day */
   }

   /* Hidden interaction button */
   .hidden-button {
      display: none;
   }
</style>

<!-- Hidden button to trigger user interaction -->
<button class="hidden-button" id="startBeepButton"></button>

<table class="table mb-0 table-borderless">
    <thead>
        <tr>
            <th scope="col">Supplier <br>Name</th>
            <th scope="col">Bank <br>Name</th>
            <th scope="col">Check <br>No</th>
            <th scope="col">Amount</th>
            <th scope="col">Hold <br>Until</th>
        </tr>
    </thead>
    <tbody>
        <?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
            <?php
            $customerName = isset($customers[$row['supplier_id']]) ? htmlspecialchars($customers[$row['supplier_id']]) : 'N/A';
            $rowClass = ($row['hold_until'] < $currentDate) ? 'highlight-warning' :
                        ($row['hold_until'] == $nextDate ? 'highlight-gray' : 'highlight-safe');
            ?>
            <tr class="<?php echo $rowClass; ?>">
                <td><?php echo $customerName; ?></td>
                <td><?php echo htmlspecialchars($row['bank_name']); ?></td>
                <td><?php echo htmlspecialchars($row['cheque_number']); ?></td>
                <td><?php echo htmlspecialchars($row['amount']); ?></td>
                <td><?php echo htmlspecialchars($row['hold_until']); ?></td>
            </tr>
        <?php } ?>
    </tbody>
</table>

<script>
    let userInteracted = false;
    document.body.addEventListener('click', function() {
        userInteracted = true;
    });

    function playBeep() {
        if (userInteracted) {
            const beepSound = new Audio('beep/notifcation_cheque.mp3'); 
            beepSound.play();

            setTimeout(() => {
                beepSound.pause();
                beepSound.currentTime = 0;
            }, 6000); 
        } else {
            console.log("User hasn't interacted yet");
        }
    }

   
    <?php if ($hasRecords): ?>
        
        window.onload = function() {
            playBeep();
        }
    <?php endif; ?>
</script>

                        </div>
                     </div>
                  </div>
               </div>
               <!-- <div class="col-lg-4">
                     <div class="iq-card iq-card-block iq-card-stretch iq-card-height">
                        <div class="iqard-header d-flex justify-content-between">
                           <div class="iq-header-title">
                              <h4 class="card-title">Monthly Invoices</h4>
                           </div>
                           <div class="iq-card-header-toolbar d-flex align-items-center">
                              <div class="dropdown">
                                 <span class="dropdown-toggle" id="dropdownMenuButton1" data-toggle="dropdown" >
                                 <i class="ri-more-fill"></i>
                                 </span>
                                 <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton1" style="">
                                    <a class="dropdown-item" href="#"><i class="ri-eye-fill mr-2"></i>View</a>
                                    <a class="dropdown-item" href="#"><i class="ri-delete-bin-6-fill mr-2"></i>Delete</a>
                                    <a class="dropdown-item" href="#"><i class="ri-pencil-fill mr-2"></i>Edit</a>
                                    <a class="dropdown-item" href="#"><i class="ri-printer-fill mr-2"></i>Print</a>
                                    <a class="dropdown-item" href="#"><i class="ri-file-download-fill mr-2"></i>Download</a>
                                 </div>
                              </div>
                           </div>
                        </div>
                        <div class="iq-card-body">
                          <ul class="suggestions-lists m-0 p-0">
                           <li class="d-flex mb-4 align-items-center">
                              <div class="profile-icon iq-bg-success"><span><i class="ri-check-fill"></i></span></div>
                              <div class="media-support-info ml-3">
                                 <h6>Camelun ios</h6>
                                 <p class="mb-0 fontsize-sm"><span class="text-success">17/23</span> months paid</p>
                              </div>
                              <div class="media-support-amount ml-3">
                                 <h6><span class="text-secondary">$</span><b> 16,634.00</b></h6>
                                 <p class="mb-0 d-flex justify-content-end">per month</p>
                              </div>
                           </li>
                           <li class="d-flex mb-4 align-items-center">
                              <div class="profile-icon iq-bg-warning"><span><i class="ri-check-fill"></i></span></div>
                              <div class="media-support-info ml-3">
                                 <h6>React</h6>
                                 <p class="mb-0 fontsize-sm"><span class="text-warning">12 weeks </span>Due</p>
                              </div>
                              <div class="media-support-amount ml-3">
                                 <h6><span class="text-secondary">$</span><b> 6,000.00</b></h6>
                                 <p class="mb-0 d-flex justify-content-end">per month</p>
                              </div>
                           </li>
                           <li class="d-flex mb-4 align-items-center">
                              <div class="profile-icon iq-bg-success"><span><i class="ri-check-fill"></i></span></div>
                              <div class="media-support-info ml-3">
                                 <h6>Camelun ios</h6>
                                 <p class="mb-0 fontsize-sm"><span class="text-success">16/23</span> months paid</p>
                              </div>
                              <div class="media-support-amount ml-3">
                                 <h6><span class="text-secondary">$</span><b> 11,230.00</b></h6>
                                 <p class="mb-0 d-flex justify-content-end">per month</p>
                              </div>
                           </li>
                           <li class="d-flex mb-1 align-items-center">
                              <div class="profile-icon iq-bg-danger"><span><i class="ri-check-fill"></i></span></div>
                              <div class="media-support-info ml-3">
                                 <h6>Camelun ios</h6>
                                 <p class="mb-0 fontsize-sm"><span class="text-danger">15/23</span> months paid</p>
                              </div>
                              <div class="media-support-amount ml-3">
                                 <h6><span class="text-secondary">$</span><b> 10,050.00</b></h6>
                                 <p class="mb-0 d-flex justify-content-end">per month</p>
                              </div>
                           </li>
                        </ul>
                        </div>
                     </div>
                  </div> -->
            </div>




            <!---------------------------------------------End cheque status ---------------------------------------------->
            <div class="row">
               <div class="col-lg-12 row m-0 p-0">
                  <div class="col-md-12">
                     <div class="iq-card iq-card-block iq-card-stretch" style="border-top:3px solid blue; border-radius:5px">
                        <div class="iq-card-header d-flex justify-content-between">
                           <div class="iq-header-title">
                              <h4 class="card-title">Sales Last 30 Days</h4>
                           </div>
                           <div class="iq-card-header-toolbar d-flex align-items-center">
                              <div class="dropdown">
                                 <span class="dropdown-toggle" id="dropdownMenuButton-one" data-toggle="dropdown">
                                    <i class="ri-more-fill"></i>
                                 </span>
                                 <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton-one">
                                    <a class="dropdown-item" href="#"><i class="ri-eye-fill mr-2"></i>View</a>
                                    <a class="dropdown-item" href="#"><i class="ri-delete-bin-6-fill mr-2"></i>Delete</a>
                                    <a class="dropdown-item" href="#"><i class="ri-pencil-fill mr-2"></i>Edit</a>
                                    <a class="dropdown-item" href="#"><i class="ri-printer-fill mr-2"></i>Print</a>
                                    <a class="dropdown-item" href="#"><i class="ri-file-download-fill mr-2"></i>Download</a>
                                 </div>
                              </div>
                           </div>
                        </div>
                        <div class="iq-card-body">
                           <canvas id="salesChart"></canvas>
                        </div>
                     </div>
                  </div>
               </div>
            </div>

            <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
            <script>
               document.addEventListener('DOMContentLoaded', () => {
                  const ctx = document.getElementById('salesChart').getContext('2d');

                  
                  fetch('fetch_sales_data_graph.php')
                     .then(response => response.json())
                     .then(data => {
                        const labels = data.map(row => row.date);
                        const salesData = data.map(row => row.total_sales);
const companyName = "<?= htmlspecialchars($company['name'] ?? 'Company') ?>";

                        const salesChart = new Chart(ctx, {
                           type: 'line', 
                           data: {
                              labels: labels,
                              datasets: [{
                                  label: companyName + ': Sales (RS)',
                                 data: salesData,
                                 borderColor: 'rgba(75, 192, 192, 1)',
                                 backgroundColor: 'rgba(75, 192, 192, 0.2)',
                                 borderWidth: 1,
                                 fill: true,
                              }]
                           },
                           options: {
                              responsive: true,
                              scales: {
                                 y: {
                                    beginAtZero: true,
                                 }
                              }
                           }
                        });
                     })
                     .catch(error => console.error('Error fetching sales data:', error));
               });
            </script>

            <div class="row">
               <div class="col-lg-12">
                  <div class="iq-card" style="border-top:3px solid blue;">
                     <div class="iq-card-header d-flex justify-content-between">
                        <div class="iq-header-title">
                           <h4 class="card-title">Sales Current Financial Year</h4>
                        </div>
                     </div>
                     <div class="iq-card-body">
                        <canvas id="financialYearSalesChart"></canvas>
                     </div>
                  </div>
               </div>
            </div>

            <script>
               document.addEventListener('DOMContentLoaded', () => {
                  const ctx = document.getElementById('financialYearSalesChart').getContext('2d');
const companyName = "<?= htmlspecialchars($company['name'] ?? 'Company') ?>";

                  
                  fetch('fetch_sales_current_year.php')
                     .then(response => response.json())
                     .then(data => {
                        const labels = data.map(row => row.date);
                        const salesData = data.map(row => row.total_sales);

                        const financialYearSalesChart = new Chart(ctx, {
                           type: 'line',
                           data: {
                              labels: labels,
                              datasets: [{
                                  label: companyName + ': Sales (RS)',
                                 data: salesData,
                                 borderColor: 'rgba(75, 192, 192, 1)',
                                 backgroundColor: 'rgba(75, 192, 192, 0.2)',
                                 borderWidth: 2,
                                 fill: true, 
                                 tension: 0.3 
                              }]
                           },
                           options: {
                              responsive: true,
                              scales: {
                                 x: {
                                    title: {
                                       display: true,
                                       text: 'Date'
                                    }
                                 },
                                 y: {
                                    title: {
                                       display: true,
                                       text: 'Sheen Oil Traders (RS)'
                                    },
                                    beginAtZero: true,
                                 }
                              }
                           }
                        });
                     })
                     .catch(error => console.error('Error fetching sales data:', error));
               });
            </script>

         </div>
      </div>


   </div>

   <div class="iq-right-fixed">
      <div class="container mt-3">
         <div class="iq-header-title">
            <h4 class="card-title">
               <span><ion-icon name="warning-outline" Style=" Color:#fad14c; font-size:25px;"></ion-icon>
                  Product Stock Alert
                  <ion-icon name="information-circle-outline" Style="margin-bottom:-5px; Color:blue;font-size:25px;"></ion-icon></span>
            </h4>
         </div>
         <input type="text" class="form-control" placeholder="Search product....." onkeyup="searchProducts(this.value)">
         <div style="max-height: 400px; overflow-y: auto;">

            <table class="table table-striped">
               <thead>
                  <tr>
                     <th>Product</th>
                     <th>Location</th>
                     <th>Stock</th>
                  </tr>
               </thead>
               <tbody id="product-tbody">
                  <tr>
                     <td colspan="3">No products available. Start typing to search.</td>
                  </tr>
               </tbody>
            </table>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
         </div><button class="btn btn-success" id="export-button" onclick="exportToExcel()">Export Data</button>

         <script>
            function searchProducts(searchTerm) {
               // Fetch products based on the search term
               fetch(`search_products_index.php?search=${encodeURIComponent(searchTerm)}`)
                  .then(response => response.text())
                  .then(data => {
                     document.querySelector('#product-tbody').innerHTML = data; // Replace tbody content with new data
                  })
                  .catch(error => console.error('Error fetching products:', error));
            }

            // Call this function to load all products on page load
            document.addEventListener('DOMContentLoaded', () => {
               searchProducts(''); // Load all products by default
            });

            // Function to export table data to Excel
            function exportToExcel() {
               // Get table data
               const table = document.getElementById('product-tbody');
               const rows = table.getElementsByTagName('tr');
               const excelData = [];

               // Add headers
               excelData.push(['Product', 'Location', 'Stock']);

               // Add rows
               for (let row of rows) {
                  const cols = row.getElementsByTagName('td');
                  if (cols.length > 0) {
                     const rowData = [];
                     for (let col of cols) {
                        rowData.push(col.innerText); // Get cell text
                     }
                     excelData.push(rowData);
                  }
               }

               // Create a worksheet
               const worksheet = XLSX.utils.aoa_to_sheet(excelData);
               const workbook = XLSX.utils.book_new();
               XLSX.utils.book_append_sheet(workbook, worksheet, 'Products');

               // Export to Excel
               XLSX.writeFile(workbook, 'products.xlsx');
            }
         </script>




         <!-- <p>Showing 1 to 975 of 975 entries</p>
           <div class="row">
           <div class="col-lg-9">

           </div>
               <div class="col-lg-3">
                  <a class="btn btn-primary" href="#" role="button">Previous</a>
                  <a class="btn btn-primary" href="#" role="button">1</a>
                  <a class="btn btn-primary" href="#" role="button">Next</a>
               </div>
           </div> -->
      </div>
   </div>

   <!-- Wrapper END -->
   <!-- Footer -->
   <footer class="iq-footer">
      <div class="container-fluid">
         <div class="row">
            <div class="col-lg-6">
               <ul class="list-inline mb-0">
                  <li class="list-inline-item"><a href="privacy-policy.html">Privacy Policy</a></li>
                  <li class="list-inline-item"><a href="terms-of-service.html">Terms of Use</a></li>
               </ul>
            </div>
            <div class="col-lg-6 text-right">
               Copyright <span id="copyright">
                  <script>
                     document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))
                  </script>
               </span> <a href="#">Vito</a> All Rights Reserved.
            </div>
         </div>
      </div>
   </footer>

   <nav class="iq-float-menu">
      <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
      <label class="iq-float-menu-open-button" for="menu-open">
         <span class="lines line-1"></span>
         <span class="lines line-2"></span>
         <span class="lines line-3"></span>
      </label>
      <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode" data-mode="rtl"><i class="ri-text-direction-r"></i></button>
      <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode" id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
      <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i class="ri-palette-line"></i></button>
   </nav>
   <!-- Footer END -->
   <!-- Optional JavaScript -->
   <!-- jQuery first, then Popper.js, then Bootstrap JS -->

   <script src="js/jquery.min.js"></script>
   <!-- Rtl and Darkmode -->
   <script src="js/rtl.js"></script>
   <script src="js/customizer.js"></script>
   <script src="js/popper.min.js"></script>
   <script src="js/bootstrap.min.js"></script>
   <!-- Appear JavaScript -->
   <script src="js/jquery.appear.js"></script>
   <!-- Countdown JavaScript -->
   <script src="js/countdown.min.js"></script>
   <!-- Counterup JavaScript -->
   <script src="js/waypoints.min.js"></script>
   <script src="js/jquery.counterup.min.js"></script>
   <!-- Wow JavaScript -->
   <script src="js/wow.min.js"></script>
   <!-- Apexcharts JavaScript -->
   <script src="js/apexcharts.js"></script>
   <!-- Slick JavaScript -->
   <script src="js/slick.min.js"></script>
   <!-- Select2 JavaScript -->
   <script src="js/select2.min.js"></script>
   <!-- Magnific Popup JavaScript -->
   <script src="js/jquery.magnific-popup.min.js"></script>
   <!-- Smooth Scrollbar JavaScript -->
   <script src="js/smooth-scrollbar.js"></script>
   <!-- lottie JavaScript -->
   <script src="js/lottie.js"></script>
   <!-- am core JavaScript -->
   <script src="js/core.js"></script>
   <!-- am charts JavaScript -->
   <script src="js/charts.js"></script>
   <!-- am animated JavaScript -->
   <script src="js/animated.js"></script>
   <!-- am kelly JavaScript -->
   <script src="js/kelly.js"></script>
   <!-- Morris JavaScript -->
   <script src="js/morris.js"></script>
   <!-- am maps JavaScript -->
   <script src="js/maps.js"></script>
   <!-- am worldLow JavaScript -->
   <script src="js/worldLow.js"></script>
   <!-- ChartList Js -->
   <script src="js/chartist/chartist.min.js"></script>
   <!-- Chart Custom JavaScript -->
   <script async src="js/chart-custom.js"></script>
   <!-- Custom JavaScript -->
   <script src="js/custom.js"></script>
   <script src="js/jquery.min.js"></script>
   <!-- Rtl and Darkmode -->
   <script src="js/rtl.js"></script>
   <script src="js/customizer.js"></script>
   <script src="js/popper.min.js"></script>
   <script src="js/bootstrap.min.js"></script>
   <!-- Appear JavaScript -->
   <script src="js/jquery.appear.js"></script>
   <!-- Countdown JavaScript -->
   <script src="js/countdown.min.js"></script>
   <!-- Counterup JavaScript -->
   <script src="js/waypoints.min.js"></script>
   <script src="js/jquery.counterup.min.js"></script>
   <!-- Wow JavaScript -->
   <script src="js/wow.min.js"></script>
   <!-- Apexcharts JavaScript -->
   <script src="js/apexcharts.js"></script>
   <!-- Slick JavaScript -->
   <script src="js/slick.min.js"></script>
   <!-- Select2 JavaScript -->
   <script src="js/select2.min.js"></script>
   <!-- Owl Carousel JavaScript -->
   <script src="js/owl.carousel.min.js"></script>
   <!-- Magnific Popup JavaScript -->
   <script src="js/jquery.magnific-popup.min.js"></script>
   <!-- Smooth Scrollbar JavaScript -->
   <script src="js/smooth-scrollbar.js"></script>
   <!-- lottie JavaScript -->
   <script src="js/lottie.js"></script>
   <!-- highcharts JavaScript -->
   <script src="js/highcharts.js"></script>
   <!-- highcharts-3d JavaScript -->
   <script src="js/highcharts-3d.js"></script>
   <!-- highcharts-more JavaScript -->
   <script src="js/highcharts-more.js"></script>
   <!-- Chart Custom JavaScript -->
   <script src="js/chart-custom.js"></script>
   <!-- Custom JavaScript -->
   <script src="js/custom.js"></script>
</body>

</html>