<?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>Jacyjoka Apartment</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="./quixlab/plugins/tables/css/datatable/dataTables.bootstrap4.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" />

</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
        ***********************************-->
   <?php


// Define arrays for each user role and the corresponding allowed links
$managerLinks = array(
    "orders.php", 
    "table.php", 
    "payments.php", 
    "reports.php", 
    "purchases.php", 
    "employee.php", 
    "reg-customer.php", 
    "inventory.php"
);

$cashierLinks = array(
    "orders.php", 
    "reg-customer.php", 
    "sales.php"
);

$receptionistLinks = array(
    "orders.php", 
    "reg-customer.php", 
    "payments.php", 
    "sales.php"
);


// Check if user is logged in and their role is set in the session
if(isset($_SESSION['type'])) {
    $role = $_SESSION['type'];
    
    // Assign the corresponding links based on the user role
    switch($role) {
        case "Manager":
            $links = $managerLinks;
            break;
        case "Cashier":
            $links = $cashierLinks;
            break;
        case "Receptionist":
            $links = $receptionistLinks;
            break;
        default:
            $links = array();
            break;
    }
} else {
    // Redirect user to login page if they are not logged in
    header("Location: login.php");
    exit();
}

?>

<div class="nk-sidebar">           
    <div class="nk-nav-scroll">
        <ul class="metismenu" id="menu">
            <li class="nav-label">Dashboard</li>
            <li>
                <a class="has-arrow" href="javascript:void()" aria-expanded="false">
                    <i class="icon-speedometer menu-icon"></i><span class="nav-text">Dashboard</span>
                </a>
                <ul aria-expanded="false">
                    <li><a href="index.php">Dashboard</a></li>
                    <!-- <li><a href="./index-2.html">Home 2</a></li> -->
                </ul>
            </li>
            <?php 
               foreach($links as $link) {
    $linkText = ucfirst(str_replace(".php", "", $link)); // remove .php extension and capitalize first letter
    echo '<li><a href="' . $link . '"><i class="icon-menu menu-icon"></i><span class="nav-text">' . $linkText . '</span></a></li>';
}

            ?>
            <li>
                <a href="logout.php" aria-expanded="false">
                    <i class="icon-lock menu-icon"></i><span class="nav-text">LogOut</span>
                </a>
            </li>
        </ul>
    </div>
</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">
                            <div class="card-body" onclick="redirectToPage('inventory.php');">
                                <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>Quantity</th>
                                  <th>Purchase Price</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>     
                    
         
               
                <!-- 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 -->
<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>

               
               
                <!-- End Of Send To Shop Modal -->
                <!-- Start Of Send To shop Items  Modal-->
                <div class="modal fade" id="shopite">
                  <div class="modal-dialog" role="document">
                    <div class="modal-content">
                       <div class="dropdown-content-body-sm">
                                    <div class="card-sm">
                                      <div class="card-body">
                                          <h4 class="card-title">Purchase Order Details</h4>
                                          <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">Company</th>
                                                        <th scope="col">Quantity</th>
                                                        <th scope="col">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                
                                                <?php
                               
                               $total= 0;
                               $amount= 0;   
                               $balance =0;   
                                
                               $output = '';
                               
                               
                               ?>
                                     
                                           
                                       <?php     if (!empty($_SESSION['p_order'])){
                                  
                                   foreach($_SESSION['p_order'] as $key =>  $value){ ?>
                                            <tr>
                                               
                                              
                                               <td><?php echo $value['id'];?></td>
                                                <td><?php echo $value['name'];?></td>
                                                <td><?php echo $value['company'];?></td>
                                                <td><?php echo $value['qty'];?></td>
                                               
                                                <td>
                                                  <a href="purchases.php?action=remove&id=<?php echo $value['id'];?>">
                                                  <button class="btn btn-danger btn-sm" type="button">Remove</button></a>
                                               </td>
                                               
                                            </tr>
                                           <?php 
																		
											} }?>
                                           
                                            </tbody>
                                            <thead>
                                            <tr>
                                                <th scope="col">#</th>
                                                <th scope="col"></th>
                                                <th scope="col"></th>
                                                <th scope="col"></th>
                                                <th scope="col"><a href="purchases.php?action=clearall" >
                                                <button type="button" class="btn btn-warning btn-sm" >Clear All</button></a>
                                                </th>
                                            </tr>
                                            <tr>
                                                <th scope="col">#</th>
                                                <th scope="col"></th>
                                                <th scope="col"></th>
                                                <th scope="col"></th>
                                                <th scope="col"><a href="./database/topurchase.kts.php" >
                                                <button type="submit" name="topurchase" class="btn btn-warning btn-sm" >Send To Vendor</button></a>
                                                </th>
                                            </tr>
                                           
                                        </thead>
                                            </table>
                                          </div>
                                      </div>
                                    </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></div>
                                <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>Sellling 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="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 aAdd Poduct 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></div>
                                <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" class="form-control" name="company" id="company" 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 -->

            </div>
            <!-- #/ 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>

<!-- 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>
 //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>
  
</body>

</html>