<?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> > Stock 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 -->

                            <?php

                            // Define the default number of records per page or get from the select box
                            $records_per_page = isset($_GET['records_per_page']) ? (int)$_GET['records_per_page'] : 1000;

                            // Get the current page from URL or set default to 1
                            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
                            $offset = ($page - 1) * $records_per_page;

                            // Get the search term from URL
                            $search = isset($_GET['search']) ? $_GET['search'] : '';
                            $search = htmlspecialchars($search); // Sanitize search input

                            // Define the business_id filter
                            $business_id = 3;

                            // Total number of records query with search filter and business_id
                            $total_records_query = "SELECT COUNT(*) 
    FROM products p
    LEFT JOIN purchase_lines pl ON p.id = pl.product_id
    WHERE (p.name LIKE :search)
    AND p.business_id = :business_id";
                            $total_records_stmt = $conn->prepare($total_records_query);
                            $total_records_stmt->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
                            $total_records_stmt->bindValue(':business_id', $business_id, PDO::PARAM_INT);
                            $total_records_stmt->execute();
                            $total_records = $total_records_stmt->fetchColumn();
                            $total_pages = ceil($total_records / $records_per_page);

                            // SQL query to fetch product details with pagination, search filter, and business_id
                            $sql = "SELECT 
                            p.id AS product_id,
                            p.name AS product_name,
                            p.business_id,
                            p.image,
                            p.type,
                            p.brand_id,
                            b.name AS brand_name,
                            p.category_id,
                            p.sub_category_id,
                            c1.name AS category_name,
                            c2.name AS sub_category_name,
                            p.tax,
                            p.sku,
                            p.alert_quantity,
                            p.product_custom_field1,
                            p.product_custom_field2,
                            p.product_custom_field3,
                            p.product_custom_field4,
                            p.product_description,
                            p.unit_id,
                            p.tax_type,
                            v.profit_percent,
                            u.actual_name,
                            v.default_purchase_price,
                            v.default_sell_price,
                            COALESCE(v.dpp_inc_tax, 0) AS purchase_price,
                            COALESCE(v.sell_price_inc_tax, 0) AS sale_price,
                        
                            -- Calculate total quantity from purchase lines
                            COALESCE(SUM(pl.quantity), 0) AS total_quantity,
                        
                            -- Available stock from stock settings
                            COALESCE(ss.quantity, 0) AS stock_quantity,
                        
                            -- Total sold quantity
                            COALESCE(sale.total_sale_qty, 0) AS total_sale_qty,
                        
                            -- Total transferred quantity
                            COALESCE(st_transfer.total_quantity_transferred, 0) AS total_quantity_transferred,
                        
                            -- Get the latest created_at date from stock_setting (or null if not available)
                            (
                                SELECT MAX(ss2.created_at) 
                                FROM stock_setting ss2 
                                WHERE ss2.product_id = p.id
                            ) AS last_stock_setting_date,
                        
                            -- Calculate new purchase quantity based on created_at date (use all purchases if stock_setting date is not available)
                            (
                                SELECT COALESCE(SUM(pl2.quantity), 0)
                                FROM purchase_lines pl2
                                WHERE pl2.product_id = p.id 
                                AND (
                                    (
                                        SELECT MAX(ss3.created_at) 
                                        FROM stock_setting ss3 
                                        WHERE ss3.product_id = p.id
                                    ) IS NULL OR pl2.created_at > (
                                        SELECT MAX(ss3.created_at) 
                                        FROM stock_setting ss3 
                                        WHERE ss3.product_id = p.id
                                    )
                                )
                            ) AS new_purchase_quantity,
                        
                            -- Current stock calculation: handle cases where stock_setting may not be available
                            (
                                COALESCE(ss.quantity, 0)  -- Use stock setting quantity if available
                                + (
                                    SELECT COALESCE(SUM(pl2.quantity), 0)
                                    FROM purchase_lines pl2
                                    WHERE pl2.product_id = p.id 
                                    AND (
                                        (
                                            SELECT MAX(ss3.created_at) 
                                            FROM stock_setting ss3 
                                            WHERE ss3.product_id = p.id
                                        ) IS NULL OR pl2.created_at > (
                                            SELECT MAX(ss3.created_at) 
                                            FROM stock_setting ss3 
                                            WHERE ss3.product_id = p.id
                                        )
                                    )
                                )  -- Add new purchases after last stock setting date or all purchases if no stock setting
                                - COALESCE(sale.total_sale_qty, 0)  -- Subtract total sold quantity
                                - COALESCE(st_transfer.total_quantity_transferred, 0)  -- Subtract total transferred quantity
                            ) AS current_stock,
                        
                            -- Calculate current stock value: current stock * purchase price
                            (
                                (
                                    COALESCE(ss.quantity, 0) + 
                                    (
                                        SELECT COALESCE(SUM(pl2.quantity), 0)
                                        FROM purchase_lines pl2
                                        WHERE pl2.product_id = p.id 
                                        AND (
                                            (
                                                SELECT MAX(ss3.created_at) 
                                                FROM stock_setting ss3 
                                                WHERE ss3.product_id = p.id
                                            ) IS NULL OR pl2.created_at > (
                                                SELECT MAX(ss3.created_at) 
                                                FROM stock_setting ss3 
                                                WHERE ss3.product_id = p.id
                                            )
                                        )
                                    )
                                ) - COALESCE(sale.total_sale_qty, 0) 
                                - COALESCE(st_transfer.total_quantity_transferred, 0)
                            ) * COALESCE(v.dpp_inc_tax, 0) AS current_stock_value
                        
                        FROM 
                            products p
                        LEFT JOIN 
                            (
                                SELECT 
                                    product_id, 
                                    SUM(quantity) AS quantity
                                FROM 
                                    purchase_lines
                                GROUP BY 
                                    product_id
                            ) pl ON p.id = pl.product_id
                        LEFT JOIN 
                            brands b ON p.brand_id = b.id
                        LEFT JOIN 
                            categories c1 ON p.category_id = c1.id
                        LEFT JOIN 
                            categories c2 ON p.sub_category_id = c2.id
                        LEFT JOIN 
                            units u ON p.unit_id = u.id
                        LEFT JOIN 
                            variations v ON p.id = v.product_id
                        LEFT JOIN 
                            stock_setting ss ON p.id = ss.product_id
                        LEFT JOIN 
                            (
                                SELECT 
                                    product_id, 
                                    SUM(sale_qty) AS total_sale_qty
                                FROM 
                                    stock_sale
                                GROUP BY 
                                    product_id
                            ) sale ON p.id = sale.product_id
                        LEFT JOIN 
                            (
                                SELECT 
                                    product_id, 
                                    SUM(QuantityTransferred) AS total_quantity_transferred
                                FROM 
                                    stocktransfer
                                GROUP BY 
                                    product_id
                            ) st_transfer ON p.id = st_transfer.product_id
                        WHERE 
                            p.business_id = :business_id
                            AND (p.name LIKE :search OR :search = '')
                        GROUP BY 
                            p.id
                        ORDER BY 
                            p.id DESC
                        LIMIT :limit OFFSET :offset";
                        

                            // Prepare and execute the query
                            $stmt = $conn->prepare($sql);
                            $stmt->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
                            $stmt->bindValue(':business_id', $business_id, PDO::PARAM_INT);
                            $stmt->bindValue(':limit', $records_per_page, PDO::PARAM_INT);
                            $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
                            $stmt->execute();
                            $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

                            // Function to generate pagination links
                            function generatePaginationLinks($current_page, $total_pages)
                            {
                                $pagination_links = [];
                                for ($i = 1; $i <= 4; $i++) {
                                    if ($i <= $total_pages) {
                                        $pagination_links[] = $i;
                                    }
                                }
                                if ($current_page > 5) {
                                    $pagination_links[] = '...';
                                }
                                for ($i = max(5, $current_page - 1); $i <= min($total_pages - 4, $current_page + 1); $i++) {
                                    if ($i > 4 && $i < $total_pages - 3) {
                                        $pagination_links[] = $i;
                                    }
                                }
                                if ($current_page < $total_pages - 4) {
                                    $pagination_links[] = '...';
                                }
                                for ($i = max($total_pages - 3, 5); $i <= $total_pages; $i++) {
                                    if ($i > 4) {
                                        $pagination_links[] = $i;
                                    }
                                }
                                return $pagination_links;
                            }

                            // Generate pagination links
                            $pagination_links = generatePaginationLinks($page, $total_pages);

                            ?>

                            <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 -->



