<?php
include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

// category list
$categories_res = $db->query("stock_categories", "SELECT * FROM stock_categories WHERE 1 ORDER BY `name` ASC");
$category_list = '';
while ($category = $categories_res->fetch_assoc()) {
    $category_list .= '<option value="' . $category['record_id'] . '">' . $category['name'] . '</option>';
}

// suppliers list
$suppliers_res = $db->query("suppliers", "SELECT * FROM suppliers WHERE 1 ORDER BY `name` ASC");
$supplier_list = '';
while ($supplier = $suppliers_res->fetch_assoc()) {
    $supplier_list .= '<option value="' . $supplier['record_id'] . '">' . $supplier['name'] . '</option>';
}

$stock_res = $db->query("stock", "SELECT * FROM stock WHERE stock_type = 0 ORDER BY `description` ASC");
?>

<div class="container"
    style="position: sticky; top: 0; display: flex; flex-direction: column;background-color: lightgray;">
    <div style=" display: flex; flex-direction: row; padding: 1vw; ">
        <input type="text" id="search_details" style='width: 30vw; margin-right: 3vw;border-radius: 1vw;padding: 1vw;'
            placeholder="Search..." class="submit" />
        <input type="submit" onclick="search()" value="SEARCH" class="submit_btn" />
    </div>
    <script>
        function search() {
            search_details = document.getElementById('search_details').value.toUpperCase();
            let textareas = document.getElementsByTagName('textarea');
            showLoading();
            let found = false;
            for (let i = 0; i < textareas.length; i++) {
                if (textareas[i].value.includes(search_details)) {
                    if (!found) {
                        textareas[i].focus();
                        found = true;
                    }
                    textareas[i].style.backgroundColor = 'yellow';
                } else {
                    textareas[i].style.backgroundColor = 'white';
                }
            }
            hideLoading();


        }
    </script>
</div>

<div id="loadingOverlay"
    style="display: none; position: sticky; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(255, 255, 255, 0.8); z-index: 1000; display: flex; justify-content: center; align-items: center;">
    <div class="spinner"
        style="border: 8px solid #f3f3f3; border-top: 8px solid #3498db; border-radius: 50%; width: 60px; height: 60px; animation: spin 1s linear infinite;">
    </div>
</div>

<style>
    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    .table-responsive {
        width: 100%;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        font-size: 14px;
        color: #333;
        background: #fff;
        box-shadow: 0 2px 8px rgb(0 0 0 / 0.1);
        border-radius: 8px;
        overflow: hidden;
        min-width: 700px;
    }

    thead th {
        position: sticky;
        top: 0;
        background-color: #1e90ff;
        color: white;
        text-align: left;
        padding: 12px 15px;
        font-weight: 600;
        letter-spacing: 0.03em;
        user-select: none;
        z-index: 1;
    }

    table td {
        padding: 12px 15px;
        border-bottom: 1px solid #eaeaea;
    }

    table tr:nth-child(even) {
        background: #f9f9f9;
    }

    table tbody tr:hover {
        background-color: #d0e7ff;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }
</style>

<script>
    function showLoading() {
        document.getElementById('loadingOverlay').style.display = 'flex';
    }

    function hideLoading() {
        document.getElementById('loadingOverlay').style.display = 'none';
    }

    window.addEventListener("load", function () {
        hideLoading();
    });

    function change(obj, column, record_id) {
        var value = obj.value;
        var data = {
            column: column,
            value: value,
            record_id: record_id
        };
        var row = obj.closest('tr');

        fetch("update_data.ajax.php", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: new URLSearchParams(data)
        })
            .then(response => response.text())
            .then(result => {
                row.style.transition = "background-color 0.5s ease";
                row.style.backgroundColor = result.trim() === '1' ? "green" : "red";
                setTimeout(() => row.style.backgroundColor = "", 1000);
            })
            .catch(error => console.error('Error:', error));
    }
</script>

