<?php
ob_start();
include("db/cn.php");
if(isset($_SESSION['user_name']) && isset($_SESSION['user_role'])&& isset($_SESSION['outlet_name'])
&& isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
	$outlet_address = $_SESSION['outlet_address'];
	$outlet_name = $_SESSION['outlet_name'];
}
//$cr_id = $_GET["cr_id"];
@$customer_name = $_GET["customer_name"];
//echo $cr_nickname;
$rec =  mysqli_query($connection,"select * from cdetail where customer_name = '$customer_name' && paid_by = 'credit' ");
$row1 = mysqli_fetch_array($rec);
//echo $row1["order_id"];
@$order_id = $row1["order_id"];


$date_time1 = date("Y-m-d");
$rec10 = mysqli_query($connection, "SELECT order_id, net_amount,discount_amount FROM log_user_sales WHERE customer_name = '$customer_name' && login_user = '$userName' AND user_role = '$userRole' AND paid_by = 'credit'  && r_order_id = '' GROUP BY order_id ");

if ($rec10) {
    $total_sales = 0;
    while ($row3 = mysqli_fetch_array($rec10)) {
        $total_sales += $row3['discount_amount'];
    }
    echo "";
    if (mysqli_num_rows($rec10) == 0) {
        echo "";
    }
} else {
    echo "Error executing query: " . mysqli_error($connection);
}
//------------------------------------------------------
$date_time1 = date("Y-m-d");
$rec11 = mysqli_query($connection, "SELECT order_id, discount_amount FROM log_user_sales WHERE customer_name = '$customer_name'  AND paid_by = 'credit' && status = 'refund' GROUP BY order_id ");

if ($rec11) {
    $total_sales_return = 0;
    while ($row31 = mysqli_fetch_array($rec11)) {
        $total_sales_return += $row31['discount_amount'];
    }
    echo "";
    if (mysqli_num_rows($rec11) == 0) {
        echo "";
    }
} else {
    echo "Error executing query: " . mysqli_error($connection);
}

//------------------------------------------------------
$cash_out = mysqli_query($connection, "SELECT SUM(amount) AS total_amount1 FROM credit_paid where user_name = '$userName' && user_role = '$userRole' && cr_name = '$customer_name'   ");
if ($cash_out) {
    $cash_outdata = mysqli_fetch_array($cash_out);
    if ($cash_outdata && isset($cash_outdata['total_amount1'])) {
        $totalAmount = $cash_outdata['total_amount1'];
        echo "";
    } else {
        echo "";
    }
} else {
    echo "Error executing query: " . mysqli_error($connection);
}

$credit_open = mysqli_query($connection, "SELECT SUM(open_amount) AS total_amount FROM creditor_opening_amount where login_user = '$userName' && user_role = '$userRole' && creditor_name = '$customer_name'  ");
if ($credit_open) {
    $credit_outdata = mysqli_fetch_array($credit_open);
    if ($credit_outdata && isset($credit_outdata['total_amount'])) {
        $totalAmount_credit = $credit_outdata['total_amount'];
        echo "";
    } else {
        echo "";
    }
} else {
    echo "Error executing query: " . mysqli_error($connection);
}


$pos_credit = mysqli_query($connection, "SELECT customer_name, paid_by, order_id, cash_amount FROM log_user_sales where login_user = '$userName' && user_role = '$userRole' && customer_name = '$customer_name' && paid_by = 'credit' GROUP BY order_id ");


if ($pos_credit) {
    $pos_pass_get = 0;
    while ($pos_pass = mysqli_fetch_array($pos_credit)) {
        $pos_pass_get += (int)$pos_pass['cash_amount'];
    }
    echo "";
    if (mysqli_num_rows($pos_credit) == 0) {
        echo "";
    }
} else {
    echo "Error executing query: " . mysqli_error($connection);
}

