<?php
include("db/cn.php");
include("common/tx.php");
ob_start();
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'];
}
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><?php echo $tx; ?></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">
        <link href="../css/sb-admin-2.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;
		}
		
#table-container-wrapper {
    max-height: 460px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
.btn, tr{
    font-weight:700;
}
 .form-control{
     font-weight:700;
     color:#000;
 }
  </style>
<?php
ob_start();
$rec_suplier_name = mysqli_query($connection, "SELECT supplier_name FROM supplier GROUP BY supplier_name ");
$rec_suplier_company = mysqli_query($connection, "SELECT company FROM products GROUP BY company");
$rec_suplier_company_category = mysqli_query($connection, "SELECT category FROM products GROUP BY category");
$rec_products = mysqli_query($connection, "SELECT product_name FROM products GROUP BY product_name");

// Fetch filter parameters from the form
$supplier = isset($_POST['supplier']) ? $_POST['supplier'] : '';
$company = isset($_POST['company']) ? $_POST['company'] : '';
$company_category = isset($_POST['company_category']) ? $_POST['company_category'] : '';
$product = isset($_POST['product']) ? $_POST['product'] : '';
$startDate = isset($_POST['startDate']) ? $_POST['startDate'] : '';
$endDate = isset($_POST['endDate']) ? $_POST['endDate'] : '';

// Base SQL query
$sql = "SELECT SUM(product_quantity) AS total_quantity, SUM(net_amount) AS total_amount, net_amount FROM purchase WHERE status = '' && 1=1";

// Add filters based on selected options
if (!empty($supplier)) {
    $sql .= " AND supplier_name = '$supplier'";
}
if (!empty($company)) {
    $sql .= " AND company = '$company'";
}

if (!empty($product)) {
    $sql .= " AND product_name = '$product'";
}
if (!empty($startDate) && !empty($endDate)) {
    $sql .= " AND date_time BETWEEN '$startDate' AND '$endDate'";
}

// Execute the query
$sum_result = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($sum_result);
$total_quantity = $row['total_quantity'];
$total_amount = $row['total_amount'];

// Execute the main query
$sql = "SELECT * FROM purchase WHERE status = '' && 1=1";
if (!empty($supplier)) {
    $sql .= " AND supplier_name = '$supplier'";
}
if (!empty($company)) {
    $sql .= " AND company = '$company'";
}

if (!empty($product)) {
    $sql .= " AND product_name = '$product'";
}
if (!empty($startDate) && !empty($endDate)) {
    $sql .= " AND date_time BETWEEN '$startDate' AND '$endDate'";
}