<!-- Your HTML structure for displaying the table -->
<table class="table table-hover table-bordered" id="productTable">
    <thead>
    <tr>
            <th><input type="checkbox" class="column-checkbox" checked data-column="sku"> SKU</th>
            <th><input type="checkbox" class="column-checkbox" checked data-column="product"> Product</th>
            <th><input type="checkbox" class="column-checkbox" checked data-column="unit_purchase_price"> Unit <br> Price</th>
            <th><input type="checkbox" class="column-checkbox" checked data-column="current_stock"> Current <br> Stock</th>
            <th><input type="checkbox" class="column-checkbox" checked data-column="current_stock_value"> Current Stock <br> Value</th>
            <th><input type="checkbox" class="column-checkbox" checked data-column="total_unit_sold"> Total Unit <br> Sold</th>
            <th><input type="checkbox" class="column-checkbox" checked data-column="total_unit_transfered"> Total Unit <br> Transferred</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($products as $product): ?>
            <tr>
                <td><?php echo htmlspecialchars($product['sku']); ?></td>
                <td><?php echo htmlspecialchars($product['product_name']); ?></td>
                <td><?php echo number_format($product['purchase_price'], 2); ?> RS</td>
                <td><?php echo number_format($product['current_stock']); ?> &nbsp; <?php echo htmlspecialchars($product['actual_name']); ?></td>
                <td><?php echo number_format($product['current_stock_value'], 2); ?> RS</td>
                <td><?php echo number_format($product['total_sale_qty']); ?></td>
                <td><?php echo htmlspecialchars($product['total_quantity_transferred']); ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>




                                <!-- Pagination Links -->
                                <div id="paginationContainer">

                                <nav aria-label="Page navigation">
                                    <ul class="pagination">
                                        <?php if ($page > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>" aria-label="Previous">
                                                    <span aria-hidden="true">&laquo;</span>
                                                </a>
                                            </li>
                                        <?php endif; ?>

                                        <?php foreach ($pagination_links as $link): ?>
                                            <?php if ($link === '...'): ?>
                                                <li class="page-item disabled"><span class="page-link">...</span></li>
                                            <?php else: ?>
                                                <li class="page-item <?php echo ($link == $page) ? 'active' : ''; ?>">
                                                    <a class="page-link" href="?page=<?php echo $link; ?>&search=<?php echo urlencode($search); ?>"><?php echo $link; ?></a>
                                                </li>
                                            <?php endif; ?>
                                        <?php endforeach; ?>

                                        <?php if ($page < $total_pages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>" aria-label="Next">
                                                    <span aria-hidden="true">&raquo;</span>
                                                </a>
                                            </li>
                                        <?php endif; ?>
                                    </ul>
                                    <h4>Total Products: <?php echo $total_records; ?></h4>
                                </nav>
                                </div>


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

        </div>
    </div>
    </div>
    <!-- Popup structure -->
    <div id="popup">
        <div id="popup-header">
            <div id="popup-title">Product Details</div>
            <div id="popup-close" onclick="closePopup()">×</div>
        </div>
        <div id="popup-header">
            <div id="popup-header-left">
                <div id="popup-left-details">
                    <div class="detail-row">
                        <span class="detail-label">Product Name:</span>
                        <span id="popup-product-name" class="detail-value"></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Brand:</span>
                        <span id="popup-brand" class="detail-value"></span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">Unit:</span>
                        <span id="popup-unit" class="detail-value"></span>
                    </div>
                </div>
            </div>
            <div id="popup-header-center">
                <div class="detail-row">
                    <span class="detail-label">Category:</span>
                    <span id="popup-category" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Sub Category:</span>
                    <span id="popup-sub-category" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Manage Stock?:</span>
                    <span id="popup-manage-stock" class="detail-value">Yes</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Alert Quantity:</span>
                    <span id="popup-alert-quantity" class="detail-value"></span>
                </div>
            </div>
            <div id="popup-header-right">
                <div class="detail-row">
                    <span class="detail-label">Expires in:</span>
                    <span id="popup-expires-in" class="detail-value">Not Applicable</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Applicable Tax:</span>
                    <span id="popup-tax" class="detail-value">None</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Selling Price Tax Type:</span>
                    <span id="popup-tax-type" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">Product Type:</span>
                    <span id="popup-product-type" class="detail-value">Single</span>
                </div>
            </div>

            <!-- Image moved to the right side -->
            <img id="popup-image" src="" alt="Product Image">

        </div>



        <div id="popup-content">
            <table>
                <tr class="header-row">
                    <th>Default Purchase Price (Exc. tax):</th>
                    <th>Default Purchase Price (Inc. tax):</th>
                    <th>X Margin (%):</th>
                    <th>Default Selling Price (Exc. tax):</th>
                    <th>Default Selling Price (Inc. tax):</th>
                </tr>
                <tr style="background-color: #d2d6de;">
                    <td id="popup-purchase-price"></td>
                    <td id="popup-purchase-price-inc"></td>
                    <td id="popup-margin"></td>
                    <td id="popup-sale-price"></td>
                    <td id="popup-sale-price-inc"></td>

                </tr>
            </table>
        </div>
        <!-- Additional Table for SKU and Stock Information -->
        <div id="popup-additional-info">
            <table>
                <tr class="header-row">
                    <th>SKU</th>
                    <th>Product</th>
                    <th>Location</th>
                    <th>Unit Price</th>
                    <th>Current Stock</th>
                    <th>Current Stock Value</th>
                    <th>Total unit sold</th>
                    <th>Total Unit Transfered</th>
                    <th>Total Unit Adjusted</th>
                </tr>
                <tr style="background-color: #d2d6de;">
                    <td id="popup-sku"></td>
                    <td id="popup-product"></td>
                    <td id="popup-location"></td>
                    <td id="popup-unit-price"></td>
                    <td id="popup-current-stock"></td>
                    <td id="popup-stock-value"></td>
                    <td id="popup-unit-sold-value"> 0.00</td>
                    <td id="popup-unit-transfered-value"> 0.00</td>
                    <td id="popup-unit-adjusted-value"> 0.00</td>
                </tr>
            </table>
            <button onclick="printPopup()">Print</button>

        </div>
    </div>
    <script>
        function printPopup() {
            const popup = document.getElementById('popup');

            const printWindow = window.open('', '_blank', 'width=800,height=600');

            printWindow.document.write(`
        <html>
            <head>
                <title>Print</title>
                <style>
                    /* Include all your CSS styles here */
                    body {
                        margin: 0;
                        padding: 20px;
                        font-family: Arial, sans-serif;
                    }
              /* Popup styling */
#popup {
    display: none;
    position: fixed;
    top: 1%;
    left: 50%;
    transform: translateX(-50%);
    width: 90%;
    max-width: 1100px; /* Adjust width as needed */
    background: white;
    border: 1px solid #ccc;
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
    padding: 20px;
    z-index: 1000;
    max-height: 104vh; /* Ensure it doesn't exceed viewport height */
    overflow-y: auto; /* Enable scrolling if content exceeds height */
    border-radius: 10px;
}

/* Popup header styling */
#popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2px solid #ddd;
    padding-bottom: 10px;
    position: relative;
}

/* Popup close button styling */
#popup-close {
    cursor: pointer;
    font-size: 24px;
    color: #333;
}

/* Popup image styling */
#popup-image {
    width: 200px; /* Adjust size as needed */
    height: auto;
    border-radius: 5px;
}

/* Popup title styling */
#popup-title {
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

/* Popup details styling */
#popup-details {
    margin-top: 20px;
    border-bottom: 2px solid #ddd;
    padding-bottom: 10px;
}

.detail-row {
    justify-content: space-between;
    padding: 5px 0;
}

.detail-label {
    font-weight: bold;
    color: #555;
}

.detail-value {
    font-size: 16px;
    color: #333;
}

/* Popup content styling */
#popup-content, #popup-additional-info {
    margin-top: 20px;
}

#popup-content, #popup-additional-info table {
    width: 100%;
    border-collapse: collapse;
}

#popup-content, #popup-additional-info, table th, #popup-content, #popup-additional-info table td {
    padding: 12px;
    color:black;
    border: 1px solid #ddd;
    text-align: left;
}

.header-row {
    background-color: #2bcc8e;
    color: #fff;
    font-size: 13.4px;
    font-weight: bold;
}

                </style>
            </head>
            <body>
                ${popup.innerHTML}
            </body>
        </html>
    `);

            printWindow.document.close();

            printWindow.onload = function() {
                printWindow.print();
                printWindow.close();
            };
        }
    </script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
$(document).ready(function() {
    let debounceTimer;
    let ajaxRequest; 

    // Search functionality
    $('#searchInput').on('input', function() {
        clearTimeout(debounceTimer); // Clear the previous timer
        let searchTerm = $(this).val().trim(); 

        $('#paginationContainer').css('display', 'none');

        // Set a new timer
        debounceTimer = setTimeout(function() {
            if (searchTerm.length > 0) {
                if (ajaxRequest) {
                    ajaxRequest.abort();
                }

                // Make the AJAX request
                ajaxRequest = $.ajax({
                    url: 'search_filter_products_stock_report.php',
                    type: 'GET',
                    data: {
                        search: searchTerm,
                        page: 1, 
                        records_per_page: <?php echo $records_per_page; ?>
                    },
                    success: function(data) {
                        $('#productTable tbody').html(data);
                        $('#paginationContainer').css('display', 'block');
                    },
                    error: function(jqXHR, textStatus) {
                        if (textStatus !== 'abort') { 
                            alert('Error searching for products');
                        }
                    }
                });
            } else {
                $('#productTable tbody').html('');
                $('#paginationContainer').css('display', 'block');
            }
        }, 300); 
    });
});


    function showPopup(product) {
        // Your popup code here
        const purchasePrice = parseFloat(product.default_purchase_price) || 0;
        const purchasePriceInc = parseFloat(product.purchase_price) || 0;
        const salePrice = parseFloat(product.default_sell_price) || 0;
        const salePriceInc = parseFloat(product.sale_price) || 0;
        const margin = parseFloat(product.profit_percent) || 0;
        const currentStock = parseFloat(product.current_stock) || 0;
        const unitSold = parseFloat(product.total_sale_qty) || 0;
        const unitPrice = parseFloat(product.sale_price) || 0;
        const stockValue = currentStock * unitPrice;
        const transferStock = parseFloat(product.total_quantity_transferred) || 0;

        // Set popup content
        document.getElementById('popup-title').innerText = product.product_name || '';
        document.getElementById('popup-brand').innerText = product.brand_name || '';
        document.getElementById('popup-product-name').innerText = product.product_name || '';
        document.getElementById('popup-product').innerText = product.product_name || '';
        document.getElementById('popup-category').innerText = product.category_name || '';
        document.getElementById('popup-sub-category').innerText = product.sub_category_name || '';
        document.getElementById('popup-alert-quantity').innerText = product.alert_quantity || '';
        document.getElementById('popup-tax-type').innerText = product.tax_type || '';
        document.getElementById('popup-unit').innerText = product.actual_name || '';
        document.getElementById('popup-purchase-price').innerText = purchasePrice.toFixed(2);
        document.getElementById('popup-purchase-price-inc').innerText = purchasePriceInc.toFixed(2);
        document.getElementById('popup-sale-price').innerText = salePrice.toFixed(2);
        document.getElementById('popup-sale-price-inc').innerText = salePriceInc.toFixed(2);
        document.getElementById('popup-margin').innerText = margin.toFixed(2);
        document.getElementById('popup-sku').innerText = product.sku || '';
        document.getElementById('popup-location').innerText = 'Fatima Lace Emporium'; // Assuming fixed location
        document.getElementById('popup-unit-price').innerText = salePrice.toFixed(2);
        document.getElementById('popup-current-stock').innerText = currentStock;
        document.getElementById('popup-stock-value').innerText = stockValue.toFixed(2);
        document.getElementById('popup-unit-sold-value').innerText = unitSold.toFixed(2);
        document.getElementById('popup-unit-transfered-value').innerText = transferStock.toFixed(2);
        document.getElementById('popup-image').src = `img/${product.image || ''}`;

        document.getElementById('popup').style.display = 'block';
    }

    // Function to close the popup
    function closePopup() {
        document.getElementById('popup').style.display = 'none';
    }
</script>




    <style>
        /* Popup styling */
        #popup {
            display: none;
            position: fixed;
            top: 1%;
            left: 50%;
            transform: translateX(-50%);
            width: 90%;
            max-width: 1100px;
            /* Adjust width as needed */
            background: white;
            border: 1px solid #ccc;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
            padding: 20px;
            z-index: 1000;
            max-height: 104vh;
            /* Ensure it doesn't exceed viewport height */
            overflow-y: auto;
            /* Enable scrolling if content exceeds height */
            border-radius: 10px;
        }

        /* Popup header styling */
        #popup-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 2px solid #ddd;
            padding-bottom: 10px;
            position: relative;
        }

        /* Popup close button styling */
        #popup-close {
            cursor: pointer;
            font-size: 24px;
            color: #333;
        }

        /* Popup image styling */
        #popup-image {
            width: 200px;
            /* Adjust size as needed */
            height: auto;
            border-radius: 5px;
        }

        /* Popup title styling */
        #popup-title {
            font-size: 24px;
            font-weight: bold;
            color: #333;
        }

        /* Popup details styling */
        #popup-details {
            margin-top: 20px;
            border-bottom: 2px solid #ddd;
            padding-bottom: 10px;
        }

        .detail-row {
            justify-content: space-between;
            padding: 5px 0;
        }

        .detail-label {
            font-weight: bold;
            color: #555;
        }

        .detail-value {
            font-size: 16px;
            color: #333;
        }

        /* Popup content styling */
        #popup-content,
        #popup-additional-info {
            margin-top: 20px;
        }

        #popup-content,
        #popup-additional-info table {
            width: 100%;
            border-collapse: collapse;
        }

        #popup-content,
        #popup-additional-info,
        table th,
        #popup-content,
        #popup-additional-info table td {
            padding: 12px;
            color: black;
            border: 1px solid #ddd;
            text-align: left;
        }

        .header-row {
            background-color: #2bcc8e;
            color: #fff;
            font-size: 13.4px;
            font-weight: bold;
        }
    </style>



    <!-- Wrapper END -->
    <!-- Footer -->
    <footer class="iq-footer">
        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-6">
                    <ul class="list-inline mb-0">
                        <li class="list-inline-item"><a href="privacy-policy.html">Privacy Policy</a></li>
                        <li class="list-inline-item"><a href="terms-of-service.html">Terms of Use</a></li>
                    </ul>
                </div>
                <div class="col-lg-6 text-right">
                    Copyright <span id="copyright">
                        <script>
                            document.getElementById('copyright').appendChild(document.createTextNode(new Date()
                                .getFullYear()))
                        </script>
                    </span> <a href="#">Vito</a> All Rights Reserved.
                </div>
            </div>
        </div>
    </footer>
    <nav class="iq-float-menu">
        <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
        <label class="iq-float-menu-open-button" for="menu-open">
            <span class="lines line-1"></span>
            <span class="lines line-2"></span>
            <span class="lines line-3"></span>
        </label>
        <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
            data-mode="rtl"><i class="ri-text-direction-r"></i></button>
        <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
            id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
        <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                class="ri-palette-line"></i></button>
    </nav>
    <!-- Footer END -->
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <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/jspdf-autotable/3.5.13/jspdf.plugin.autotable.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            // Simulate a loading delay
            setTimeout(function() {
                document.getElementById("loading_data").style.display = "none"; // Hide loading
                document.getElementById("content").style.display = "block"; // Show content
            }, 2000); // Change the duration as needed
        });
    </script>