if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["creditor_paid"])){
$date_time = date("Y-m-d");
	$cr_name = $_POST["cr_name"];
	@$cr_address = $_POST["cr_address"];
	$amount = $_POST["amount"];
	$paid_by = $_POST["paid_by"];
	
	 mysqli_query($connection,"insert into credit_paid(cr_name,amount,paid_by,date_time,user_name,user_role,outlet_name,outlet_address)
values('".$cr_name."','".$amount."','".$paid_by."','".$date_time."','".$userName."','".$userRole."','".$outlet_name."','".$outlet_address."')");

	 echo "<script type='text/javascript'>window.location.href = 'creditor_detail.php?customer_name=$customer_name';</script>";

}
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["creditor_close"])) {
    // Set current date
    $date_time_close = date("Y-m-d");
    
    // Retrieve values from $_POST
    $creditor_name = $_POST["creditor_name"];
    $open_amount = $_POST["opening_cash"]; // Corrected variable name
    $credit_sales = $_POST["credit_sales"];
    
    $credit_received = $_POST["credit_recieved"];
   
    $remain_balance = $_POST["remian_balance"]; // Corrected variable name
    $date_time1 = date("Y-m-d");

    // Check if the creditor already has an entry in the database
    $check_sql = "SELECT * FROM creditor_closing WHERE creditor_name = '$creditor_name'";
    $result = mysqli_query($connection, $check_sql);

    if (mysqli_num_rows($result) > 0) {
        // Update existing record
        $sql = "UPDATE creditor_closing SET 
                    opening_cash = '$open_amount', 
                    credit_sales = '$credit_sales',  
                    credit_recieved = '$credit_received',
                    remain_balance = '$remain_balance', 
                    date_time = '$date_time1', 
                    login_user = '$userName', 
                    user_role = '$userRole', 
                    outlet_name = '$outlet_name', 
                    outlet_address = '$outlet_address' 
                WHERE creditor_name = '$creditor_name'";
    } else {
        // Insert new record
        $sql = "INSERT INTO creditor_closing (
                    creditor_name, opening_cash, credit_sales,
                    credit_recieved, remain_balance, date_time, 
                    login_user, user_role, outlet_name, outlet_address
                ) VALUES (
                    '$creditor_name', '$open_amount', '$credit_sales', 
                    '$credit_received', '$remain_balance', '$date_time1', 
                    '$userName', '$userRole', '$outlet_name', '$outlet_address'
                )";
    }

    // Execute SQL query
    if (mysqli_query($connection, $sql)) {
       echo "<script type='text/javascript'>window.location.href = 'view_creditor.php';</script>";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($connection);
    }
}

if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["creditor_open"])){
$date_time32 = date("Y-m-d");
			$creditor = $_POST["creditor_name"];
			$open_amount = $_POST["open_amount"];
			$paid_by1 = $_POST["paid_by"];
			 
			 mysqli_query($connection,"insert into creditor_opening_amount(creditor_name,open_amount,paid_by,date_time,login_user,user_role,outlet_name,outlet_address)
			 values('".$creditor."','".$open_amount."','".$paid_by1."','".$date_time32."','".$userName."','".$userRole."','".$outlet_name."','".$outlet_address."');");
			 
			  echo "<script type='text/javascript'>window.location.href = 'creditor_detail.php?customer_name=$customer_name';</script>";
}
ob_end_flush();
?>

<!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, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Kashmir Bazar</title>

    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
   <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<style>
body {
    font-family: 'Quicksand', sans-serif;
    
}
		    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
.bg-gradient-primary{
    
	background:#0A4657;
	color:#fff;	
	
	}

.btn-primary{
	background:#0A4657;
	color:#fff;
	 border:1px #0A4657 solid;
	
	}  
.btn-primary:hover{
  
  background:#fff;
  border:1px #0A4657 solid;
	color:#0A4657;
	
	}	 
    .chart-container {
      position: relative;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    canvas {
      max-width: 100%;
      height: auto;
    }
	
	.fa-download:hover{
		color:#953E39;
		}
		
	/* Basic styling */
    .tab {
        display: none;
        padding: 20px;
    }
    .active {
        display: block;
    }
    .tab-buttons {
        display: flex;
    }
    .tab-button {
        cursor: pointer;
        padding: 10px 10px;
        background-color: #ffff;
        border: 1px solid #0A5064;
        border-radius: 5px 5px 0 0;
        margin-right: 5px;
		color:#212529;
		font-weight:700;
    }
    .tab-button.active {
        background-color: #212529;
		color:#fff;
    }

    /* Background colors for tab content */
    #tab1 {
        background-color: #fff;
		color:#212529;
		padding:20px;
    }
    #tab2 {
        color:#212529;
		background-color: ;
    }
    #tab3 {
		color:#212529;
        background-color: ;
    }
    tr{
        color: #353535;
        font-weight: 700;
        background-color: #fff;
    }
    
    label{
        font-weight: 700;
    }
    h3, h4{
        font-weight:700;
        color:#000;
    }
    .btn, .form-control{
        font-weight:700;
    }
    
  </style>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <?php
        include("common/sd.php");
		?>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>

                     <?php include('common/log.php');  ?>
                </nav>
