<?php
     session_start();
      include 'database/shikanisha.kts.php';
        if(!($_SESSION['type'] == 'Manager' )){
            header("location:logout.php");
}


if (isset($_GET['action'])) {
    if ($_GET['action'] == 'clearall') {
        unset($_SESSION['p_order']);
        header('Location: http:./purchases.php');
        exit();
    }

    if ($_GET['action'] == 'remove') {
        foreach ($_SESSION['p_order'] as $key => $value) {
            if ($value['id'] == $_GET['id']) {
                unset($_SESSION['p_order'][$key]);
                header('Location:./purchases.php');
                exit();
            }
        }
    }
}

if(isset($_POST['add'])){
    $id    = $_POST['add'];
    $name  = $_POST['name'];
    $company = $_POST['company'];
    $qty   = $_POST['qty'];
    
  
      // Product add to list
      $session_array = array(
          'id'    =>  $id,
          'name'  =>  $name,
          'company' =>  $company,
          'qty'   =>  $qty 
      );
          
      if(!empty($_SESSION['p_order'])){
          $session_array_id = array_column($_SESSION['p_order'],'id');
          if(in_array($id, $session_array_id))
          {
              foreach($_SESSION['p_order'] as $key => $val){
                  if($_SESSION['p_order'][$key]['id']===$id){
                      if(!empty($qty)){
                          $_SESSION['p_order'][$key]['qty'] = $_SESSION['p_order'][$key]['qty'] + $qty;
                      }
                  }
              }
          }else{
              if(!empty($qty)){
                  $_SESSION['p_order'][]= $session_array;
              }
          }
      }else{
          if(!empty($qty)){
              $_SESSION['p_order'][]= $session_array;
         
      
    } else {
      echo "Error: " . mysqli_error($conn);
    }
}
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title id="shopname"></title>
    <!-- Favicon icon -->
    <link rel="icon" type="./quixlab/image/png" sizes="16x16" href="./quixlab/images/favicon.png">
    <!-- Pignose Calender -->
    <link href="./quixlab/plugins/pg-calendar/css/pignose.calendar.min.css" rel="stylesheet">
    <!-- Chartist -->
    <link rel="stylesheet" href="./quixlab/plugins/chartist/css/chartist.min.css">
    <link rel="stylesheet" href="./quixlab/plugins/chartist-plugin-tooltips/css/chartist-plugin-tooltip.css">
    <!-- Custom Stylesheet -->
    <link href="./quixlab/css/design.css" rel="stylesheet">
    <!-- DataTables with Buttons -->
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <link href="./quixlab/plugins/tables/css/datatable/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="./quixlab/css/buttons.bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.min.css">


</head>

<body>

    <!--*******************
        Preloader start
    ********************-->
    <div id="preloader">
        <div class="loader">
            <svg class="circular" viewBox="25 25 50 50">
                <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="3" stroke-miterlimit="10" />
            </svg>
        </div>
    </div>
    <!--*******************
        Preloader end
    ********************-->

    
    <!--**********************************
        Main wrapper start
    ***********************************-->
    <div id="main-wrapper">

        <!--**********************************
            Nav header start
        ***********************************-->
        <div class="nav-header">
            <div class="brand-logo" style="background-image: url('./quixlab/images/room.png');">
                
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header start
        ***********************************-->
        <div class="header">    
            <div class="header-content clearfix">
                
                <div class="nav-control">
                    <div class="hamburger">
                        <span class="toggle-icon"><i class="icon-menu"></i></span>
                    </div>
                </div>
                <div class="header-left">
                    <div class="input-group icons">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-transparent border-0 pr-2 pr-sm-3" id="basic-addon1"><i class="mdi mdi-magnify"></i></span>
                        </div>
                        <input type="search" class="form-control" placeholder="Search Dashboard" aria-label="Search Dashboard">
                        <div class="drop-down animated flipInX d-md-none">
                            <form action="#">
                                <input type="text" class="form-control" placeholder="Search">
                            </form>
                        </div>
                    </div>
                </div>
                <div class="header-right">
                    <ul class="clearfix">
                        
                        <li class="icons dropdown d-none d-md-flex"><a href="javascript:void(0)" id="storecart">
                                <i class="mdi mdi-cart-outline"></i>
                                <span class="badge badge-pill gradient-12">2</span>
                            </a>
                        </li>
                        
                    </ul>
                </div>
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header start
        ***********************************-->
 
<div class="nk-sidebar">           
      <?php require 'navbar.php'; ?>
</div> <!--**********************************
            Header end ti-comment-alt
        ***********************************-->

        <!--**********************************
            Sidebar start
        ***********************************-->
    
        <!--**********************************
            Sidebar end
        ***********************************-->

        <!--**********************************
            Content body start
        ***********************************-->
        <div class="content-body">

            <div class="container-fluid mt-3">
                 <div class="row">
                    <div class="col-lg-6 col-sm-6" id="vendor">
                        <div class="card gradient-9">
                            <div class="card-body">
                                <h3 class="card-title text-white"></h3>
                                <div class="d-inline-block">
                                    <h2 class="text-white">Add Vendor</h2>
                                    <p class="text-white mb-0"></p>
                                </div>
                                <span class="float-right display-5 opacity-5"><i class="fa fa-shopping-cart"></i></span>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6 col-sm-6">
    <div class="card gradient-8"  data-toggle="modal" data-target="#addPurchaseModal">
        <div class="card-body">
            <h3 class="card-title text-white"></h3>
            <div class="d-inline-block">
                <h2 class="text-white">Add Purchase</h2>
                <p class="text-white mb-0"></p>
            </div>
            <span class="float-right display-5 opacity-5"><i class="fa fa-money"></i></span>
        </div>
    </div>
</div>

                  </div>
                <div class="row">
                   
                    <div class="col-lg-12 col-sm-12">
                      <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Vendor Details</h4>
                                <div class="table-responsive">
                                    <table class="table table-striped table-bordered zero-configuration table-sm">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Name</th>
                                                <th>Contact</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody id="vendor_table">
                                        
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
               </div> 
                   <div class="row">
                   
                    <div class="col-lg-12 col-sm-12">
                      <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Vendor Debts</h4>
                                <div class="table-responsive">
                                       <table class="table table-bordered" id="vendorDebtsTable">
            <thead>
                <tr>
                    <th>Vendor Name</th>
                    <th>Amount Owned</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <!-- Vendor debts will be dynamically inserted here -->
            </tbody>
        </table>
                                </div>
                            </div>
                        </div>
                    </div>
               </div> 
                  
              <div class="row">     
                    <div class="col-lg-12 col-sm-12">
                      <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Vendor Pay/Debt Transactions</h4>
                                <div class="table-responsive">
                                <table class="table table-striped table-bordered zero-configuration table-sm" id="vendortrans_table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Amount Transacted</th>
            <th>Transaction Type</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <!-- Data will be dynamically loaded here -->
    </tbody>
</table>

                                </div>
                            </div>
                        </div>
                    </div>
               </div> 
              
          <div class="row">
            <div class="col-lg-12 col-sm-12">
                <div class="card">
                    <div class="card-body">  
                      <h4 class="card-title">Purchase Detailed Report</h4>  <!-- Items Report Form -->
                        <form id="purchasesreport">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="start_date">Start Date:</label>
                                        <input type="datetime-local" class="form-control" id="start_date" name="start_date" required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="end_date">End Date:</label>
                                        <input type="datetime-local" class="form-control" id="end_date" name="end_date" required>
                                    </div>
                                </div>
                                <div class="col-md-4 d-flex align-items-end">
                                    <button type="submit" class="btn btn-primary">Generate Report</button>
                                </div>
                            </div>
                        </form>

                      <!-- Items Report Table -->
                       <div class="active-member">
                          <div class="table-responsive">
                             <table class="table table-striped table-bordered table-sm" id="purchaseTable" >
                              <thead>
                                <tr>
                                  <th>Item Name</th>
                                  <th>Purchase Price</th>
                                  <th>Quantity</th>
                                  <th>Subtotal</th>
                                </tr>
                              </thead>
                              
                              <tbody></tbody>
                             <tfoot>
    <th colspan="3">Total Amount: <span id="totalAmount"></span></th>
</tfoot>

                            </table>
                          </div>
                        </div>
                      </div>
                  </div>
             </div>
        </div>     
                    
         <div class="modal fade" id="addPurchaseModal" tabindex="-1" role="dialog" aria-labelledby="addPurchaseModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addPurchaseModalLabel">Add Purchase</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="searchInput" class="col-form-label">Search:</label>
                        <input type="text" class="form-control" id="searchInput">
                    </div>
                </form>
                <div id="searchResults" style="display: none;">
                    <table class="table table-striped" id="resultsTable">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Unit</th>
                                <th>Buying Price</th>
                                <th>Quantity</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Search results will be appended here -->
                        </tbody>
                    </table>
                </div>
            </div>
           
        </div>
    </div>
</div>

               
                <!-- Send To Shop Modal -->
                   <div class="modal fade" id="ShopModal">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">

                        <div class="modal-body">
                        
                              <form class="justify-content-between" method="POST">
                                  <input type="text" class="form-control" id="search_text" name="search_text" placeholder="Search Here">
                                  <button type="submit" class="btn"></button>
                                  <span class="lnr lnr-cross" id="close_search" title="Close Search"></span>
                                  <br/>
                                   <div id="result">
                                     
                                   </div>
				              </form>
                         
                           </div>
                     

                    </div>
                </div>
            </div>
               
        
                
<!-- Modal Structure -->


<!-- Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog" aria-labelledby="paymentModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form id="paymentForm">
        <div class="modal-header">
          <h5 class="modal-title" id="paymentModalLabel">Manage Payments</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="paymentAmount">Amount:</label>
            <input type="number" class="form-control" id="paymentAmount" name="paymentAmount" required>
          </div>
          <div class="form-group">
            <label for="paymentType">Payment Type:</label>
            <select class="form-control" id="paymentType" name="paymentType">
              <option value="debit">Payment</option>
            </select>
          </div>
          <input type="hidden" id="vendorId" name="vendorId"> <!-- Hidden input field for vendorId -->
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary" id="submitPayment">Submit</button>
        </div>
      </form>
    </div>
  </div>
</div>

               
               
        <!-- Start Of Send To Shop Items Modal -->
<div class="modal fade" id="shopite" tabindex="-1" role="dialog" aria-labelledby="shopiteLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="shopiteLabel">Purchase Order Details</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="table-responsive">
          <table class="table table-striped table-bordered zero-configuration table-sm" id="bootstrap-data-table-export">
            <thead>
              <tr>
                <th scope="col">Id</th>
                <th scope="col">Name</th>
                <th scope="col">Category</th>
                <th scope="col">Quantity</th>
                <th scope="col">Unit</th>
                <th scope="col">Action</th>
              </tr>
            </thead>
            <tbody id="cartBody">
              <!-- Cart items will be dynamically appended here -->
              <?php
              if (isset($_SESSION['purchaseCart'])) {
                  foreach ($_SESSION['purchaseCart'] as $index => $item) {
                      echo "<tr data-index='$index'>
                              <td>{$item['id']}</td>
                              <td>{$item['name']}</td>
                              <td>{$item['category']}</td>
                              <td>{$item['quantity']}</td>
                              <td>{$item['unit']}</td>
                              <td>
                                  <button type='button' class='btn btn-danger btn-sm remove-from-cart' data-index='$index'>Remove</button>
                              </td>
                            </tr>";
                  }
              }
              ?>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="5" class="text-right">
                  <button type="button" class="btn btn-warning btn-sm clear-cart">Clear All</button>
                </td>
              </tr>
            </tfoot>
          </table>
          <form id="edit-form">
            <div class="container mt-5">
              <div class="mb-3">
                <label for="invoice_id" class="form-label">Transaction ID</label>
                <input type="text" class="form-control" id="invoice_id">
              </div>
              <div class="mb-3">
                <label for="vendorSelect" class="form-label">Select Vendor</label>
                <select id="vendorSelect" class="form-control selectpicker" data-live-search="true" title="Choose Vendor">
                  <!-- Options will be populated via AJAX -->
                </select>
              </div>
              <button type="button" class="btn btn-success btn-sm" id="receiveProductsBtn">Receive Products</button>
              <div id="errorMessage" class="alert alert-danger mt-3" style="display: none;"></div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- End Of Send To Shop Items Modal -->

<!-- Add Stock Modal -->
<div class="modal fade" id="basicModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body">
        <div class="card">
          <div class="card-body">
            <div class="input-group icons">
              <div class="input-group-prepend">
                <span class="input-group-text bg-transparent border-0 pr-1 pr-sm-2" id="basic-addon1">
                  <i class="mdi mdi-magnify"></i>
                </span>
              </div>
              <input type="search" class="form-control rounded" placeholder="Search Dashboard" aria-label="Search Dashboard">
              <div class="drop-down animated flipInX d-md-none">
                <form action="#">
                  <input type="text" class="form-control" placeholder="Search">
                </form>
              </div>
            </div>
            <p></p>
            <h4 class="card-title">Product Details</h4>
            <p></p>
            <div class="basic-form">
              <form>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Product Name</label>
                    <input type="text" class="form-control" placeholder="Product Name" required>
                  </div>
                  <div class="form-group col-md-6">
                    <label>Company</label>
                    <input type="text" class="form-control" placeholder="Company" required>
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Buying Price</label>
                    <input type="number" class="form-control" placeholder="Buying Price" required>
                  </div>
                  <div class="form-group col-md-6">
                    <label>Selling Price</label>
                    <input type="number" class="form-control" placeholder="Selling Price" required>
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Quantity</label>
                    <input type="number" class="form-control" placeholder="Quantity" required>
                  </div>
                  <div class="form-group col-md-4">
                    <label>Location</label>
                    <select id="inputState" class="form-control" required>
                      <option selected>Choose...</option>
                      <option>Store</option>
                      <option>Shop</option>
                    </select>
                  </div>
                </div>
                <div class="form-group col-md-6">
                  <label>Extra</label>
                  <input type="text" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-dark">Submit</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- End Of Add Product Modal -->

<!-- Start Of Add Vendor Modal -->
<div class="modal fade" id="vendite">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="dropdown-content-body-sm">
        <div class="card-sm">
          <div class="card-body">
            <div class="input-group icons">
              <div class="input-group-prepend">
                <span class="input-group-text bg-transparent border-0 pr-1 pr-sm-2" id="basic-addon1">
                  <i class="mdi mdi-magnify"></i>
                </span>
              </div>
              <input type="search" class="form-control rounded" placeholder="Search Dashboard" aria-label="Search Dashboard">
              <div class="drop-down animated flipInX d-md-none">
                <form action="#">
                  <input type="text" class="form-control" placeholder="Search">
                </form>
              </div>
            </div>
            <p></p>
            <h4 class="card-title">Vendor Details</h4>
            <p></p>
            <div class="basic-form">
              <form id="vend_details">
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Vendor Name</label>
                    <input type="text" name="vendor_name" id="vendor_name" class="form-control" placeholder="Vendor Name" required>
                  </div>
                  <div class="form-group col-md-6">
                    <label>Company</label>
                    <input type="text" name="company" id="company" class="form-control" placeholder="Company" required>
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Vendor Address</label>
                    <input type="text" name="address" id="address" class="form-control" placeholder="Address/Location" required>
                  </div>
                  <div class="form-group col-md-6">
                    <label>Vendor Phone</label>
                    <input type="text" name="phone_number" id="phone_number" class="form-control" placeholder="Phone Number" required>
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Email</label>
                    <input type="email" name="email" id="email" class="form-control" placeholder="Email" required>
                  </div>
                </div>
                <button type="submit" class="btn btn-dark">Submit</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- End Of Add Vendor Modal -->
 
<!-- Add Stock Modal -->
<div class="modal fade" id="basicModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body">
        <div class="card">
          <div class="card-body">
            <div class="input-group icons">
              <div class="input-group-prepend">
                <span class="input-group-text bg-transparent border-0 pr-1 pr-sm-2" id="basic-addon1">
                  <i class="mdi mdi-magnify"></i>
                </span>
              </div>
              <input type="search" class="form-control rounded" placeholder="Search Dashboard" aria-label="Search Dashboard">
              <div class="drop-down animated flipInX d-md-none">
                <form action="#">
                  <input type="text" class="form-control" placeholder="Search">
                </form>
              </div>
            </div>
            <p></p>
            <h4 class="card-title">Product Details</h4>
            <p></p>
            <div class="basic-form">
              <form>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Product Name</label>
                    <input type="text" class="form-control" placeholder="Product Name" required>
                  </div>
                  <div class="form-group col-md-6">
                    <label>Company</label>
                    <input type="text" class="form-control" placeholder="Company" required>
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Buying Price</label>
                    <input type="number" class="form-control" placeholder="Buying Price" required>
                  </div>
                  <div class="form-group col-md-6">
                    <label>Selling Price</label>
                    <input type="number" class="form-control" placeholder="Selling Price" required>
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Quantity</label>
                    <input type="number" class="form-control" placeholder="Quantity" required>
                  </div>
                  <div class="form-group col-md-4">
                    <label>Location</label>
                    <select id="inputState" class="form-control" required>
                      <option selected>Choose...</option>
                      <option>Store</option>
                      <option>Shop</option>
                    </select>
                  </div>
                </div>
                <div class="form-group col-md-6">
                  <label>Extra</label>
                  <input type="text" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-dark">Submit</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- End Of Add Product Modal -->

<!-- Start Of Add Vendor Modal -->
<div class="modal fade" id="vendite">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="dropdown-content-body-sm">
        <div class="card-sm">
          <div class="card-body">
            <div class="input-group icons">
              <div class="input-group-prepend">
                <span class="input-group-text bg-transparent border-0 pr-1 pr-sm-2" id="basic-addon1">
                  <i class="mdi mdi-magnify"></i>
                </span>
              </div>
              <input type="search" class="form-control rounded" placeholder="Search Dashboard" aria-label="Search Dashboard">
              <div class="drop-down animated flipInX d-md-none">
                <form action="#">
                  <input type="text" class="form-control" placeholder="Search">
                </form>
              </div>
            </div>
            <p></p>
            <h4 class="card-title">Vendor Details</h4>
            <p></p>
            <div class="basic-form">
              <form id="vend_details">
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Vendor Name</label>
                    <input type="text" name="vendor_name" id="vendor_name" class="form-control" placeholder="Vendor Name" required>
                  </div>
                  <div class="form-group col-md-6">
                    <label>Company</label>
                    <input type="text" name="company" id="company" class="form-control" placeholder="Company" required>
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Vendor Address</label>
                    <input type="text" name="address" id="address" class="form-control" placeholder="Address/Location" required>
                  </div>
                  <div class="form-group col-md-6">
                    <label>Vendor Phone</label>
                    <input type="text" name="phone_number" id="phone_number" class="form-control" placeholder="Phone Number" required>
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label>Email</label>
                    <input type="email" name="email" id="email" class="form-control" placeholder="Email" required>
                  </div>
                </div>
                <button type="submit" class="btn btn-dark">Submit</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- End Of Add Vendor Modal -->

            <!-- #/ container -->
        </div>
        <!--**********************************
            Content body end
        ***********************************-->
        
        
        <!--**********************************
            Footer start
        ***********************************-->
        <div class="footer">
            <div class="copyright">
                <p>Copyright &copy; Designed & Developed by <a href="https://kakashitech.com">Kakashi Tech</a></p>
            </div>
        </div>
        <!--**********************************
            Footer end
        ***********************************-->
    </div>
    <!--**********************************
        Main wrapper end
    ***********************************-->

    <!--**********************************
        Scripts
***********************************-->
     <!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <!-- Bootstrap 4 JS -->
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="./quixlab/plugins/jqueryui/js/jquery-ui.min.js"></script>
<script src="./quixlab/plugins/moment/moment.min.js"></script>
<script src="./quixlab/plugins/fullcalendar/js/fullcalendar.min.js"></script>
<!-- FullCalendar -->

<!-- Other scripts ... -->
<script src="./quixlab/plugins/sweetalert2/dist/sweetalert2.min.js"></script>
<script src="./quixlab/plugins/chart.js/Chart.bundle.min.js"></script>
<script src="./quixlab/plugins/circle-progress/circle-progress.min.js"></script>
<script src="./quixlab/plugins/d3v3/index.js"></script>
<script src="./quixlab/plugins/topojson/topojson.min.js"></script>
<script src="./quixlab/plugins/datamaps/datamaps.world.min.js"></script>
<script src="./quixlab/plugins/raphael/raphael.min.js"></script>
<script src="./quixlab/plugins/morris/morris.min.js"></script>
<script src="./quixlab/plugins/moment/moment.min.js"></script>
<script src="./quixlab/plugins/pg-calendar/js/pignose.calendar.min.js"></script>
<script src="./quixlab/plugins/chartist/js/chartist.min.js"></script>
<script src="./quixlab/plugins/chartist-plugin-tooltips/js/chartist-plugin-tooltip.min.js"></script>
<script src="./quixlab/js/custom.min.js"></script>
<script src="./quixlab/js/settings.js"></script>
<script src="./quixlab/js/gleek.js"></script>
<script src="./quixlab/js/styleSwitcher.js"></script>
<!-- ... -->

<!-- DataTables -->
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
<script src="./quixlab/plugins/tables/js/dataTables.bootstrap4.min.js"></script>
<script src="./quixlab/js/data-table/dataTables.buttons.min.js"></script>
<script src="./quixlab/js/data-table/buttons.flash.min.js"></script>
<script src="./quixlab/js/data-table/jszip.min.js"></script>
<script src="./quixlab/js/data-table/pdfmake.min.js"></script>
<script src="./quixlab/js/data-table/vfs_fonts.js"></script>
<script src="./quixlab/js/data-table/buttons.html5.min.js"></script>
<script src="./quixlab/js/data-table/buttons.print.min.js"></script>
<script src="./quixlab/js/data-table/datatables-init.js"></script>

<!-- Other scripts ... -->
<script src="./quixlab/js/plugins-init/chartjs-init.js"></script>
<script src="./quixlab/js/dashboard/dashboard-1.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>

  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>

     <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


  <script>
 //Add Stock Modal 
 $('#addstock').click(function(){
   $('#basicModal').modal();
 });
//Send stock to Shop  
 $('#sendshop').click(function(){
   $('#ShopModal').modal();
 });
// Items To Send
  $('#storecart').click(function(){
    $('#shopite').modal();
  });    
// Add Vendor
  $('#vendor').click(function(){
    $('#vendite').modal();
  });    
 </script>
 
  <script>
		$(document).ready(function() {
			// Add event listener to form submit button
			$('#vend_details').on('submit', function(event) {
				event.preventDefault(); // Prevent default form submission behavior
              
             

				// Serialize form data
				var formData = $(this).serialize();
              
				// Send AJAX request to server
				$.ajax({
					url: './database/vendors.kts.php', // PHP script to handle the request
					type: 'POST',
					data: formData,
					success: function(response) {
                        // Display the response from the PHP script
                        alert(response);

                        // Clear the form input fields
                        $('#vend_details')[0].reset();
                      },
					error: function(xhr, status, error) {
						// Handle errors
						console.log(xhr.responseText);
					}
				});
			});
		});
	
  </script>
<!-- Start of delete vendor -->
 <script>
  $(document).ready(function() {
    function loadData() {
      $.ajax({
        url: "database/vendor_list.kts.php",
        type: "POST",
        success: function(data) {
          $("#vendor_table").html(data);
        }
      });
    }
    loadData();
   $(document).on("click", ".delete_vendor", function(){
  var vendor_id = $(this).data("id");
  if (confirm("Are you sure you want to delete this vendor?")) {
    $.ajax({
      url: "database/delete_vendor.kts.php",
      type: "POST",
      data: { vendor_id: vendor_id },
      success: function(data){
        loadData();
      }
    });
  }
});

  });
</script>

	<!-- End of delete vendor -->
	<!-- Start of delete vendor Transaction -->

<script>
 
    // Load data on page load
    $(document).ready(function() {
        // Fetch data from the server using Ajax
$.ajax({
    url: 'database/delvendortrans.kts.php',
    method: 'GET',
    dataType: 'json',
    success: function(data) {
        // Initialize DataTable with fetched data
        const table = $('#vendortrans_table').DataTable({
            dom: 'Bfrtip',
            buttons: [
                'copyHtml5',
                'excelHtml5',
                'csvHtml5',
                'pdfHtml5',
                'print'
            ],
            data: data,
            columns: [
                { data: "vendor_name" },
                { data: "amount_transacted" },
                { data: "transaction_type" },
                {
                    // Add a column for the "Delete" button
                    data: null,
                    render: function (data, type, row) {
                        return "<button class='delete_trans btn btn-danger' data-id='" + row.id + "'>Delete</button>";
                    }
                }
            ]
        });
    },
    error: function(xhr, status, error) {
        console.error('Error fetching data:', error);
    }
});

    });
$(document).on("click", ".delete_trans", function() {
    var transaction_id = $(this).data("id");

    // Use SweetAlert for confirmation
    Swal.fire({
        title: 'Are you sure?',
        text: 'You won\'t be able to revert this!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            // User confirmed, proceed with deletion
            $.ajax({
                url: "database/delete_vendortrans.kts.php",
                type: "POST",
                data: { transaction_id: transaction_id },
                success: function(data) {
                    // Reload data after deletion
                   location.reload();
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting vendor transaction:', error);
                }
            });
        }
    });
});
</script>

	<script>
	$(document).ready(function() {
    $('#submitPayment').click(function() {
        var vendorId = $('#vendorId').val();
        var paymentAmount = $('#paymentAmount').val();
        var paymentType = $('#paymentType').val();
       
        $.ajax({
            type: 'POST',
            url: 'database/vendor_payment.kts.php',
            data: {
                vendorId: vendorId,
                paymentAmount: paymentAmount,
                paymentType: paymentType
            },
            success: function(response) {
                alert(response);
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert('Error processing payment');
            }
        });
    });
});
  </script>
  <script>

    $(document).ready(function(){
        $('#search_text').keyup(function(){
            var txt = $(this).val();
            if (txt != ''){
                $.ajax({
                    url:"./database/fetch.kts.php",
                    method: "post",
                    data:{search:txt},
                    dataType:"text",
                    success:function(data)
                    {
                        $('#result').html(data);
                    }
                });
            }
            else{
                $('#result').html('');
            }
		
		});
    });
		

    
