File "supplier_v.php"

Full path: /home/atrmarke/public_html/atrdemolive.site/mzm/pages/supplier_v.php
File size: 0.02 KB (22.48 KB bytes)
MIME-type: text/x-php
Charset: utf-8

Download   Open   Edit   Advanced Editor   Back

<?php
include("db/cn.php");
ob_start();
if (isset($_SESSION['user_name'], $_SESSION['user_role'], $_SESSION['outlet_name'], $_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}

@$supplier_Name = $_GET["supplier_name"];

$transactions = [];
$totalBalance = 0;
$supplierName = '';
$startDate = '';
$endDate = '';
$openingBalance = 0;
$openingBalanceDate = '';

if (isset($_POST['filter'])) {
    $supplierName = $_POST['supplier'];
    $startDate = $_POST['startDate'];
    $endDate = $_POST['endDate'];

    function isValidDate($dateString) {
        $timestamp = strtotime($dateString);
        return $timestamp && $timestamp > 0 && $dateString !== '1970-01-01';
    }

    function formatDateForDisplay($dateString) {
        return isValidDate($dateString) ? date("d-m-Y", strtotime($dateString)) : '';
    }

    $dateCondition = !empty($startDate) && !empty($endDate) 
        ? "AND date_time BETWEEN '$startDate' AND '$endDate'" 
        : "";

    $query = "SELECT open_amount AS amount, date_time 
              FROM supplier_opening_amount 
              WHERE supplier_name = '$supplierName' $dateCondition";
    $result = mysqli_query($connection, $query);
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $openingBalance = $row['amount'];
        $openingBalanceDate = $row['date_time'];
        if (isValidDate($openingBalanceDate)) {
            $totalBalance += $openingBalance;
            $transactions[] = [
                'date_time' => $openingBalanceDate,
                'date' => formatDateForDisplay($openingBalanceDate),
                'description' => 'Opening Balance',
                'Name' => '-',
                'amount' => $openingBalance,
                'type' => 'debit'
            ];
        }
    }

    $queries = [
        [
            "query" => "SELECT discount_amount AS amount, date_time 
                        FROM purchase 
                        WHERE customer_name = '$supplierName' AND paid_by = 'Credit' 
                        AND status = '' AND r_inv_id = '' $dateCondition GROUP BY inv_id",
            "description" => "Credit Purchase",
            "effect" => function($amount) use (&$totalBalance) {
                $totalBalance += $amount;
                return -$amount;
            }
        ],
        [
            "query" => "SELECT supplier_amount AS amount, date_time, desc_name 
                        FROM supplier_paid 
                        WHERE supplier_name = '$supplierName' $dateCondition", 
            "description" => "Payment to Supplier",
            "effect" => function($amount) use (&$totalBalance) {
                $totalBalance -= $amount;
                return $amount;
            }
        ],
        [
            "query" => "SELECT discount_amount AS amount, date_time 
                        FROM purchase 
                        WHERE customer_name = '$supplierName' AND paid_by = 'Credit' AND status = 'return' 
                        $dateCondition GROUP BY r_inv_id",
            "description" => "Purchase Return",
            "effect" => function($amount) use (&$totalBalance) {
                $totalBalance -= $amount;
                return -$amount;
            }
        ],
         [
        "query" => "SELECT cash_amount AS amount, date_time 
                    FROM purchase 
                    WHERE customer_name = '$supplierName' 
                    AND paid_by = 'Credit' 
                    $dateCondition 
                    GROUP BY inv_id",
        "description" => "POS Supplier Paid",
        "effect" => function($amount) use (&$totalBalance) {
            $totalBalance -= $amount;
             return $amount;
          }
       ]
    ];

    foreach ($queries as $queryData) {
        $result = mysqli_query($connection, $queryData['query']);
        while ($row = mysqli_fetch_assoc($result)) {
            if (!empty($row['amount']) && isValidDate($row['date_time'])) {
                $transactionAmount = $queryData['effect']($row['amount']);
                $transactions[] = [
                    'date_time' => $row['date_time'],
                    'date' => formatDateForDisplay($row['date_time']),
                    'description' => $queryData['description'],
                    'Name' => isset($row['desc_name']) ? $row['desc_name'] : '-',
                    'amount' => $transactionAmount,
                    'type' => $transactionAmount < 0 ? 'credit' : 'debit'
                ];
            }
        }
    }

    usort($transactions, function ($a, $b) {
        return strtotime($a['date_time']) - strtotime($b['date_time']);
    });
}
?>