<br />
<div class="container">
<div class="row">
<div class="col-sm-9">
<h3 style="color:#212529;">Receivable Detail <span style="padding:10px; border-radius:7px; text-transform:capitalize; color:#fff;font-size:18px; border:1px solid #0A5064;background:#212529;"><?php echo $customer_name; ?></span></h3>
</div>
<div class="col-sm-3">
<a href="view_creditor.php"><button type="button" class="btn btn-dark"><i class="fa fa-arrow-left"></i></button></a>
<button type="button" class="btn btn-dark btn-sm" data-toggle="modal" data-target="#addPurchaseModal">
               Get
            </button>
            <button type="button" class="btn btn-dark btn-sm" data-toggle="modal" data-target="#addopenPurchaseModal">
              Add Open
            </button>
</div>
</div>
<br />
<div class="container">
<div class="row">
<div class="col-sm-3  text-dark text-capitalize" >
</div>
<div class="col-sm-9"></div>

</div>
</div>
<br /><br />
<div class="container">
<div class="tab-buttons">
    <div class="tab-button active" onclick="openTab(event, 'tab1')">Overview</div>
    <div class="tab-button" onclick="openTab(event, 'tab2')">Credit Recieved</div>
    <div class="tab-button" onclick="openTab(event, 'tab3')">Credit Sales</div>
    <div class="tab-button" onclick="openTab(event, 'tab4')">Credit Sales Return</div>
    <div class="tab-button" onclick="openTab(event, 'tab6')">POS Credit Recieved</div>
</div>
<?php  

@$remain_credit = $total_sales - $totalAmount - $total_sales_return ;
@$remaining = $remain_credit + $totalAmount_credit;
?>
<div class="tab-container">
    <div id="tab1" class="tab active">
    <h4>Overview</h4>
    <br />
    <form method="post" action="creditor_detail.php?customer_name=<?php echo $customer_name; ?>">
    <input type="hidden" value="<?php echo $customer_name; ?>" name="creditor_name" />
    <div class="container ">
        <div class="row" style="padding:20px;background:#fff; box-shadow: 0px 0px 5px 2px #CCC; border-radius:10px;">
            <div class="col-sm-12" style="padding:20px;">
            <table class="table table-hover"  >
            <tr style="color:#8A1218;padding:20px;">
            <td style="font-weight:600;">Opening Cash</td>
            <td style="text-align:right; font-size:19px; font-weight:600;">
             <?php echo isset($totalAmount_credit) ? "Rs ".$totalAmount_credit."" : ""; ?>
            <input type="hidden" value="<?php echo isset($totalAmount_credit) ? "Rs ".$totalAmount_credit."" : ""; ?>" name="opening_cash" />
			</td>
            </tr>
            <tr>
            <td style="font-weight:600;">Credit Sales</td>
            <td style="text-align:right; font-size:19px; font-weight:600;">
            <?php echo isset($total_sales) ? "Rs ".$total_sales."" : ""; ?>
            <input type="hidden" value="<?php echo $total_sales; ?>" name="credit_sales" />
			</td>
            </tr>
             <tr>
            <td style="font-weight:600;">Credit Sales Return</td>
            <td style="text-align:right; font-size:19px; font-weight:600;">
            <?php echo isset($total_sales_return) ? "Rs ".$total_sales_return."" : ""; ?>
            <input type="hidden" value="<?php echo $total_sales_return; ?>" name="credit_sales" />
			</td>
            </tr>
            <tr>
            <td style="font-weight:600;">Credit Recieved</td>
            <td style="text-align:right; font-size:19px; font-weight:600;">
            <?php echo isset($totalAmount) ? "Rs ".$totalAmount."" : ""; ?>
            <input type="hidden" value="<?php echo $totalAmount; ?>" name="credit_recieved" />
			</td>
            </tr>
            <tr>
            <td style="font-weight:600;">POS Credit Recieved</td>
            <td style="text-align:right; font-size:19px; font-weight:600;">
            <?php echo isset($pos_pass_get) ? "Rs ".$pos_pass_get."" : ""; ?>
            <input type="hidden" value="<?php echo $pos_pass_get; ?>" name="pos_credit" />
			</td>
            </tr>
            <tr>
            <td style="font-weight:600;">Remaining Credit</td>
            <td style="text-align:right; font-size:19px; font-weight:600;">
            <?php echo isset($remain_credit) ? "Rs ".$remaining."" : ""; ?>
            <input type="hidden" value="<?php echo $remaining; ?>" name="remian_balance" />
			</td>
            </tr>
                    
            </table>
            <button type="submit" name="creditor_close" class="btn btn-dark">Save</button> 
            </div>
            
            
        </div>
        <br />
        
        
    </div>
     </form>
    