</script>
 
 <script>
    $(document).ready(function () {
        // Initialize DataTable
        const table = $('#purchaseTable').DataTable({
            dom: 'Bfrtip',
            buttons: [
                'copyHtml5',
                'excelHtml5',
                'csvHtml5',
                'pdfHtml5',
                'print'
            ],
            columns: [
                { data: "productname" },
                { data: "price" },
                { data: "quantity" },
                { data: "subtotal" }
            ]
        });

        // Handle form submission without page reload
        $('#purchasesreport').submit(function (event) {
            event.preventDefault();

            // Get form data
            const formData = $(this).serialize();

            // AJAX request to server
            $.ajax({
                url: 'database/purchasereport.kts.php',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function (response) {
                    // Clear existing rows
                    table.clear().draw();

                    // Add new rows
                    table.rows.add(response).draw();

                    // Calculate and display total
                    const totalAmount = response.reduce((total, row) => total + parseFloat(row.subtotal || 0), 0);
                    $('#totalAmount').text(totalAmount.toFixed(2)); // Assuming two decimal places
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseText);
                }
            });

            // Prevent form submission from reloading the page
            return false;
        });
    });
</script>

  
   <script>
   function redirectToPage(url) {
    window.location.href = url;
    }
  </script> 
<script>
      $(document).ready(function () {
    // Function to fetch and display vendor debts
    function fetchVendorDebts() {
        $.ajax({
            url: 'database/fetch_vendor_debts.kts.php',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                $('#vendorDebtsTable tbody').empty();
                if (data.length > 0) {
                    data.forEach(function (debt) {
                        var row = '<tr>' +
                            '<td>' + debt.vendor_name + '</td>' +
                            '<td>' + debt.amount_owed + '</td>' +
                            '<td><button type="button" class="btn btn-primary managePaymentBtn" data-vendor-id="' + debt.vendor_id + '">Manage Payments</button></td>' +
                            '</tr>';
                        $('#vendorDebtsTable tbody').append(row);
                    });
                } else {
                    var emptyRow = '<tr><td colspan="3">No vendor debts found.</td></tr>';
                    $('#vendorDebtsTable tbody').append(emptyRow);
                }
            },
            error: function (xhr, status, error) {
                console.error('Error fetching vendor debts:', error);
            }
        });
    }

    // Call the fetchVendorDebts function when the page loads
    fetchVendorDebts();

    // Event listener for "Manage Payments" button click
    $(document).on('click', '.managePaymentBtn', function () {
        var vendorId = $(this).data('vendor-id'); // Get the vendor ID from the button's data attribute
        $('#vendorId').val(vendorId); // Set the vendor ID in the hidden input field
        $('#paymentModal').modal('show'); // Show the payment modal
    });
});

    </script>
  <script>

    $(document).ready(function() {
    $('#addPurchaseCard').on('click', function() {
        $('#addPurchaseModal').modal('show');
    });
});

    
    </script>