<div class="table-responsive">
    <table class="table">
        <!-- <thead style="position: sticky; top: 0;">
            <tr>
                <th>Description</th>
                <th>Category</th>
                <th>Stock Type</th>
                <th>Supplier</th>
                <th>Package Size</th>
                <th>Cost Price</th>
                <th>Max</th>
                <th>Min</th>
                <th>Barcode</th>
                <th>Item Code</th>
                <th>Adjustment Type</th>
                <th>Amount</th>
            </tr>
        </thead> -->
        <tbody>
            <?php $index = 0;
            while ($stock = $stock_res->fetch_assoc()) { ?>
                <tr>
                    <td>
                        <label>Description</label>
                        <textarea class="inputs" style="overflow:hidden; height:auto;"
                            onchange="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px'; change(this, 'description', '<?php echo $stock['record_id']; ?>')"><?php echo $stock['description']; ?></textarea>
                    </td>
                    <td>
                        <label>Category</label>
                        <select class="inputs" id='category_<?php echo $index; ?>'
                            onchange="change(this, 'category_id', '<?php echo $stock['record_id']; ?>')">
                            <option value="-1">Select category</option>
                            <?php echo $category_list; ?>
                        </select>
                        <script>document.getElementById('category_<?php echo $index; ?>').value = '<?php echo $stock['category_id']; ?>';</script>
                    </td>
                    <td>
                        <label>Stock Type</label>
                        <select class="inputs" id="stock_type_<?php echo $index; ?>"
                            onchange="change(this, 'stock_type', '<?php echo $stock['record_id']; ?>')">
                            <option value="-1">Select stock type</option>
                            <option value="0">STOCK</option>
                            <option value="1">NON STOCK</option>
                            <option value="2">UNITS</option>
                        </select>
                        <script>document.getElementById('stock_type_<?php echo $index; ?>').value = '<?php echo $stock['stock_type']; ?>';</script>
                    </td>
                    <td>
                        <label>Supplier</label>
                        <select class="inputs" id='supplier_<?php echo $index; ?>'
                            onchange="change(this, 'supplier_id', '<?php echo $stock['record_id']; ?>')">
                            <option value="-1">Select supplier</option>
                            <?php echo $supplier_list; ?>
                        </select>
                        <script>document.getElementById('supplier_<?php echo $index; ?>').value = '<?php echo $stock['supplier_id']; ?>';</script>
                    </td>
                    <td>
                        <label>Package Size</label>
                        <input type="text" class="inputs" value="<?php echo $stock['packaging_size']; ?>"
                            onchange="change(this, 'packaging_size', '<?php echo $stock['record_id']; ?>')" />
                    </td>
                    <td>
                        <label>Cost Price</label>
                        <input step="0.001" type="text" class="inputs" value="<?php echo $stock['cost_price']; ?>"
                            onchange="change(this, 'cost_price', '<?php echo $stock['record_id']; ?>')" />
                    </td>
                    <td>
                        <label>Max</label>
                        <input step="0.001" type="text" class="inputs" value="<?php echo $stock['max']; ?>"
                            onchange="change(this, 'max', '<?php echo $stock['record_id']; ?>')" />
                    </td>
                    <td>
                        <label>Min</label>
                        <input step="0.001" type="text" class="inputs" value="<?php echo $stock['min']; ?>"
                            onchange="change(this, 'min', '<?php echo $stock['record_id']; ?>')" />
                    </td>
                    <td>
                        <label>Barcode</label>
                        <input type="text" class="inputs" value="<?php echo $stock['barcode']; ?>"
                            onchange="change(this, 'barcode', '<?php echo $stock['record_id']; ?>')" />
                    </td>
                    <td>
                        <label>Item Code</label>
                        <input type="text" class="inputs" value="<?php echo $stock['item_code']; ?>"
                            onchange="change(this, 'item_code', '<?php echo $stock['record_id']; ?>')" />
                    </td>
                    <td>
                        <label>Adjustment Type</label>
                        <select class="inputs" id="adjustment_type_<?php echo $index; ?>"
                            onchange="change(this, 'adjustment_type', '<?php echo $stock['record_id']; ?>')">
                            <option value="-1">Select adjustment type</option>
                            <option value="X">Multiply By</option>
                            <option value="/">Divide By</option>
                        </select>
                        <script>document.getElementById('adjustment_type_<?php echo $index; ?>').value = '<?php echo $stock['adjustment_type']; ?>';</script>
                    </td>
                    <td>
                        <label>Amount</label>
                        <input type="text" class="inputs" value="<?php echo $stock['amount']; ?>"
                            onchange="change(this, 'amount', '<?php echo $stock['record_id']; ?>')" />
                    </td>
                </tr>
                <?php $index++;
            } ?>
        </tbody>
    </table>
</div>