</div>

<div id="tab6" class="tab">
        <h4>POS Credit Recieved</h4>
        <div class="container">
           <div class="row">    
           </div>
           <br />
             <div class="col-sm-12" id="table-container-wrapper">
                 <div class="row">
              <div class="col-sm-4">
    <label for="startDate">Start Date:</label>
    <input  class="form-control" style="width:305px;" type="date" id="startDatePOS">
    </div>
    <div class="col-sm-4">
    <label for="endDate">End Date:</label>
    <input class="form-control" style="width:305px;" type="date" id="endDatePOS">
</div>
<div class="col-sm-4">
     <button type="button" class="btn btn-dark" style="float:right;margin-top:30px;" onclick="downloadTableData('salesTableBody', 'POS_Credit_Received.xlsx')">Download</button>
</div>

</div>
<hr>
               <table class="table table-stripped table-sm text-center">
    <thead>
        <tr style="background:#212529; color:#fff;">
            <td>Date</td>
            <td>ORDER ID</td>
            <td>Amount(Rs)</td>
            <td>Method</td>
            <td>Received By</td>                
        </tr>
    </thead>
    <tbody id="salesTableBody">
        <?php  
        $rec36 = mysqli_query($connection,"SELECT * FROM log_user_sales WHERE customer_name = '$customer_name' AND paid_by = 'credit' GROUP BY order_id");
        while($row36 = mysqli_fetch_array($rec36)){
        ?>
        <tr>
            <td><?php echo $row36['date_time']; ?></td>
            <td><?php echo $row36['order_id']; ?></td>
            <td>Rs. <?php echo $row36['cash_amount']; ?></td>
            <td class="text-capitalize"><?php echo $row36['paid_by']; ?></td>
            <td class="text-capitalize"><?php echo $row36['login_user']; ?></td>
        </tr>
        <?php }?>
    </tbody>
</table>
             </div>
           </div>
          </div>
          

    <div id="tab2" class="tab">
        <h4>Credit Recieved</h4>
        <div class="container">
           <div class="row">    
           </div>
           <br />
             <div class="col-sm-12" id="table-container-wrapper">
                <div class="row">
                    <div class="col-sm-4">
    <label for="startDate">Start Date:</label>
    <input class="form-control" type="date" id="startDateCR">
    </div>
    <div class="col-sm-4">
    <label for="endDate">End Date:</label>
    <input class="form-control"  type="date" id="endDateCR">
</div>
<div class="col-sm-4">
      <button type="button" class="btn btn-dark" style="float:right;margin-top:30px;" onclick="downloadTableData('creditTableBody', 'Credit_Received.xlsx')">Download</button>
                </div>
</div>
                </div> 
                <hr>
                 
               <table class="table table-stripped table-sm text-center">
    <thead>
        <tr style="background:#212529; color:#fff;">
            <td>Date</td>
            <td>Amount(Rs)</td>
            <td>Method</td>
            <td>Received By</td>                
        </tr>
    </thead>
    <tbody id="creditTableBody">
        <?php  
        $rec3 = mysqli_query($connection, "SELECT * FROM credit_paid WHERE cr_name = '$customer_name'");
        while($row3 = mysqli_fetch_array($rec3)) {
        ?>
        <tr>
            <td><?php echo $row3['date_time']; ?></td>
            <td>Rs. <?php echo $row3['amount']; ?></td>
            <td class="text-capitalize"><?php echo $row3['paid_by']; ?></td>
            <td class="text-capitalize"><?php echo $row3['user_name']; ?></td>
        </tr>
        <?php } ?>
    </tbody>