$rec_purchases = mysqli_query($connection, $sql);
ob_end_flush();
?>
<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 -->
                
                   <div class="container-fluid mt-5">
            <div class="row">
        <div class="col-sm-3">
                <h3 style="color:#060606; font-weight:700">Purchase Report</h3>  
        </div>
        <div class="col-sm-6"></div>
        <div class="col-sm-3">

        </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" name="supplier">
                            <option style="font-weight:700;" value="">Select Supplier</option>
                            <?php while($row_supplier_name = mysqli_fetch_array($rec_suplier_name)) { ?>
                                <option style="font-weight:700;" value="<?php echo $row_supplier_name['supplier_name']; ?>"><?php echo $row_supplier_name['supplier_name']; ?></option>
                            <?php } ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="company">Supplier Company:</label>
                        <select class="form-control" name="company">
                            <option value="" style="font-weight:700;">Select Company</option>
                            <?php while($row_supplier_company = mysqli_fetch_array($rec_suplier_company)) { ?>
                                <option style="font-weight:700;" value="<?php echo $row_supplier_company['company']; ?>"><?php echo $row_supplier_company['company']; ?></option>
                            <?php } ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="product">Category</label>
                        <select class="form-control" name="company_category">
                            <option style="font-weight:700;" value="">Select Category</option>
                            <?php while($row_supplier_category = mysqli_fetch_array($rec_suplier_company_category)) { ?>
                                <option style="font-weight:700;" value="<?php echo $row_supplier_category['category']; ?>"><?php echo $row_supplier_category['category']; ?></option>
                            <?php } ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="product">Product Name:</label>
                        <select class="form-control" name="product">
                            <option style="font-weight:700;" value="">Select Product</option>
                            <?php while($row_products = mysqli_fetch_array($rec_products)) { ?>
                                <option style="font-weight:700;" value="<?php echo $row_products['product_name']; ?>"><?php echo $row_products['product_name']; ?></option>
                            <?php } ?>
                        </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" name="startDate">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="endDate">End Date:</label>
                        <input type="date" class="form-control" name="endDate">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                       
                     <button type="submit" class="btn btn-primary  " style="margin-top:30px;" name="filter"><i class="fas fa-filter fa-1x"></i> &nbsp; Filter</button>
                    
                    <a href="report_pur.php"><button type="button" class="btn btn-dark btn-lg" style="margin-top:30px;">
                        <i class="fas fa-sync-alt fa-1x"></i></button></a>
                        <button id="downloadExcel" type="button" class="btn btn-success " style="margin-top:30px;">Excel</button>
                    <button id="downloadPdf" type="button" class="btn btn-danger " 
                    style="margin-top:30px;">PDF </button>

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

                
                <div id='report'>
                                <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 style="background:#0A4657; color:white;">
                                   <thead class="font-weight-bold text-center">
                             
                             <tr>
                                 <th colspan="8">Report Date Range</th>
                             </tr>
                             <tr>
                                 <th colspan="8"> <?php 
                              echo $startDate .'&nbsp;To&nbsp;'. $endDate
                             ?></th>
                             </tr>
                            
                             
                         </thead>
                         <thead style="background:#0A4657; color:white;">
                                    <tr>
                                        <th colspan="8" class="text-center p-3">Purchase Report Information</th>
                                    </tr>
                                </thead>
                    <thead>
                        <tr class="bg-dark text-white">
                            <th>Date</th>
                            <th>Supplier</th>
                            <th>Company</th>
                             <th>Category</th>
                            <th>Product Name</th>
                            <th>Purchase Quantity </th>
                            <th>Total Amount(Rs)</th>
                            <th>Purchase Price(Rs)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
						ob_start();
						 while($row = mysqli_fetch_array($rec_purchases)) { ?>
                            <tr style="color:#000;">
                                <td><?php echo $row['date_time']; ?></td>
                                <td class="text-capitalize"><?php echo $row['supplier_name']; ?></td>
                                <td class="text-capitalize"><?php echo $row['company']; ?></td>
                              <td class="text-capitalize"><?php echo $row['category']; ?></td>
                                <td class="text-capitalize"><?php echo $row['product_name']; ?></td>
                                <td><?php echo $row['product_quantity']; ?></td>
                                <td> <?php echo $row['net_amount']; ?> </td>
                                <td>
                                    <?php 
                                    if ($row["product_quantity"] > 0) {
                                        $in_tr = $row["total_amount"] / $row["product_quantity"];
                                        echo $in_tr;
                                    } else {
                                        echo "N/A"; // Avoid division by zero
                                    }
                                    ?>
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>

            <div class="row">
               
                <div class="col-sm-12">
                    <table class="table bg-white" style="color:#000;">
                        <tfoot>
                            <tr>
                              
                                <td ><strong>Total Quantity :</strong></td>
                                <td> <?php echo $total_quantity; ?></td>
                            </tr>
                            <tr>
                               <td ><strong>Total Amount(Rs):</strong></td>
                               <td> <?php echo $total_amount; ?></td> 
                                
                            </tr>
                                
                               
                            
                        </tfoot>
                    </table>
                </div>
            </div>
                </div>
                
            <div class="row">
                <div class="col-sm-5"></div>
                <div class="col-sm-5"></div>
                <div class="col-sm-2  text-center text-white" style="padding:10px;"><?php echo ''; ?></div>
            </div>
        </form>
    </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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

<!-- JavaScript for exporting the table data to Excel -->
<script>
/* ===================== EXCEL ===================== */
document.getElementById('downloadExcel').addEventListener('click', function (e) {
    e.preventDefault(); // ðŸ”´ STOP form submit

    var table = document.getElementById('patientTable');
    if (!table) {
        alert("Table not found");
        return;
    }

    var clone = table.cloneNode(true);
    var rows = clone.querySelectorAll('tr');

    rows.forEach(function (row) {
        if (row.style.display === 'none' || row.innerText.trim() === '') {
            row.remove();
        }
    });

    var workbook = XLSX.utils.table_to_book(clone, { sheet: "Refund Sales" });
    XLSX.writeFile(workbook, 'Purchase_data.xlsx');
});


/* ===================== PDF ===================== */
document.getElementById("downloadPdf").addEventListener("click", function (e) {
    e.preventDefault(); // ðŸ”´ STOP form submit

    const { jsPDF } = window.jspdf;

    // âœ… CORRECT ID
    const report = document.getElementById("table-container-wrapper");

    if (!report) {
        alert("Report container not found");
        return;
    }

    const now = new Date();
    const formattedDateTime =
        now.toLocaleDateString() + " " + now.toLocaleTimeString();

    html2canvas(report, { scale: 2 }).then(canvas => {

        // ðŸ”» small-size PDF
        const imgData = canvas.toDataURL("image/jpeg", 0.65);

        const pdf = new jsPDF("p", "mm", "a4");
        const pageWidth = pdf.internal.pageSize.getWidth();

        const imgHeight = (canvas.height * pageWidth) / canvas.width;

        pdf.setFont("helvetica", "bold");
        pdf.setFontSize(16);
        pdf.text("Whole Sale Retail", 2, 12);
        pdf.setFont("helvetica", "normal");
        pdf.setFontSize(10);
        pdf.text("Address: Al-Hafeez Shopping Mall, Gulberg III Lahore. ", 2, 17);
        pdf.setFontSize(10);
        pdf.text("Phone: 0334-8739892, Whatsapp: 0334-8739892", 2, 21);
        pdf.setFontSize(10);
        pdf.text("Email: info@atrsms.pk ", 2, 26);
         pdf.setFont("helvetica", "bold");
        pdf.setFontSize(14);
        pdf.text("Purchase Report", pageWidth - 10, 12, { align: "right" });

        pdf.setFontSize(12);
        pdf.setFont("helvetica", "bold");
        pdf.text(`Printed: ${formattedDateTime}`, pageWidth - 10, 20, { align: "right" });
        // CONTENT
        pdf.addImage(imgData, "JPEG", 0, 30, pageWidth, imgHeight);

        pdf.save("Purchase-Report.pdf");

    }).catch(err => {
        console.error(err);
        alert("PDF generation failed");
    });
});
</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>


    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>

</html>