<?php

function getTotalProductCount() {
    // Connect to the database
    $db = mysqli_connect("localhost", "root", "", "shangrilaperfumes");

    // Check connection
    if (!$db) {
        return "Error: Unable to connect to the database";
    }

    // Query to get total product count
    $query = "SELECT COUNT(*) as total FROM test_table";
    $result = mysqli_query($db, $query);

    // Check if query executed successfully
    if ($result) {
        $row = mysqli_fetch_assoc($result);
        return $row['total'];
    } else {
        return "Error: Unable to fetch total product count";
    }

    // Close the database connection
    mysqli_close($db);
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Shangri-la Perfumes Dashboard</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="styles.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <style>
    
    tr:first-child {
    background-color: #28a4c9;
   color: white;  
   
      }
.table-responsive{
 padding: 50px;
 overflow-x:unset !important ;
 background-color: white;
 }
.table-striped>tbody>tr:nth-of-type(odd) {
background-color: unset;

}
tbody tr:nth-of-type(1) {
background-color: #C1E1C1 !important;
color: black !important;
}
table{
text-align: center !important;
}
thead th {
text-align: center;
}

.loader {
            border: 5px solid #f3f3f3;
            border-top: 5px solid #3498db;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            display: none; /* Initially hide the loader */
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -25px;
            margin-left: -25px;
            z-index: 9999;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
</style>
</head>
<body>
<?php include('header.php'); ?>
<!-- <header>
        <h1 style="color:white;">Shangrilla Perfumes</h1>
        <div class="container">
        <ul>
        <li style="color:white;"><a href="text.php">Home</a></li>
        
        <li style="color:white;"><a href="manage_vendor.php">Manage Vendors</a></li>
        
        </ul>
        </div> 
        </div>
       
 </header> -->
 <div class="row form-container">
    <form action="import_export.php" method="post" enctype="multipart/form-data">
        <label for="file">Select Excel File to Import:</label>
        <input type="file" name="file" id="file">
        <!-- <label for="vendor">Select Vendor:</label>
        <select name="vendor" id="vendor">
          
        </select> -->
        <button  action="import_export.php" name="map"  id="mapButton" type="submit" style="width: 50%;margin-top: 30px;margin-left: 26%;">Map</button>
        <div class="loader" id="loader"></div>
    <!-- <button type="submit" name="import" onclick="showPopupAndRefresh('File Imported')" style="width: 150px; margin: 0 auto; display: block;">Import</button> -->

    </form>
    <form class="form-horizontal" action="import_export.php" method="post" name="upload_excel" enctype="multipart/form-data">
        <div class="form-group">
        <label class="col-md-4 control-label" for="filebutton">Export Product  File</label>
    <button type="submit" name="export" id="exportButton" onclick="showExportLoader()">Export to Excel</button>
    <div class="loader" id="exportLoader"></div>
    <label class="col-md-4 control-label" for="filebutton">Delete All Records</label>
    <button type="submit" name="delete">Delete </button>
    </div>
    <div id="total-product-count-container" class="form-horizontal" style="margin: 20px !important; border: 1px solid black !important; width: 92%; text-align: center; padding: 18px; border-radius: 2px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
    <label style="font-size: 19px; font-weight: bold;">Total Products:</label>
    <span id="total-product-count" style="font-size: 20px; color: #3498db; font-weight: bold;"><?php echo getTotalProductCount(); ?></span>
    </form>
 </div>
 <div class="row-count-container">
        <label style="padding: 15px;">Search Result Count:</label>
        <div id="row-count" class="row-count">  Search First...</div>
</div>
</div>
<form action="" class="search" style="height: 178px;margin-left: 82px;background-color: white;    border: 1px solid;">
         <div class="form-group">
            
            <label class="col-md-4 control-label" for="search" style="font-size: 25px; margin-top: -20px;"  >Search Record</label>
            <div class="col-md-4">
                <input type="text" name="search" id="search" class="form-control" placeholder="Enter UPC to See all Prices">
            </div>
            <div class="col-md-4">
            <button type="button" id="searchBtn" class="btn btn-info" style="width: 150px; margin: 0 auto; display: block;">Search</button>

            </div>
        </div>
            </form>
        </div>	
        <div id="searchResultsTable">
       </div>

</body>

<script>

    // JavaScript function to display a popup message and refresh the page
    function showPopupAndRefresh(message) {
        alert(message);
        location.reload(true); // Reload the page (true for a hard refresh)
    }
    
    document.getElementById("searchBtn").addEventListener("click", function () {
        var search = document.getElementById("search").value.toUpperCase();
        $.post("query.php", {
            search: search
        },
        function (data, textStatus) {
            document.getElementById("searchResultsTable").innerHTML = data;
            // Call updateRowCount after the search to update the total records
            updateRowCount();
        });
    });
 
    function updateRowCount() {
        var rowCountElement = document.getElementById("row-count");
        var table = document.getElementById("myTable");

        if (table) {
            var rowCount = table.rows.length - 1; // Exclude the header row
            rowCountElement.innerHTML =  rowCount;
        } else {
            rowCountElement.innerHTML = "Search First";
        }
    }


    function searchRecords() {
        var searchTerm = document.getElementById("search").value.toUpperCase();
        var table = document.getElementById("myTable");
        var rows = table.getElementsByTagName("tr");
        var searchResults = [];

        for (var i = 1; i < rows.length; i++) {
            var cells = rows[i].getElementsByTagName("td");
            var matchFound = false;

            for (var j = 0; j < cells.length; j++) {
                var cellText = cells[j].textContent || cells[j].innerText;

                // Check for a match in UPC or other columns
                if (cellText.toUpperCase().indexOf(searchTerm) > -1) {
                    matchFound = true;
                    break;
                }
            }

            if (matchFound) {
                searchResults.push({
                    UPC: cells[0].textContent,
                    Product: cells[2].textContent,
                    Vendor: cells[3].textContent,
                    Price: cells[4].textContent,
                });
            }
        }
        // Sort search results by "price" column in descending order
        searchResults.sort(function (a, b) {
            return parseFloat(a.price) - parseFloat(b.price);
        });

        // Display search results
        display_search_results(searchResults);
        // Call updateRowCount after the search to update the total records
        updateRowCount();

    }
    document.addEventListener("DOMContentLoaded", function () {
        updateTotalProductCount();
    });
    document.getElementById('mapButton').addEventListener('click', function() {
    window.location.href = 'import_export.php';
  });
  
  function showLoader(loaderId, message) {
            document.getElementById(loaderId).style.display = "block";
        }

        // Function to hide the loader
        function hideLoader(loaderId) {
            document.getElementById(loaderId).style.display = "none";
        }

        // Add an event listener to the import button
        document.querySelector('button[name="map"]').addEventListener('click', function() {
            // Show the loader when the import button is clicked
            showLoader('loader');
        });

        // Simulating a successful import
        setTimeout(function() {
            // Hide the loader after the successful import
            hideLoader('loader');
        }, 2000); 

        document.querySelector('button[name="export"]').addEventListener('click', function() {
            // Show the loader when the export button is clicked
            showLoader('exportLoader', 'You will retrieve all products from all vendors. ...');
            // Simulating a successful export
            setTimeout(function() {
                // Hide the loader after the successful export
                hideLoader('exportLoader');
            }, 20000);
        });

</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>
    <!-- <script src="script.js"></script> -->
</html>
