<?php
include 'includes/config.php';
session_start();

// error_reporting(E_ALL);
// ini_set('display_errors', 1);


if (!$_SESSION['email']) {
    header('location:login.php');
}
?>
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>View Products</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }

        .custom_select {
            position: relative;
            display: inline-block;
        }

        .select-button {
            background-color: #007BFF;
            color: white;
            padding: 4px 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 70px;
            text-align: left;
        }

        .arrow {
            margin-left: 3px;
        }

        .select-options {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 120px;
            box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
            z-index: 1;
            border-radius: 4px;
            top: 100%;
            left: 0;
        }

        .select-options a {
            color: black;
            padding: 6px 10px;
            text-decoration: none;
            display: block;
            font-size: 12px;
        }

        .select-options a:hover {
            background-color: #f1f1f1;
        }

        /* Style for the popup background overlay */
        .popup {
            display: none;
            /* Hidden by default */
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            /* Semi-transparent background */
            z-index: 1000;
            /* Ensure it's above other content */
            overflow: auto;
            /* Scroll if needed */
        }

        /* Style for the popup content box */
        .popup-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            /* Center the box */
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            /* Rounded corners */
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            /* Shadow effect */
            width: 90%;
            max-width: 500px;
            /* Responsive max width */
            box-sizing: border-box;
            /* Include padding in width calculation */
        }

        /* Close button styling */
        .close {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 24px;
            font-weight: bold;
            color: #333;
            cursor: pointer;
            transition: color 0.3s;
        }

        .close:hover {
            color: #e74c3c;
            /* Change color on hover */
        }

        /* Styling for headings */
        .popup-content h2 {
            margin-top: 0;
            font-size: 24px;
            color: #333;
        }

        /* Table styling */
        .popup-content table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }

        .popup-content th,
        .popup-content td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        .popup-content th {
            background-color: #f4f4f4;
        }

        /* Input field styling */
        input[type="number"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            /* Include padding in width calculation */
        }

        /* Button styling */
        button {
            background-color: #3498db;
            /* Primary color */
            color: #fff;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #2980b9;
            /* Darker shade on hover */
        }

        .loading_data {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            /* background-color: rgba(255, 255, 255, 0.8); */
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            /* Ensures the loader is on top */
        }

        .spinner {
            border: 8px solid rgba(0, 0, 0, 0.1);
            border-left-color: #3498db;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
    </style>

</head>

<body>
    <!--<div id="loading_data" class="loading_data">-->
    <!--    <div class="spinner"></div>-->
    <!--</div>-->
    <!-- Popup Modal -->
    <!-- HTML for the Modal Popup -->
    <div id="stockPopup" class="popup">
        <div class="popup-content">
            <span class="close" onclick="closePopupstock()">&times;</span>
            <h2>Edit Stock</h2>
            <table>
                <tr>
                    <th>Product Name</th>
                    <th>Overall Purchase Stock</th>
                    <th>Opening Stock</th>
                    <th style="display: none;">Difference Stock</th>
                    <th>Opening Value</th>
                </tr>
                <tr id="productDetailsRow">
                    <td id="productName"></td>
                    <td id="overallStock"></td>
                    <td id="OpeningStock"></td>
                    <!-- Input field for current stock -->
                    <td id="currentStock" style="display: none;"></td>
                    <td><input type="number" id="currentStocksaleInput" /></td>
                </tr>
            </table>
            <!-- Button to submit the stock update -->
            <button onclick="updateStock()">Edit Stock</button>
        </div>
    </div>

    <!-- PHP button for editing stock -->
    <a href="#" onclick="openPopup(<?php echo htmlentities($product['product_id']); ?>)">
        <ion-icon name="server-outline"></ion-icon> &nbsp; Edit Stock
    </a>

    <!-- loader Start -->

    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php
        include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php'; ?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between row">
                                <div class="iq-header-title col-lg-6">
                                    <h4 class="card-title"><a href="list_products.php">Reports</a> > Defective Report
                                    </h4>
                                </div>
                                <div class="col-lg-6">
                                    <!-- <button class="btn btn-primary  ps-5 pe-5" style="float:inline-end;">
                                        <a href="add_products.php" class="text-white">
                                            <ion-icon name="add-outline" style="font-size:20px; margin-bottom:-4px">
                                            </ion-icon> Add
                                        </a>
                                    </button> -->
                                    <!-- <button class="btn btn-primary  ps-5 pe-5 me-2" style="float:inline-end;">
                                        <a href="list_stock_report.php" class="text-white">Stock Report</a>
                                    </button> -->
                                </div>
                            </div>
                            <!-- search bar -->

             
                            <!-- <form method="get" id="recordsPerPageForm" style="margin-left:2em;">
                                <label for="recordsPerPage">Show</label>
                                <select name="records_per_page" id="recordsPerPage" class="form-control" style="width: 8em;" onchange="document.getElementById('recordsPerPageForm').submit();">
                                    <option value="50" <?php if ($records_per_page == 50) echo 'selected'; ?>>50</option>
                                    <option value="100" <?php if ($records_per_page == 100) echo 'selected'; ?>>100</option>
                                    <option value="200" <?php if ($records_per_page == 200) echo 'selected'; ?>>200</option>
                                    <option value="500" <?php if ($records_per_page == 500) echo 'selected'; ?>>500</option>
                                    <option value="50" <?php if ($records_per_page == 1000) echo 'selected'; ?>>1000</option>
                                </select>
                                <input type="hidden" name="page" value="<?php echo $page; ?>">
                                <input type="hidden" name="search" value="<?php echo htmlspecialchars($search); ?>">
                            </form> -->
                            <form action="" method="get">
                                <div class="row mt-5" style="width:95%;margin:0 auto;">
                                   
                                    <div class="col-lg-5">
                                        <input type="text" id="searchInput" class="form-control" placeholder="Search products..." autocomplete="off">

                                        <!-- <input type="search" id="search" name="search" class="form-control" placeholder="Search products" value="<?php echo htmlspecialchars($search); ?>" autocomplete="off">
                                        <div id="suggestions" style="border: 1px solid #ccc; display: none; position: absolute; z-index: 1000; background: white; width: calc(100% - 20px);"></div> -->
                                    </div>
                                    <!-- <div class="col-lg-2">
                                        <button type="submit" style="width:100%;" class="btn btn-primary p-2">Search</button>
                                    </div> -->
                                    <div class="col-lg-2">
                                        <button type="button" style="width:100%;" class="btn btn-success p-2" onclick="clearFilter()">Clear Filter</button>
                                    </div>
                                </div>
                            </form>



                            <!-- searchbar end -->
                            <!-- buttons for export -->
                            <div class="row mt-5">
                                <div class="col-lg-2"></div>
                                <!--<div class="col-lg-8">-->
                                <!--    <button class="btn btn-primary" onclick="exportToCSV()">-->
                                <!--        <ion-icon name="document-outline"></ion-icon>Export to CSV-->
                                <!--    </button>-->
                                <!--    <button class="btn btn-info" onclick="exportToExcel()">-->
                                <!--        <ion-icon name="document-outline"></ion-icon>Export to Excel-->
                                <!--    </button>-->
                                <!--    <button class="btn btn-warning">-->
                                <!--        <ion-icon name="print-outline"></ion-icon>Print-->
                                <!--    </button>-->
                                <!--    <button class="btn btn-danger">-->
                                <!--        <ion-icon name="stop-outline"></ion-icon>Column Visibility-->
                                <!--    </button>-->
                                <!--    <button class="btn btn-dark" onclick="exportToPDF()">-->
                                <!--        <ion-icon name="document-outline"></ion-icon>Export to PDF-->
                                <!--    </button>-->
                                <!--</div>-->

                            </div>

                            <!-- buttons for export end -->
                            <div class="iq-card-body" style="overflow:auto;">

                                <!-- HTML Table -->


                                <!-- HTML Table -->


<div class="col-lg-2 mt-2">
    <button id="downloadPDF" style="width:100%;" class="btn btn-danger p-2">Download PDF</button>
</div>




</table>
<h2>Defective Report</h2>
<div >
  <strong>Total Quantity:</strong> <span id="totalQty">0</span><br>
  <strong style="display:none;">Total Loss:</strong> <span id="totalLoss" style="display:none;">0.00</span>
</div>
<table class="table table-hover table-bordered" border="1" id="defectiveTable">
    <thead>
        <tr>
            <th>Invoice</th>
            <th style="display:none;">Product ID</th>
            <th>Product Name</th>
            <th>Defective Label</th>
            <th>Category</th>
            <th>Unit</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Total</th>
            <th>Date</th>
            <th>Customer</th>
        </tr>
    </thead>
     <tbody id="defectiveBody"></tbody>
</table>

<div id="loading">Loading...</div>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const tableBody = document.getElementById("defectiveBody");
    const loading = document.getElementById("loading");
    const searchInput = document.getElementById("searchInput");

    console.log("Fetching defective report...");

    fetch("fetch_defective_report.php")
        .then(res => res.json())
        .then(data => {
            loading.style.display = "none";

            if (!Array.isArray(data)) {
                tableBody.innerHTML = `<tr><td colspan="11">Invalid data format</td></tr>`;
                return;
            }

            if (data.length === 0) {
                tableBody.innerHTML = `<tr><td colspan="11">No defective sales found</td></tr>`;
                return;
            }

            let totalQty = 0;
            let totalLoss = 0;

            data.forEach(item => {
                const row = document.createElement("tr");

                totalQty += parseFloat(item.sale_qty || 0);
                totalLoss += parseFloat(item.total_amount || 0);

                row.innerHTML = `
                    <td>${parseInt(item.invoice, 10)}</td>
                    <td style="display:none;">${item.product_id}</td>
                    <td>${item.product_name}</td>
                    <td>${item.defective_name}</td>
                    <td>${item.category}</td>
                    <td>${item.unit}</td>
                    <td>${parseFloat(item.price).toFixed(2)}</td>
                    <td>${item.sale_qty}</td>
                    <td>${parseFloat(item.total_amount).toFixed(2)}</td>
                    <td>${item.date_sale}</td>
                    <td>${item.customer_name || '-'}</td>
                `;

                tableBody.appendChild(row);
            });

            document.getElementById("totalQty").textContent = totalQty;
            document.getElementById("totalLoss").textContent = totalLoss.toFixed(2);
        })
        .catch(err => {
            loading.style.display = "none";
            tableBody.innerHTML = `<tr><td colspan="11">Error: ${err.message}</td></tr>`;
        });

    searchInput.addEventListener("input", function () {
        const filter = this.value.toLowerCase();
        const rows = tableBody.getElementsByTagName("tr");
        Array.from(rows).forEach(row => {
            const rowText = row.textContent.toLowerCase();
            row.style.display = rowText.includes(filter) ? "" : "none";
        });
    });

    window.clearFilter = function () {
        searchInput.value = "";
        const rows = tableBody.getElementsByTagName("tr");
        Array.from(rows).forEach(row => row.style.display = "");
    };

    document.getElementById("downloadPDF").addEventListener("click", function () {
        const table = document.getElementById("defectiveTable");

        html2canvas(table).then(canvas => {
            const imgData = canvas.toDataURL("image/png");
            const pdf = new jspdf.jsPDF('l', 'mm', 'a4');
            const imgProps = pdf.getImageProperties(imgData);
            const pdfWidth = pdf.internal.pageSize.getWidth();
            const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
            pdf.addImage(imgData, 'PNG', 10, 10, pdfWidth - 20, pdfHeight);
            pdf.save("defective_report.pdf");
        });
    });
});
</script>



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

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

    <script src="js/jquery.min.js"></script>
    <!-- Rtl and Darkmode -->
    <script src="js/rtl.js"></script>
    <script src="js/customizer.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>
</body>

</html>