<script>
function exportToCSV() {
    const table = document.getElementById('productTable'); // Get the specific table
    const checkedColumns = Array.from(document.querySelectorAll('.column-checkbox:checked')).map(cb => cb.getAttribute('data-column'));

    if (checkedColumns.length === 0) {
        alert("Please select at least one column to export.");
        return;
    }

    const csvContent = Array.from(table.querySelectorAll('tbody tr')).map(row => {
        const cols = [];
        checkedColumns.forEach(column => {
            let cellValue = ''; // Initialize cellValue

            // Populate cellValue based on column
            switch (column) {
                case 'sku':
                    cellValue = row.cells[0]?.innerText || ''; // SKU
                    break;
                case 'product':
                    cellValue = row.cells[1]?.innerText || ''; // Product
                    break;
                case 'unit_purchase_price':
                    cellValue = row.cells[2]?.innerText || ''; // Unit Purchase Price
                    break;
                case 'current_stock':
                    cellValue = row.cells[3]?.innerText || ''; // Current Stock
                    break;
                case 'current_stock_value':
                    cellValue = row.cells[4]?.innerText || ''; // Current Stock Value
                    break;
                case 'total_unit_sold':
                    cellValue = row.cells[5]?.innerText || ''; // Total Unit Sold
                    break;
                case 'total_unit_transfered':
                    cellValue = row.cells[6]?.innerText || ''; // Total Unit Transferred
                    break;
            }

            cols.push(cellValue); // Push the cell value to the cols array
        });
        return cols.join(','); // Join columns with commas
    }).join('\n'); // Join rows with newlines

    const blob = new Blob([csvContent], {
        type: 'text/csv;charset=utf-8;'
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'products.csv';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

function exportToExcel() {
    const table = document.getElementById('productTable'); // Get the specific table
    const checkedColumns = Array.from(document.querySelectorAll('.column-checkbox:checked')).map(cb => cb.getAttribute('data-column'));

    if (checkedColumns.length === 0) {
        alert("Please select at least one column to export.");
        return;
    }

    const exportTable = document.createElement('table');

    // Create header row for the export table
    const headerRow = exportTable.insertRow();
    checkedColumns.forEach(column => {
        const newHeaderCell = headerRow.insertCell();
        newHeaderCell.textContent = column.charAt(0).toUpperCase() + column.slice(1).replace(/_/g, ' '); // Capitalize header
    });

    Array.from(table.querySelectorAll('tbody tr')).forEach(row => {
        const newRow = exportTable.insertRow();
        checkedColumns.forEach(column => {
            let cellValue = '';

            // Populate cellValue based on column
            switch (column) {
                case 'sku':
                    cellValue = row.cells[0]?.innerText || ''; // SKU
                    break;
                case 'product':
                    cellValue = row.cells[1]?.innerText || ''; // Product
                    break;
                case 'unit_purchase_price':
                    cellValue = row.cells[2]?.innerText || ''; // Unit Purchase Price
                    break;
                case 'current_stock':
                    cellValue = row.cells[3]?.innerText || ''; // Current Stock
                    break;
                case 'current_stock_value':
                    cellValue = row.cells[4]?.innerText || ''; // Current Stock Value
                    break;
                case 'total_unit_sold':
                    cellValue = row.cells[5]?.innerText || ''; // Total Unit Sold
                    break;
                case 'total_unit_transfered':
                    cellValue = row.cells[6]?.innerText || ''; // Total Unit Transferred
                    break;
            }

            const newCell = newRow.insertCell();
            newCell.textContent = cellValue; // Set the cell's text
        });
    });

    const workbook = XLSX.utils.table_to_book(exportTable, {
        sheet: "Products"
    });
    XLSX.writeFile(workbook, 'products.xlsx');
}
</script>



    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // Attach event listeners for dynamically added elements
            document.body.addEventListener('click', (event) => {
                const selectButton = event.target.closest('.select-button');
                const selectOptions = event.target.closest('.select-options');

                if (selectButton) {
                    const dropdown = selectButton.nextElementSibling; // select-options
                    dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
                    event.stopPropagation(); // Prevent the click from propagating to window
                } else if (!selectOptions || !selectOptions.contains(event.target)) {
                    // Hide all dropdowns if the click is outside of any dropdown
                    document.querySelectorAll('.select-options').forEach((dropdown) => {
                        if (dropdown.style.display === 'block') {
                            dropdown.style.display = 'none';
                        }
                    });
                }
            });

            // Handle option selection
            document.body.addEventListener('click', (event) => {
                if (event.target.tagName === 'A' && event.target.closest('.select-options')) {
                    const selectButton = event.target.closest('.custom_select').querySelector('.select-button');
                    selectButton.querySelector('.selected-option').textContent = event.target.textContent;
                    event.target.closest('.select-options').style.display = 'none';
                }
            });
        });
    </script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        function openPopup(productId) {
            fetch('fetch_product_data.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'product_id=' + productId,
                })
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        alert('Error: ' + data.error);
                    } else {
                        // Populate the modal with data
                        document.getElementById('productName').innerText = data.name;
                        document.getElementById('overallStock').innerText = data.overallStock;
                        document.getElementById('OpeningStock').innerText = data.OpeningStock;
                        document.getElementById('currentStock').innerText = data.currentStock;

                        // Store product ID for use when editing stock
                        document.getElementById('stockPopup').dataset.productId = productId;

                        // Show the popup
                        document.getElementById('stockPopup').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An unexpected error occurred.');
                });
        }


        function updateStock() {
            // Get the updated current stock value
            const updatedStock = document.getElementById('currentStocksaleInput').value;
            const productId = document.getElementById('stockPopup').dataset.productId;

            // Make an AJAX request to update the stock
            fetch('update_stock.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'product_id=' + productId + '&current_stock=' + updatedStock,
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Stock updated successfully!');
                        closePopupstock();
                    } else {
                        alert('Error: ' + data.error);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An unexpected error occurred.');
                });
        }

        function closePopupstock() {
            document.getElementById('stockPopup').style.display = 'none';
        }
    </script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#search").on("input", function() {
                var query = $(this).val();
                if (query.length > 0) {
                    $.ajax({
                        url: "suggest_product.php",
                        type: "GET",
                        data: {
                            term: query
                        },
                        success: function(data) {
                            var suggestions = JSON.parse(data);
                            $("#suggestions").empty().show();
                            suggestions.forEach(function(item) {
                                $("#suggestions").append("<div class='suggestion-item'>" + item + "</div>");
                            });
                        }
                    });
                } else {
                    $("#suggestions").hide();
                }
            });

            $(document).on("click", ".suggestion-item", function() {
                $("#search").val($(this).text()); // Set the input value
                $("#suggestions").hide(); // Hide suggestions

                // Automatically trigger the search
                $("form").submit(); // Submit the form
            });

            $(document).click(function(e) {
                if (!$(e.target).closest("#suggestions, #search").length) {
                    $("#suggestions").hide(); // Hide suggestions if clicked outside
                }
            });
        });

        function clearFilter() {
            window.location.href = 'stock_report.php'; // Clear filter
        }
    </script>

    <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>