</table>
             </div>
           </div>
          </div>
          
    </div>
    <div id="tab3" class="tab">
        <h4> Credit Sales</h2>
        <div class="container ">
           <div class="row">
     
            
            </div>
           
           <br />
             <div class="col-sm-12" id="table-container-wrapper">
                 <div class="row">
                     <div class="col-sm-4">
    <label for="startDate">Start Date:</label>
    <input class="form-control" type="date" id="startDateCS">
    </div>
    <div class="col-sm-4">
    <label for="endDate">End Date:</label>
    <input class="form-control" type="date" id="endDateCS">
</div>
<div class="col-sm-4">
     <button type="button" class="btn btn-dark" style="float:right;margin-top:30px;" onclick="downloadTableData('orderTableBody', 'Credit_Sales.xlsx')">Download</button>
</div>
</div>
<hr>
               <table class="table table-stripped table-sm text-center">
    <thead>
        <tr style="background:#212529; color:#fff;">
            <td>Date</td>
            <td>Order-ID</td>
            <td>Amount(Rs)</td>
            <td>Method</td>
            <td>By</td>
        </tr>
    </thead>
    <tbody id="orderTableBody">
        <?php 
        $date_time = date("Y-m-d");
        $rec1 = mysqli_query($connection, "SELECT order_id, r_order_id, total_amount, tax_amount, discount_amount, discounted, date_time, paid_by, SUM(net_amount) AS total_product, login_user FROM log_user_sales WHERE login_user = '$userName' AND user_role = '$userRole' AND customer_name = '$customer_name' AND r_order_id = '' GROUP BY order_id");
        while($row2 = mysqli_fetch_array($rec1)) {
        ?>
        <tr>
            <td><?php echo $row2["date_time"]; ?></td>
            <td style="font-weight:700;"><?php echo $row2["order_id"]; ?></td>
            <td>Rs <?php echo $row2["discount_amount"]; ?></td>
            <td style="text-transform:capitalize;"><?php echo $row2["paid_by"]; ?></td>
            <td style="text-transform:capitalize;"><?php echo $row2["login_user"]; ?></td>
        </tr>
        <?php } ?>
    </tbody>
</table>
             </div>
           </div>
          </div>
    </div>

<div class="modal fade" id="addPurchaseModal" tabindex="-1" role="dialog" 
            aria-labelledby="addPurchaseModalLabel" aria-hidden="true" style="margin-top:80px;">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header" style="background:#0A4657;">
                            <h5 class="modal-title text-capitalize text-white font-weight-bold" id="addPurchaseModalLabel">Add Credit Recieved</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 for adding purchase -->
                            <form method="post" action="creditor_detail.php?customer_name=<?php echo $customer_name; ?>" enctype="multipart/form-data">
                            
                                <input type="text" name="cr_name" placeholder="Name" style="background:#0A4657; color:#fff;" value="<?php echo $customer_name; ?>" class="form-control" />
                                <br />
                                <input type="text" name="amount" placeholder="Amount" class="form-control" />
                               <br />
                               <select name="paid_by" class="form-control">
                               <option value="">Select Method </option>
                               <option value="cash" >Cash</option>
                               <option value="bank1">Bank 1</option>
                                    <option value="bank2">Bank 2 </option>
                                    <option value="bank3">Bank 3</option>
                               <option value="other">Other</option>
                               
                               </select>                               
                               <br />
                                <input class="form-control" type="date" name="date_time"  />
                                <br />
                                <button type="submit" name="creditor_paid"  class="btn btn-dark">Enter</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            
            <div id="tab4" class="tab">
        
        <div class="container">
            <h4>Credit Sales Return</h4>
           <div class="row">    
           </div>
           <br />
             <div class="col-sm-12" id="table-container-wrapper">
                 <div class="row">
                     <div class="col-sm-4">
    <label for="startDate">Start Date:</label>
    <input class="form-control" type="date" id="startDateRF">
    </div>
    <div class="col-sm-4">
    <label for="endDate">End Date:</label>
    <input class="form-control" type="date" id="endDateRF">
