<?php
        
        require_once __DIR__  . '/config/db.php';
        require_once __DIR__ . '/config/inventory.php';
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        if (!isset($_SESSION['user_id'])) {
            header('location:login.php');
            exit;
        }
        
	if (isset($_GET['ajax']) && $_GET['ajax'] == 'search' && isset($_GET['searchword'])) {
    if (ob_get_length()) ob_end_clean();

    header('Content-Type: application/json; charset=utf-8');

    require_once __DIR__  . '/config/db.php';
    require_once __DIR__ . '/config/inventory.php';

    $inventory = new Inventory();
    $searchword = $_GET['searchword'];
    $result = $inventory->search_bar($searchword);
    
    date_default_timezone_set('Europe/Budapest');

    echo json_encode($result ?: ["error" => "Nincs találat"], JSON_UNESCAPED_UNICODE);
    exit;
}      
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr" crossorigin="anonymous">
    <link rel="stylesheet" href="./style/style.css">
    <title>ART Inventory</title>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js" integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q" crossorigin="anonymous"></script>
    <style>
        .col-list{
            max-width:350px;
        }

	#searchInput{
            min-width: 250px!important;
            max-height:31px!important;
            margin-top: 20px!important;
            margin-bottom: -15px!important;
        }
    </style>
</head>
<body class="dark-theme">
    <div class="container">
    <?php
        include './header.php';
    ?>
<div class="container text-center">

<div class="col-auto">
    <input id="searchInput" class="form-control form-control-sm form-select-sort mt-2" type="text" placeholder="Search" onkeyup="searchBar(this)">
  </div>
  <div id="innerContent">
  <div class="row my-5 align-middle">
    <div class="col-4 border rounded-3 mx-2 col-list">
    <h2 class='my-3'>Manufacturers</h2>
      <table class="table table-hover ">
        <thead>
            <tr>
            <th scope="col">Manufacturer</th>
            <th scope="col">Quantity</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $inventory = new Inventory();
                $list = $inventory->maunfacturer_count();
                foreach ($list as $x) {
                    echo "<tr><td class='text-start'>".$x['name']."</td><td>".$x['counted']."</td></tr>";
                }
            ?>
        </tbody>
      </table>
    </div>
    <div class="col-4 border rounded-3 mx-2 col-list">
    <h2 class='my-3'>Footprints</h2>
      <table class="table table-hover ">
        <thead>
            <tr>
            <th scope="col">Footprint</th>
            <th scope="col">Quantity</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $inventory = new Inventory();
                $list = $inventory->footprint_count();
                foreach ($list as $x) {
                    echo "<tr><td class='text-start'>".$x['name']."</td><td>".$x['counted']."</td></tr>";
                }
            ?>
        </tbody>
        </table>
    </div>
  </div>
</div>
</div>
</div>

<script>
    function searchBar(inputElement) {
        let searchword = inputElement.value;
        console.log(searchword);

        searchword = searchword.toLowerCase();
        //document.getElementById("routeLink").innerHTML='<a href="./components.php" class="routeLinkClass">Components</a>';

        fetch("?ajax=search&searchword=" + encodeURIComponent(searchword))
            .then(response => response.json())
            .then(data => {
                console.clear();
                console.log("Search results:", data);

                if (data.error) {
                    console.warn(data.error);
                    document.getElementById("innerContent").innerHTML = "";
                } else {
                    document.getElementById("innerContent").innerHTML = `
                    <table class="table table-hover mx-auto bgColorChange" id="inventoryTable">
    <thead>
      <tr>
        <th>Manufacturer</th>
        <th>Name</th>
        <th>Type</th>
        <th>Footprint</th>
        <th>Component Number</th>
        <th>Tolerance</th>
        <th>Max Current</th>
        <th>Max Voltage</th>
        <th>Location</th>
        <th>Description</th>
        <th>Quantity</th>
      </tr>
    </thead>
    <tbody id="tableBody"></tbody></table>`;
                    document.getElementById("tableBody").innerHTML = data.map(item => 
                        `<tr>
                            <td>${item.manufacturer}</td>
                            <td>${item.name}</td>
                            <td>${item.category}</td>
                            <td>${item.footprint}</td>
                            <td>${item.componentnumber}</td>
                            <td>${item.tolerance}</td>
                            <td>${item.maxcurrent}</td>
                            <td>${item.maxvoltage}</td>
                            <td>${item.location}</td>
                            <td>${item.description}</td>
                            <td>${item.sumquant || 0} pcs</td>
                        </tr>`
                    ).join('');
                }
            })
        .catch(error => console.error("Hiba:", error));
    }


</script>

<?php
include './footer.php';
?>

</body>
</html>