<script>
    $(document).ready(function() {
        $('#searchInput').on('keyup', function() {
            let query = $(this).val().trim(); // Trim whitespace around the input
            if (query.length > 0) {
                $.ajax({
                    url: './database/searchpurchases.kts.php', // URL to the PHP file that handles the search
                    method: 'POST',
                    dataType: 'json', // Expect JSON response from the server
                    data: { query: query },
                    success: function(response) {
                        try {
                            // Clear previous results
                            $('#resultsTable tbody').empty();

                            // Check if data is not empty
                            if (response.length > 0) {
                                $('#searchResults').show(); // Show search results div
                                // Iterate through each result and append to the table
                                $.each(response, function(index, row) {
                                    $('#resultsTable tbody').append(
                                        `<tr>
                                            <td>${row.name}</td>
                                            <td>${row.unit}</td>
                                            <td><input type='text' class='form-control buying-price' value='${row.buying_price}'></td>
<td>
    <input type='number' class='form-control quantity' step='any'>
</td>                                            <td><button class='btn btn-success add-to-cart' data-id='${row.id}' data-availability='${row.availability}' data-category='${row.category}'data-unit='${row.unit}' data-name='${row.name}'>Add to Cart</button></td>
                                        </tr>`
                                    );
                                });
                            } else {
                                // If no results found, show message in table body
                                $('#resultsTable tbody').html("<tr><td colspan='4'>No results found</td></tr>");
                            }
                        } catch (error) {
                            console.error('Error parsing JSON:', error); // Log any JSON parsing errors
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error:', error); // Log any AJAX errors
                    }
                });
            } else {
                $('#searchResults').hide(); // Hide search results div if input length <= 1
            }
        });

        // Event handler for adding to cart
        $('#resultsTable').on('click', '.add-to-cart', function() {
            let id = $(this).data('id');
            let availability = $(this).data('availability');
            let category = $(this).data('category');
            let name = $(this).data('name');
            let unit = $(this).data('unit');
            let quantity = $(this).closest('tr').find('.quantity').val();
            let buyingPrice = $(this).closest('tr').find('.buying-price').val(); // Fetch buying price from input field

            // Create an object with item details
            let item = {
                id: id,
                name: name,
                unit: unit,
                category: category,
                buyingPrice: buyingPrice,
                quantity: quantity,
                availability: availability
            };

            // Send item data to PHP script to add to session cart
            $.ajax({
                url: './database/addtopurchase.kts.php',
                method: 'POST',
                data: { item: item },
                success: function(response) {
                    alert('Item added to cart: ' + name);
                    updateCartDisplay();
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error); // Log any AJAX errors
                }
            });
        });

        // Function to update cart display
        function updateCartDisplay() {
            $.ajax({
                url: './database/get_cart_items.kts.php', // PHP script to fetch current session cart items
                method: 'GET',
                dataType: 'html', // Expect HTML response to directly append to cart body
                success: function(response) {
                    $('#cartBody').html(response); // Replace current cart items with updated items
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error); // Log any AJAX errors
                }
            });
        }

        // Handle remove item from cart
            $('#bootstrap-data-table-export').on('click', '.remove-from-cart', function() {
                var index = $(this).data('index');
                $.ajax({
                    url: './database/removefrompurchases.kts.php',
                    method: 'POST',
                    data: { index: index },
                    success: function(response) {
                        var res = JSON.parse(response);
                        if (res.status === 'success') {
                            updateCartDisplay(); // Update cart display after removing item
                            toastr.success(res.message); // Show success message
                        } else {
                            toastr.error(res.message); // Show error message
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error:', error); // Log any AJAX errors
                        toastr.error('Failed to remove item from cart.');
                    }
                });
            });


        $('.clear-cart').click(function() {
            $.ajax({
                url: './database/clear_cart.kts.php',
                method: 'POST',
                success: function(response) {
                    var res = JSON.parse(response);
                    if (res.status === 'success') {
                        updateCartDisplay(); // Update cart display after clearing cart
                        toastr.success(res.message); // Show success message
                    } else {
                        toastr.error(res.message); // Show error message
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error); // Log any AJAX errors
                    toastr.error('Failed to clear cart.');
                }
            });
        });

       
    });
