<?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();
}
$datefrom = "";
$dateto = "";
$datetime = date('d-m-Y');
if (isset($_GET['view'])) {
    extract($_REQUEST);
    if ($datefrom == "") {
        $datefrom = date('Y-m-d', strtotime("-30 days"));
    } else {
        $datefrom = date("Y-m-d", strtotime($datefrom));
    }
    if ($dateto == "") {
        $dateto = date('Y-m-d');
    } else {
        $dateto = date("Y-m-d", strtotime($dateto));
    }
    $datefrom = date("d-m-Y", strtotime($datefrom));
    $dateto = date("d-m-Y", strtotime($dateto));

    $qryDate = date("Y-m-d", strtotime($datefrom));
    $qryTo = date("Y-m-d", strtotime($dateto));
    $filterStockView = " WHERE DATE_FORMAT(datetime,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(datetime,'%Y-%m-%d')<='$qryTo'";
}

?>
<!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>Ingredient Stock Setup</h3>
            </div>
            <script>
                $(function () {
                    $('.datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true, // Creates a dropdown to control month
                        selectYears: true,
                    });
                    $('.datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true, // Creates a dropdown to control month
                        selectYears: true,
                    });
                });
            </script>
            <?php if (isset($_GET['view'])) {
            $datefrom = date("d-m-Y", strtotime($datefrom));
            $dateto = date("d-m-Y", strtotime($dateto));

            ?>
                <form action="" method="get" name="search"
                      id="searchfrm">
                    <table class="table">
                        <tr>
                            <td class="col l4">Date From<br>
                                <input type="text" name="datefrom" id="datepicker"
                                       placeholder="Date From"
                                       value="<?= $datefrom ?>" class="datepicker form-control"/>
                                <input type="hidden" name="view" id="view" class="form-control"/>
                            </td>
                            <td class="col l4"> Date To<br>
                                <input type="text" name="dateto" id="datepicker1"
                                       placeholder="Date To"
                                       value="<?= $dateto ?>" class="datepicker form-control"/>
                            </td>
                            <td class="col l4">&nbsp;<br>
                                <button type="submit" class="btn waves-effect waves-light"
                                        style="float:left;">
                                    Search
                                </button>
                            </td>
                        </tr>
                    </table>
                </form>
            <?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['add'])) {
            if (isset($_POST) && !empty($_POST)) {
                extract($_REQUEST);
                $data['ingredient_id'] = $ingredient_id;
                $data['qty'] = $qty;
                $data['user_id'] = $_SESSION['sess_userid'];
                $data['datetime'] = date('Y-m-d H:i:s', strtotime($datetime));
                //$data['datetime'] = 'NOW()';

                $ing = IngSetup::GetIngSetupById($ingredient_id);
                if (!empty($ing)) {
                    $availableStock = $ing->availability;
                    $totalStock = $availableStock + $qty;
                    $dataIng['availability'] = $totalStock;
                    IngSetup::UpdateIngSetup($ingredient_id, $dataIng);
                }

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

                if ((strlen($ingredient_id) == 0))
                    array_push($errors, "Please select ingredient");
                if ((strlen($qty) == 0))
                    array_push($errors, "Please enter quantity");

            if (count($errors) == 0) {
                $q = ProductionStock::AddProductionStockSetup($data);
            if ($q) {
                $output = '';
                //header("Location: ?view&sucess"); ?>
                <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>";
                }
            }
            }
            ?>
                <div class="row">
                    <form action="" method="post" id="stock_setup_form" novalidate="novalidate">
                        <div class="col s12 form-group">
                            <?php echo $output; ?>
                            <div class="col s8">
                                <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'";
                                        $qry = IngSetup::GetIngSetupList($filter, $pageno = "null", $pagesize = "null");
                                        if ($qry) {
                                            echo '<select id="ingredient_id" name="ingredient_id" class="form-control"><option></option>';
                                            foreach ($qry as $qery) {
                                                echo '<option value=' . $qery->id . '>' . $qery->name . '</option>';
                                            }
                                            echo '</select>';
                                        }
                                        ?>
                                        <label for="ingredient_id" class="control-label">Ingredient *</label>
                                    </div>
                                </div>
                                <div class="row margin">
                                    <div class="input-field col s12">
                                        <input type="text" name="datetime" id="datepicker"
                                               value="<?= $datetime ?>" class="datepicker form-control"/>
                                        <label for="datepicker" class="control-label">Date *</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; ?>'/><br>
                                        <label for="qty" class="control-label">Quantity *</label>
                                    </div>
                                </div>
                                <div class="row margin">
                                    <div class="input-field col s12">
                                        <button id="btnsubmit" type="submit" class="btn waves-effect waves-light">Submit</button>
                                        <button type="button" class="btn waves-effect waves-light"
                                                onclick="location.href='ing_stock_setup.php?view'">Cancel
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>

                <?php
            } // add close

            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>Action</th>
                            <th>Date</th>
                            <th>Ingredient</th>
                            <th>Quantity</th>
                            <th>User</th>
                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th>Action</th>
                            <th>Date</th>
                            <th>Ingredient</th>
                            <th>Quantity</th>
                            <th>User</th>
                        </tr>
                        </tfoot>
                        <tbody>
                        <?php
                        $qry = ProductionStock::GetProductionStockSetupList($filterStockView);
                        if ($qry) {
                            foreach ($qry as $qery) {
                                $ing = IngSetup::GetIngSetupById($qery->ingredient_id);
                                $user = User_setup::GetUserSetupId($qery->user_id);
                                ?>
                                <tr>
                                    <td>
                                        <?php
                                        if ($_SESSION['sess_role'] == 'VEC' || $_SESSION['sess_role'] == 'VE') {
                                            ?>
                                            <a href='?edit&id=<?php echo $qery->id; ?>&v' title="View">
                                    <span style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                          class="mini-stat-icon pink"><i class="mdi-action-description"></i></span>
                                            </a>
                                            <a href="?edit&id=<?php echo $qery->id; ?>" title="Edit">
                                    <span style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                          class="mini-stat-icon orange"><i class="mdi-image-edit"></i></span>
                                            </a>
                                        <?php } else { ?>
                                            <a href="?edit&id=<?php echo $qery->id; ?>&v" title="View">
                                    <span style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                          class="mini-stat-icon pink"><i class="mdi-action-description"></i></span>
                                            </a>
                                        <?php } ?>
                                    </td>
                                    <td><?php echo date('Y-m-d', strtotime($qery->datetime)); ?></td>
                                    <td><?php echo $ing->name; ?></td>
                                    <td><?php echo $qery->qty; ?></td>
                                    <td><?php echo $user->username; ?></td>
                                </tr>
                                <?php
                            }
                        } ?>
                        </tbody>
                    </table>
                </div>
                <?php

            } // close view


            if (isset($_GET['edit']) && !empty($_POST)) {
                extract($_REQUEST);
                $id = $_GET['id'];
                $data['ingredient_id'] = $ingredient_id;
                $data['qty'] = $qty;
                $data['user_id'] = $_SESSION['sess_userid'];
                $data['datetime'] = date('Y-m-d H:i:s', strtotime($datetime));

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

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

                if (count($errors) == 0) {
                    $ing = IngSetup::GetIngSetupById($ingredient_id);
                    if (!empty($ing)) {
                        $availableStock = $ing->availability;

                        $ingInStock = ProductionStock::GetProductionStockSetupById($id);
                        if ($ingInStock->qty > $qty) {
                            $qtyDiff = $ingInStock->qty - $qty;
                            $totalStock = $availableStock - $qtyDiff;
                        } else if ($ingInStock->qty < $qty) {
                            $qtyDiff = $qty - $ingInStock->qty;
                            $totalStock = $availableStock + $qtyDiff;
                        } else {
                            $totalStock = $availableStock;
                        }
                        $dataIng['availability'] = $totalStock;
                        IngSetup::UpdateIngSetup($ingredient_id, $dataIng);
                    }

                    $q = ProductionStock::UpdateProductionStockSetup($id, $data);


                    if ($q) {
                        $output = '';
                        //header("Location: ?view&sucess"); ?>
                        <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 = ProductionStock::GetProductionStockSetupById($id);
                    $qty = $qry->qty;
                    $datetime = date('d-m-Y', strtotime($qry->datetime));
                    $ingredient_id = $qry->ingredient_id;
                    $ing = IngSetup::GetIngSetupById($ingredient_id);
                    $ingname = $ing->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">Ingredient Name:</div>
                                <span class="col s6"><?php echo $ingname; ?></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'";
                                            $qry = IngSetup::GetIngSetupList($filter, $pageno = "null", $pagesize = "null");
                                            if ($qry) {
                                                echo '<select id="ingredient_id" name="ingredient_id" class="form-control"><option></option>';
                                                foreach ($qry as $qery) {
                                                    echo $ingredient_id;
                                                    if ($qery->id == $ingredient_id) {
                                                        $select = "selected";
                                                    } else {
                                                        $select = "";
                                                    }
                                                    echo '<option ' . $select . ' value=' . $qery->id . '>' . $qery->name . '</option>';
                                                }
                                                echo '</select>';
                                            }
                                            ?>
                                            <label for="ingredient_id" class="control-label">Ingredient *</label>
                                        </div>
                                    </div>
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input type="text" name="datetime" id="datepicker"
                                                   value="<?= $datetime ?>" class="datepicker form-control"/>
                                            <label for="datepicker" class="control-label">Date *</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='ing_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 () {
            // Ajax request
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });
    });
</script>
</body>
</html>