<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$qty = "";
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

// ✅ No date filtering on stock page anymore
$filterStockView = "";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Stock Setup</h3>
            </div>
            <?php if (isset($_GET['view'])) { ?>
                <!-- (Date filters removed intentionally) -->
            <?php } ?>
            <hr>
            <?php if ($_SESSION['sess_role'] == 'VEC') {
                if (isset($_GET['view'])) { ?>
                    <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;" href="?add">Add <i
                                class="mdi-content-add-box"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>

            <?php
            if (isset($_GET['view'])) {
                ?>
                <?php if (isset($_GET['sucess'])) { ?>
                    <div id='card-alert' class='card green lighten-5'>
                        <div class='card-content green-text'>
                            <p>Successfully updated!</p>
                        </div>
                        <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                        </button>
                    </div>
                <?php } ?>
                <?php if (isset($_GET['error'])) { ?>
                    <div id='card-alert' class='card orange lighten-5'>
                        <div class='card-content orange-text'>
                            <p>WARNING : <strong>Attention! </strong>Error occurred!</p>
                        </div>
                        <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                        </button>
                    </div>
                <?php } ?>
                <div class="table-datatables">
                    <table id="data-table-simple" class="responsive-table display">
                        <thead>
                        <tr>
                            <th>Product</th>
                            <th>Carton/Bags</th>
                            <th>Dozen/Quantity</th>
                            <th>Total Cost</th>
                        </tr>
                        </thead>

                        <tbody>
                        <?php
                        // Initialize totals
                        $totalQty      = 0;
                        $totalCost     = 0;
                        $totalCartons  = 0; // ✅ new total for cartons

                        $qry = Stock::GetStockSetupList($filterStockView);
                        if ($qry) {
                            foreach ($qry as $qery) {
                                $product = ProductSetup::GetProductSetupById($qery->product_id);
                                $user    = User_setup::GetUserSetupId($qery->user_id);

                                $rowQty   = (float)$qery->total_qty;
                                $rowCost  = (float)$qery->total_cost;

                                // ✅ cartons/bags FOR THIS PRODUCT ONLY
                                if (!empty($product->carton_pieces) && $product->carton_pieces > 0) {
                                    $rowCartons = $rowQty / $product->carton_pieces;
                                } else {
                                    $rowCartons = 0;
                                }

                                // accumulate totals
                                $totalQty     += $rowQty;
                                $totalCost    += $rowCost;
                                $totalCartons += $rowCartons;
                                ?>
                                <tr>
                                    <td><?php echo $product->name; ?></td>
                                    <td><?php echo number_format($rowCartons, 2); ?></td>
                                    <td><?php echo number_format($rowQty, 2); ?></td>
                                    <td><?php echo number_format($rowCost, 2); ?></td>
                                </tr>
                                <?php
                            }
                        }
                        ?>
                        </tbody>
                        <?php
                        // ✅ Totals Row aligned with headers:
                        // Product | Carton/Bags | Dozen/Quantity | Total Cost
                        echo "
                        <tr style='font-weight: bold; background: #f1f1f1; border-top: 2px solid #666;'>
                            <td class='center-align'>Totals:</td>
                            <td class='left-align'>".number_format($totalCartons, 2)."</td>
                            <td class='left-align'>".number_format($totalQty, 2)."</td>
                            <td class='left-align'>".number_format($totalCost, 2)."</td>
                        </tr>";
                        ?>
                    </table>
                </div>
                <?php

            } // close view


            if (isset($_GET['edit']) && !empty($_POST)) {
                extract($_REQUEST);
                $id = $_GET['id'];
                $data['product_id'] = $product_id;
                $data['qty'] = $qty;
                $data['user_id'] = $_SESSION['sess_userid'];
                $data['datetime'] = 'NOW()';

                $errors = array();
                // Validate the input

                if ((strlen($product_id) == 0))
                    array_push($errors, "Please select product");
                if ((strlen($qty) == 0))
                    array_push($errors, "Please enter Quantity");

                if (count($errors) == 0) {
                    $product = ProductSetup::GetProductSetupById($product_id);
                    if (!empty($product)) {
                        $availableStock = $product->availability;

                        $productInStock = Stock::GetStockSetupById($id);
                        if ($productInStock->qty > $qty) {
                            $qtyDiff = $productInStock->qty - $qty;
                            $totalStock = $availableStock - $qtyDiff;
                        } else if ($productInStock->qty < $qty) {
                            $qtyDiff = $qty - $productInStock->qty;
                            $totalStock = $availableStock + $qtyDiff;
                        } else {
                            $totalStock = $availableStock;
                        }
                        $dataProduct['availability'] = $totalStock;
                        ProductSetup::UpdateProductSetup($product_id, $dataProduct);
                    }

                    $q = Stock::UpdateStockSetup($id, $data);


                    if ($q) {
                        $output = '';
                        ?>
                        <script>window.location.href = '?view&sucess'</script>
                        <?php
                        echo "<div id='card-alert' class='card green lighten-5'>
                      <div class='card-content green-text'>
                        <p>SUCCESS : <strong>Attention! </strong>Submitted!</p>
                      </div>
                      <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                    } else {
                        $output = '';
                        echo "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>Some error occurred!</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                    }
                } else {
                    //Prepare errors for output
                    foreach ($errors as $val) {
                        $output .= "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>$val</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                    }
                }
            }
            if (isset($_GET['edit'])) {
                $id = $_GET['id'];
                if (empty($_POST)) {
                    $qry = Stock::GetStockSetupById($id);
                    $qty = $qry->qty;
                    $product_id = $qry->product_id;
                    $product = ProductSetup::GetProductSetupById($product_id);
                    $productname = $product->name;
                    $user = User_setup::GetUserSetupId($qry->user_id);
                    $username = $user->username;
                }
                if ($_REQUEST['id'] && isset($_REQUEST['v'])) {
                    ?>
                    <div class="row">
                    <!--  The form that will be parsed by jQuery before submit  -->
                    <div class="col s12 form-group">
                        <div class="col s8">
                            <div class="row">
                                <div class="col s6">Product Name:</div>
                                <span class="col s6"><?php echo $productname; ?></span>
                            </div>
                            <div class="row">
                                <div class="col s6">Quantity:</div>
                                <span class="col s6"><?php echo $qty; ?></span>
                            </div>
                            <div class="row">
                                <div class="col s6">User Name:</div>
                                <span class="col s6"><?php echo $username; ?></span>
                            </div>
                        </div>
                    </div>
                <?php } else {
                    ?>
                    <div class="row">
                        <!--  The form that will be parsed by jQuery before submit  -->
                        <form action="?edit&id=<?php echo $id ?>" method="post" id="stock_setup_form"
                              novalidate="novalidate">
                            <div class="col s12 form-group">
                                <div class="col s8">
                                    <div class="row">
                                        <?php echo $output; ?>
                                    </div>
                                    <div class="row">
                                        <span>(*) Mark Fields are mandatory</span><br/><br/>
                                    </div>
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <?php
                                            $filter = " where status = 'active' ORDER BY name";
                                            $qry = ProductSetup::GetProductSetupList($filter, $pageno = "null", $pagesize = "null");
                                            if ($qry) {
                                                echo '<select id="product_id" name="product_id" class="form-control"><option></option>';
                                                foreach ($qry as $qery) {
                                                    if ($qery->id == $product_id) {
                                                        $select = "selected";
                                                    } else {
                                                        $select = "";
                                                    }
                                                    echo '<option ' . $select . ' value=' . $qery->id . '>' . $qery->name . '</option>';
                                                }
                                                echo '</select>';
                                            }
                                            ?>
                                            <label for="product_id" class="control-label">Product *</label>
                                        </div>
                                    </div>
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="qty" maxlength="30"
                                                   name="qty"
                                                   value='<?php echo $qty; ?>'/>
                                            <label for="qty" class="control-label">Quantity *</label><br/>
                                        </div>
                                    </div>
                                    <div class="clearfix"></div>
                                    <?php if ($_SESSION['sess_role'] == 'VE' || $_SESSION['sess_role'] == 'VEC') { ?>
                                        <button id="btnsubmit" type="submit" class="btn waves-effect waves-light">
                                            Submit
                                        </button>
                                    <?php } ?>
                                    <button type="button" class="btn waves-effect waves-light"
                                            onclick="location.href='stock_setup.php?view'">
                                        Cancel
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                <?php } ?>
                </div>
                <?php
            }
            ?>


        </div>
    </div>
</div>
</div>
<?php include('includes/inc_footer.php'); ?>

<?php include('includes/inc_js.php'); ?>
<script type="application/javascript">
    $(document).ready(function () {
        var fewSeconds = 2;
        $('#btnsubmit').click(function () {
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });
    });
</script>
</body>
</html>