<!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> مدینہ زرعی مرکز اینڈ سپرے سینٹر</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>
 #table-container-wrapper {
    max-height: 460px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
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;
		}
		
.select{
	  font-weight:500;
	  color:#000;
		}
		label{
		    font-weight:700;
		    color:#000;
		}
		.btn{
		    font-weight:700;
		}
		.form-control{
		    border:1px solid #353535;
		}
  </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">

                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

                    <!-- Sidebar Toggle (Topbar) -->
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>

                    <!-- Topbar Search -->
                    
  <?php include('common/log.php');  ?>

                    <!-- Topbar Navbar -->
                    
                </nav>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
                <?php
                	$supplierQuery = "SELECT DISTINCT supplier_name FROM supplier";
                                $supplierResult = mysqli_query($connection, $supplierQuery);
                ?>
                      <div class="container-fluid mt-5">
            <div class="row">
        <div class="col-sm-3">
     <h3 style="font-weight:700; color:#060606;">Supplier Report</h3>
        </div>
        <div class="col-sm-6"></div>
        <div class="col-sm-3">
             <a href="supplier_view.php" class="btn btn-dark" style="float:right;"><i class="fas fa-arrow-left fa-1x"></i></a>
            <!-- <button type="button" class="btn btn-dark " data-toggle="modal" style="float:right; margin-right:10px;" data-target="#addPurchaseModal">-->
            <!--   Paid-->
            <!--</button>-->
            <!-- <button type="button" class="btn btn-dark" data-toggle="modal" style="float:right; margin-right:10px;" data-target="#addopenPurchaseModal">-->
            <!--  Add Open-->
            <!--</button>-->
        </div>
    </div>
       <br>
            <form method="post">
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="supplier">Supplier Name:</label>
                            <select class="form-control select" name="supplier" style="text-transform:capitalize; background:#0A4567; color:#fff; font-weight:700;">
                                
                               
         <option value="<?php echo $supplier_Name; ?>"> <?php echo $supplier_Name; ?></option>
                               
                            </select>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="startDate">Start Date:</label>
                            <input type="date" class="form-control select" name="startDate" value="<?php echo $startDate; ?>" >
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="endDate">End Date:</label>
                            <input type="date" class="form-control select" name="endDate" value="<?php echo $endDate; ?>" >
                        </div>
                    </div>
                    <div class="col-md-4">
                    <div class="form-group">
                        
                        <button type="submit" class="btn btn-dark" name="filter" style="margin-top:30px;">Filter</button>
                         
<button id="downloadExcel" class="btn btn-dark " style="margin-top:30px;">Download </button>


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

                <?php if (!empty($transactions)) : ?>
                    <h3 style="background:#0A4657; color:#fff;padding:20px; border-radius:10px;text-align:center;
                    text-transform:capitalize; font-weight:700;">Supplier Ledger Report : <?php echo $supplierName; ?></h3>

                    <div class="row">
                       <div class="col-sm-12" id="table-container-wrapper">
    <table id="patientTable" class="table table-striped table-hover text-center table-sm bg-white"  >
        <thead>
            <tr class="bg-dark text-white">
                <th>Date</th>
                <th>Amount Type</th>
                <th>Description</th>
                <th>POS Supplier Paid</th>
                <th>Debit Amount (Rs)</th>
                <th>Credit Amount (Rs)</th>
                <th>Balance (Rs)</th>
            </tr>
        </thead>
        <tbody>
        <?php 
        // Set initial balance from the opening balance
        $runningBalance = $openingBalance; 
        ?>
        <tr>
            <td style="color:#0A4657; font-weight:700;"><?php echo date('d-m-Y', strtotime($openingBalanceDate)); ?></td>
            <td style="color:#0A4657; font-weight:700;">Opening Balance</td>
            
            <td style="color:#04A657; font-weight:700;"><?php echo htmlspecialchars($desc_name); ?></td>
            <td style="color:#04A657; font-weight:700;"><?php echo htmlspecialchars($total_supplier); ?></td>
            <td style="color:#04A657; font-weight:700;">-</td>
            <td style="color:#0A4657; font-weight:700;"><?php echo number_format($openingBalance, 2); ?></td>
            <td style="color:#0A4657; font-weight:700;"><?php echo number_format($runningBalance, 2); ?></td>
        </tr>
        <?php 
       // Iterate over each transaction to update the running balance