</div>
<div class="col-sm-4">
    <button type="button" class="btn btn-dark" style="float:right;margin-top:30px;" onclick="downloadTableData('refundTableBody', 'Credit_Sales_Return.xlsx')">Download</button>
</div>
</div>
<hr>
               <table class="table table-stripped table-sm text-center">
    <thead>
        <tr style="background:#212529; color:#fff;">
            <td>Date</td>
            <td>Order-ID</td>
            <td>Sub-total(Rs)</td>
            <td>Discount(Rs)</td>
            <td>Amount(Rs)</td>
            <td>Method</td>
        </tr>
    </thead>
    <tbody id="refundTableBody">
        <?php  
        $rec3 = mysqli_query($connection, "SELECT *, SUM(net_amount) AS netAmounts FROM log_user_sales WHERE customer_name = '$customer_name' AND status = 'refund' GROUP BY r_order_id");
        while($row3 = mysqli_fetch_array($rec3)) {
        ?>
        <tr>
            <td><?php echo $row3['date_time']; ?></td>
            <td style="font-weight:700;"><?php echo $row3['order_id']; ?></td>
            <td>Rs. <?php echo $row3['netAmounts']; ?>.00</td>
            <td><?php echo $row3['discounted']; ?></td>
            <td>Rs. <?php echo $row3['discount_amount']; ?></td>
            <td class="text-capitalize"><?php echo $row3['paid_by']; ?></td>
        </tr>
        <?php } ?>
    </tbody>
</table>
             </div>
           </div>
          </div>
   
            
            <div class="modal fade" id="addopenPurchaseModal" tabindex="-1" role="dialog" 
            aria-labelledby="addPurchaseopenModalLabel" aria-hidden="true" style="margin-top:80px;">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header" style="background:#0A4657;">
                            <h5 class="modal-title text-capitalize text-white font-weight-bold" id="addPurchaseopenModalLabel">Add Opening Amount</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 for adding purchase -->
                            <form method="post" action="creditor_detail.php?customer_name=<?php echo $customer_name; ?>" enctype="multipart/form-data">
                            
                                <input type="hidden" value="<?php echo $customer_name; ?>" name="creditor_name" placeholder="Name" class="form-control" />
                             
                                <input type="text" name="open_amount" placeholder="Amount" class="form-control" />
                               <br />
                               <!-- <input class="form-control" type="date" name="date_time"  />
                                <br />-->
                                <button type="submit" name="creditor_open"  class="btn btn-dark">Enter</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>



            </div>
            <br><br>
            <!-- End of Main Content -->

            <!-- Footer -->
            <?php include("common/main_ft.php");  ?>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>

      <script>
// Download function for each table
function downloadTableData(tableBodyId, filename) {
    const tableBody = document.getElementById(tableBodyId);
    const rows = Array.from(tableBody.querySelectorAll("tr"));
    const data = [];

    // Loop through each row and extract cell data
    rows.forEach(row => {
        const rowData = Array.from(row.querySelectorAll("td")).map(cell => cell.innerText);
        data.push(rowData);
    });

    // Create workbook and worksheet, then download as Excel
    const ws = XLSX.utils.aoa_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    XLSX.writeFile(wb, filename);
}

// Filter function for POS Credit Received table
function filterSalesTableByDate() {
    const startDate = new Date(document.getElementById('startDatePOS').value);
    const endDate = new Date(document.getElementById('endDatePOS').value);
    const rows = document.querySelectorAll('#salesTableBody tr');

    rows.forEach(row => {
        const rowDate = new Date(row.cells[0].innerText);
        row.style.display = (!isNaN(startDate) && rowDate < startDate) || (!isNaN(endDate) && rowDate > endDate) ? 'none' : '';
    });
}

// Filter function for Credit Received table
function filterCreditTableByDate() {
    const startDate = new Date(document.getElementById('startDateCR').value);
    const endDate = new Date(document.getElementById('endDateCR').value);
    const rows = document.querySelectorAll('#creditTableBody tr');

    rows.forEach(row => {
        const rowDate = new Date(row.cells[0].innerText);
        row.style.display = (!isNaN(startDate) && rowDate < startDate) || (!isNaN(endDate) && rowDate > endDate) ? 'none' : '';
    });
}