</script>



   <script>
    $(document).ready(function() {
      // Initialize Bootstrap Select
      $('.selectpicker').selectpicker();

      // Fetch vendors and populate the select
      function fetchVendors() {
        $.ajax({
          url: './database/fetch_sup.kts.php',
          type: 'GET',
          dataType: 'json',
          success: function(response) {
            if (response.status === 'success') {
              var $select = $('#vendorSelect');
              $select.empty(); // Clear existing options
              $select.append('<option value="" disabled selected>Select Vendor</option>'); // Add default option
              response.vendors.forEach(function(vendor) {
                $select.append(new Option(vendor.company, vendor.vendor_id));
              });
              $select.selectpicker('refresh'); // Refresh Bootstrap Select
              $('#errorMessage').hide(); // Hide error message if data is successfully loaded
            } else if (response.status === 'error') {
              $('#errorMessage').text(response.message).show(); // Show error message
            }
          },
          error: function(xhr, status, error) {
            $('#errorMessage').text('Error fetching vendors: ' + xhr.responseText).show(); // Show error message
          }
        });
      }

      fetchVendors();
$('#receiveProductsBtn').click(function(event) {
  event.preventDefault(); // Prevent the default form submission

  var invoiceId = $('#invoice_id').val();
  var vendorId = $('#vendorSelect').val();

  if (!invoiceId || !vendorId) {
    swal("Error", "Please fill in all fields before submitting.", "error");
    return;
  }

$.ajax({
  url: './database/receive_purchases.kts.php',
  method: 'POST',
  dataType: 'json',
  data: {
    invoice_id: invoiceId,
    vendor_id: vendorId
  },
  success: function(response) {
    if (response.status === 'success') {
      updateCartDisplay(); // Clear the cart display after receiving products
      Swal.fire({
        icon: 'success',
        title: 'Success',
        text: response.message,
        showConfirmButton: false,
        timer: 2000
      });
    } else {
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: response.message
      });
    }
  },
  error: function(xhr, status, error) {
    console.error('Error:', error); // Log any AJAX errors
    Swal.fire({
      icon: 'error',
      title: 'Error',
      text: 'Failed to receive products.'
    });
  }
});

});

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