foreach ($transactions as $transaction) : 
    $creditAmount = '';
    $debitAmount = '';

    // Set debit and credit amounts based on transaction type
    if ($transaction['type'] == 'debit') {
        $runningBalance -= abs($transaction['amount']);
        $debitAmount = number_format(abs($transaction['amount']), 2);
    } elseif ($transaction['type'] == 'credit') {
        $runningBalance += abs($transaction['amount']);
        $creditAmount = number_format(abs($transaction['amount']), 2);
    }
?>
    <tr style="color:#060606;">
        <td><?php echo date('d-m-Y', strtotime($transaction['date'])); ?></td>
        <td style="text-transform:capitalize;"><?php echo $transaction['description']; ?></td>
        
        <td style="text-transform:capitalize;"><?php echo $transaction['Name']; ?></td>
        
        <td><?php echo $debitAmount; ?></td>
        <td><?php echo $creditAmount; ?></td>
        <td><?php echo number_format($runningBalance, 2); ?></td>
    </tr>
<?php endforeach; ?>
        </tbody>
    </table>
</div>


                        <div class="col-sm-12">
                            <table class="table bg-white" style="color:#060606;">
                                <tfoot>
                                    <tr>
                                        <th>Final Balance:</th>
                                        <td><?php echo number_format($totalBalance, 2); ?></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                <?php else : ?>
                    <?php if (isset($_POST['filter'])) : ?>
                        <div class="alert alert-warning text-center text-capitalize" style="font-weight:700; background:#0A4567; color:#fff; ">
                            No records found for the selected supplier and date range.
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </form>
        </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" id="addPurchaseModalLabel" style="color:#fff; font-weight:700; ">Supplier Paid</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="supplier_v.php?supplier_name=<?php echo $supplier_Name; ?>" enctype="multipart/form-data">
                            
                                <input type="text" name="supplier_name" placeholder="Supplier Name" 
                                value="<?php echo $supplier_Name; ?>" class="form-control" style="background:#0A4657; color:#fff;" />
                                <br />
                                <input type="text" name="supplier_amount" placeholder="Amount" class="form-control" />
                               <br />
                                <select name="status" class="form-control">
                                <option value="">Select Method</option>                                
                                    <option value="cash">Cash</option>
                                    <option value="bank1">Mezzan Bank</option>
                                        <option value="bank2">Bank AL Habib</option>
                                        <option value="bank3">Habib Bank</option>
                                        <option value="bank4">JazzCash</option>
                                        <option value="bank5">Easy Paisa</option>
                                        <option value="others">Others</option>
                                </select>
                                <br />
                                <input type="date" name="date_time" class="form-control" />
                                <br />
                                <button type="submit" name="supplier_paid"  class="btn btn-dark">Enter</button>
                            </form>
                        </div>
                    </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" id="addPurchaseopenModalLabel" style="color:#fff; font-weight:700;">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="supplier_v.php?supplier_name=<?php echo $supplier_Name; ?>" enctype="multipart/form-data">
                            
                                <input type="hidden" value="<?php echo $supplier_Name; ?>" name="supplier_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="supplier_open"  class="btn btn-dark">Enter</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            
                <!-- /.container-fluid -->

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

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

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

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

    <!-- Scroll to Top Button-->
    <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>

      <!-- Include the SheetJS (xlsx) library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>

<!-- JavaScript for exporting the table data to Excel -->
<script>
    document.getElementById('downloadExcel').addEventListener('click', function() {
        // Get the table element
        var table = document.getElementById('patientTable');

        // Clean the table to avoid potential issues with hidden rows or formatting
        var clone = table.cloneNode(true); // Clone the table
        var rows = clone.querySelectorAll('tr');

        // Remove hidden or empty rows if necessary
        rows.forEach(function(row) {
            if (row.style.display === 'none' || row.innerText.trim() === '') {
                row.remove();
            }
        });

        // Convert the table into a worksheet using SheetJS
        var workbook = XLSX.utils.table_to_book(clone, { sheet: "Patients" });

        // Export the Excel file with a proper name
        try {
            XLSX.writeFile(workbook, 'Supplier_data.xlsx');
        } catch (error) {
            console.error("Error while writing the file: ", error);
            alert("Error generating Excel file. Please check if the SheetJS library is properly loaded.");
        }
    });
</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>