<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$formname = 'Opening Stock';
$maindb = 'prodsize';
$file = 'openstock.php';
$trandbexist = 0;
$grid = '';
$keyfld = "code";
$focusfield = "name";

$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

if (isset($_POST['submit'])) {
    foreach ($_POST['code'] as $idx => $code) {
        if (trim($code) === '')
            continue;

        $size = $_POST['size'][$idx];
        $newCost = $_POST['cost'][$idx];
        $newRate = $_POST['selling'][$idx];

        // Fetch existing values from DB
        $sql = "SELECT cost, rate FROM `$maindb` WHERE code = ? AND size = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ss', $code, $size);
        $stmt->execute();
        $stmt->bind_result($oldCost, $oldRate);
        $stmt->fetch();
        $stmt->close();

        // Skip update if nothing changed
        if ($newCost == $oldCost && $newRate == $oldRate) {
            continue;
        }

        // Perform update only if values changed
        $update = $conn->prepare(
            "UPDATE `$maindb` SET cost = ?, rate = ? WHERE code = ? AND size = ?"
        );
        $update->bind_param('iiss', $newCost, $newRate, $code, $size);
        $update->execute();
        $update->close();
    }

    updmess();
    header("Refresh: 1; openstock.php");
}


$senable = "";
$cenable = "";

include("includes/linkshead.php");
?>
<script>
    $(document).ready(function () {
        $(".savetabl").hide();

        $("#proceed").click(function () {
            var itemgrp = $('#itemgrp').val();
            var subgrp = $('#subgrp').val();

            $.ajax({
                type: "GET",
                url: "opnstksrch.php",
                data: {
                    itemgrp: itemgrp,
                    subgrp: subgrp
                },
                success: function (result) {
                    if (result != '') {
                        $(".savetabl").show();
                        $(".proctabl").hide();
                    } else {
                        $(".proctabl").show();
                    }
                    $("#data").html(result);

                }
            });
        });
        document.querySelector("form").addEventListener("submit", function () {
            const btn = document.getElementById('submit');
            const spinner = btn.querySelector('.spinner-border');
            const label = btn.querySelector('.btn-text');

            label.textContent = 'Saving...';
            spinner.classList.remove('d-none');

            // Let the browser capture the button value first,
            // then disable it to block double-clicks.
            setTimeout(() => btn.disabled = true, 0);
        });

    });
</script>
</head>

<body>
    <form action='' method='POST'>
        <!-- Default box -->
        <div class="row">
            <div class="col-lg-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title"><?php echo $formname; ?></h3>
                    </div>

                    <div class="panel-body proctabl">
                        <div class="row">
                            <div class="col-lg-4 col-md-1 col-sm-3 col-xs-3 text-right pad">
                                <label class="label-control marg">Product Group</label>
                            </div>
                            <div class="col-lg-3 col-md-1 col-sm-3 col-xs-3 pad">
                                <select id="itemgrp" name="itemgrp" style="height:35px;" class="itemgrp form-control">
                                    <option></option>
                                    <?php
                                    $mown = mysqli_query($conn, "SELECT code, `name` FROM `itemgrp` ") or die(mysqli_error($conn));
                                    while ($trow = mysqli_fetch_array($mown)) {
                                        echo "<option value=$trow[code]>$trow[name]</option>";
                                    }
                                    ?>
                                </select>
                                <input type="text" id="custhidden" hidden>
                            </div>
                        </div>
                    </div>
                </div>
                <div class='panel-footer'>
                    <div style="overflow: auto;">
                        <table class="table-condensed proctabl" style="margin: 0 auto;">
                            <tr>
                                <td>
                                    <input id="proceed" type='button' name='proceed' value='Proceed'
                                        class="btn btn-success">
                                </td>
                                <td>
                                    <input class="btn btn-danger" type="button"
                                        onClick="window.location.href = '<?= 'default.php' ?>'" value="Exit" />
                                </td>
                            </tr>
                        </table>

                        <table class="table-condensed savetabl" style="margin: 0 auto;">
                            <tr>
                                <td>
                                    <!-- Save button with spinner -->
                                    <button id="submit" type="submit" name="submit" class="btn btn-success">
                                        <span class="btn-text">Save</span>
                                        <span class="spinner-border spinner-border-sm ms-1 d-none" role="status"
                                            aria-hidden="true"></span>
                                    </button>
                                </td>
                                <td>
                                    <input class="btn btn-danger" type="button"
                                        onClick="window.location.href = '<?= $file ?>'" value="Exit" />
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>



                <div class="col-lg-12" id="data" style="overflow-x: scroll;height:500px;">
                </div>
            </div>
        </div>
    </form>


    <?php include("includes/linksfoot.php"); ?>
</body>

</html>