// Filter function for Credit Sales table
function filterOrderTableByDate() {
    const startDate = new Date(document.getElementById('startDateCS').value);
    const endDate = new Date(document.getElementById('endDateCS').value);
    const rows = document.querySelectorAll('#orderTableBody tr');

    rows.forEach(row => {
        const rowDate = new Date(row.cells[0].innerText);
        row.style.display = (!isNaN(startDate) && rowDate < startDate) || (!isNaN(endDate) && rowDate > endDate) ? 'none' : '';
    });
}

// Filter function for Credit Sales Return table
function filterRefundTableByDate() {
    const startDate = new Date(document.getElementById('startDateRF').value);
    const endDate = new Date(document.getElementById('endDateRF').value);
    const rows = document.querySelectorAll('#refundTableBody tr');

    rows.forEach(row => {
        const rowDate = new Date(row.cells[0].innerText);
        row.style.display = (!isNaN(startDate) && rowDate < startDate) || (!isNaN(endDate) && rowDate > endDate) ? 'none' : '';
    });
}

// Event listeners for each date range filter
document.getElementById('startDatePOS').addEventListener('change', filterSalesTableByDate);
document.getElementById('endDatePOS').addEventListener('change', filterSalesTableByDate);

document.getElementById('startDateCR').addEventListener('change', filterCreditTableByDate);
document.getElementById('endDateCR').addEventListener('change', filterCreditTableByDate);

document.getElementById('startDateCS').addEventListener('change', filterOrderTableByDate);
document.getElementById('endDateCS').addEventListener('change', filterOrderTableByDate);

document.getElementById('startDateRF').addEventListener('change', filterRefundTableByDate);
document.getElementById('endDateRF').addEventListener('change', filterRefundTableByDate);
</script>
<script>
 // Function to switch between tabs
    function openTab(evt, tabName) {
        // Get all elements with class="tab" and hide them
        var tabs = document.getElementsByClassName("tab");
        for (var i = 0; i < tabs.length; i++) {
            tabs[i].style.display = "none";
        }

        // Get all elements with class="tab-button" and remove the class "active"
        var tabButtons = document.getElementsByClassName("tab-button");
        for (var i = 0; i < tabButtons.length; i++) {
            tabButtons[i].classList.remove("active");
        }

        // Show the current tab, and add an "active" class to the button that opened the tab
        document.getElementById(tabName).style.display = "block";
        evt.currentTarget.classList.add("active");
    }
  document.addEventListener("DOMContentLoaded", function () {
    var sidebar = document.getElementById("sidebar");
    var overlay = document.createElement("div");
    overlay.classList.add("overlay");
    document.body.appendChild(overlay);

    function toggleSidebar() {
        sidebar.classList.toggle("hide");
        overlay.classList.toggle("hide");

        var mainContent = document.querySelector(".main-content");
        if (sidebar.classList.contains("hide")) {
            mainContent.style.marginLeft = "0";
        } else {
            mainContent.style.marginLeft = "100px"; // Width of the sidebar
        }
    }

    overlay.addEventListener("click", function () {
        toggleSidebar();
    });

    // Add toggle functionality to navbar toggler
    var navbarToggler = document.querySelector(".navbar-toggler");
    navbarToggler.addEventListener("click", function () {
        toggleSidebar();
    });

    // Automatically hide sidebar on all screen sizes
    // sidebar.classList.add("hide");
    // overlay.classList.add("hide");
    
    // Add class to body to prevent scrolling when sidebar is open
    // document.body.classList.add("noscroll");

    // Check if screen size is larger than a certain threshold (e.g., 768px for desktop screens)
    function checkScreenSize() {
        if (window.innerWidth > 768) {
            sidebar.classList.remove("hide");
            overlay.classList.remove("hide");
        } else {
            sidebar.classList.add("hide");
            overlay.classList.add("hide");
        }
    }

    // Check screen size on initial load and whenever the window is resized
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);
});
 
	</script>
   <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin-2.min.js"></script>

</body>

</html>