<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
$name = "";
$description = "";
$product_id = "";
$status = "";
$batch_date = "";
if ($batch_date == "") {
    $batch_date = date('d-m-Y');
} else {
    $batch_date = date("d-m-Y", strtotime($batch_date));
}

if (isset($_POST) && !empty($_POST['production']) && $_POST['production'] == 1) {
    extract($_REQUEST);
    $batch = BatchSetup::GetBatchSetupById($batch_id);

    $data['batch_id'] = $batch_id;
    $data['batch_qty'] = $batch_qty;
    $data['batch_date'] = date('Y-m-d', strtotime($batch_date));
    $data['datetime'] = 'NOW()';
    $data['batch_name'] = $batch->name;
    $data['product_id'] = $batch->product_id;
    $data['status'] = "active";

    $filterBatch = " WHERE batch_id = '$batch_id'";
    $batchItems = BatchSetup::GetBatchItems($filterBatch);

    $notFound = array();
    foreach ($batchItems as $items) {
        $ing = IngSetup::GetIngSetupById($items->ing_id);
        $required = $batch_qty * $items->per_unit;

        // Apply FIFO logic to deduct stock
        $deductedQty = ProductionStock::DeductStockFIFO($items->ing_id, $required);

        // If not enough stock was deducted, add to not found list
        if ($deductedQty < $required) {
            $notFound[] = $ing->name;
        }
    }

    if (isset($notFound[0])) {
        echo "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>Stock Not available! " . implode(', ', $notFound) . "</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
    } else {
        // Add Production Setup
        $q = ProductionSetup::AddProductionSetup($data);
        if ($q) {
            // Add Production Items
            foreach ($batchItems as $items) {
                $ing = IngSetup::GetIngSetupById($items->ing_id);
                $dataIng['production_id'] = $q;
                $dataIng['ing_id'] = $items->ing_id;
                $dataIng['per_unit'] = $items->per_unit;
                $dataIng['price'] = $ing->avg_rate;
                ProductionSetup::AddProductionItem($dataIng);
            }
            ?>
            <script>window.location.href = '?view&sucess'</script>
            <?php
        } else {
            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>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
    <style>
        .modal .modal-footer {
            height: auto !important;
            width: auto !important;
        }

        .modal {
            height: 80% !important;
            max-height: 80% !important;
        }
    </style>
</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>Batch Setup</h3>
            </div>
            <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" style="font-size:12px;"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>
            <?php
            if (isset($_GET['add'])) {
            if (isset($_POST) && !empty($_POST)) {
                extract($_REQUEST);
                $data['name'] = $name;
                $data['description'] = $description;
                $data['product_id'] = $product_id;
                $data['datetime'] = 'NOW()';
                $data['status'] = $status;
                $batchcheck = BatchSetup::CheckBatchAccount($name, 0);

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

                if ((strlen($name) == 0) || (strlen($name) > 255))
                    array_push($errors, "Please enter batch name");
                if ((strlen($product_id) == 0))
                    array_push($errors, "Please select product");
                if ($batchcheck)
                    array_push($errors, "Batch already exist");
            if (count($errors) == 0) {

                $q = BatchSetup::AddBatch($data);
            	if ($q) {
                  foreach ($item AS $prKey => $prRow) {
                      $dataProduct['batch_id'] = $q;
                      $dataProduct['ing_id'] = $prRow;
                      $dataProduct['qty'] = $per_unit[$prKey];
                      $qp = BatchSetup::AddBatchItem($dataProduct);
                  }
                  foreach ($packing_item as $prKey => $prRow) {
                      $dataPacking['batch_id'] = $q;
                      $dataPacking['ing_id'] = $prRow;
                      $dataPacking['qty'] = $packing_per_unit[$prKey];  // Assuming you have a similar array for packing items
                      $qp = BatchSetup::AddBatchItem($dataPacking);
                  }
                $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="batch_setup_form" novalidate="novalidate">
                        <div class="col s12">
                            <?php echo $output; ?>
                            <div class="row">
                                <span>(*) Mark Fields are mandatory</span><br/><br/>
                            </div>
                            <div class="row margin">
                                <div class="input-field col s6">
                                    <input type="text" name="name" id="name" maxlength="250" class="form-control"
                                           value='<?php echo $name; ?>'>
                                    <label for="name" class="center-align">Batch Name *</label>
                                </div>
                                <div class="input-field col s6">
                                    <?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) {
                                            echo '<option 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 s6">
                                    <input class="form-control" type="text" id="description"
                                           maxlength="30"
                                           name="description"
                                           value='<?php echo $description; ?>'/>
                                    <label for="description" class="center-align">Description</label>
                                </div>
                                <div id="status" class="input-field col s6">
                                    <select class="form-control" name="status">
                                        <option value="active" <?php if ($status == 'active') {
                                            echo "selected='selected'";
                                        } ?>>Active
                                        </option>
                                        <option value="inactive" <?php if ($status == 'inactive') {
                                            echo "selected='selected'";
                                        } ?>>Inactive
                                        </option>
                                    </select>
                                    <label for="status" class="center-align">Status</label>
                                </div>
                                <br/>
                            </div>
                        </div>
                      	
                        <div class="clearfix"></div>
                     <div class="row margin">
                         <h1>Add Ingredient</h1>
                        </div>
                        <div class="col s12">
                          <table style="margin-top: 20px;"
                                 class="bordered responsive-table table dataTable">
                            <thead>
                              <th>S No</th>
                              <th>Action</th>
                              <th>Item Name</th>
                              <th>Qty</th>
                            </thead>
                            <tbody id="addNewIngredient">
                            </tbody>
                          </table>
                        </div>
                        <br>

                        <div class="clearfix"></div>
                        <div class="col s12">
                          <div class="input-field col m3 col s12">
                            <?php
                $filter = " where status = 'active' ORDER BY name";
                $qry = IngSetup::GetIngSetupListIngredient($filter, $pageno = "null", $pagesize = "null");
                if ($qry) {
                  echo '<select id="ingItemIngredient" style="width: 100%!important;" class="form-control"><option></option>';
                  foreach ($qry as $qery) {
                    echo '<option value=' . $qery->id . '>' . $qery->name . '</option>';
                  }
                  echo '</select>';
                  echo '<label for="ingItemIngredient">Ingredients</label>';
                }
                            ?>
                          </div>
                        </div>
                        <div class="clearfix"></div>
                        <br>

                        <div class="col s12">
                          <div class="clearfix"></div>
                          <div class="col m12 col s12">
                            <div class="btn-group">
                              <button id="newIngredient" type="button" class="btn waves-effect waves-light">
                                Add Ingredient SA <i class="fa fa-plus"></i>
                              </button>
                            </div>
                          </div>
                        </div>

                        <div class="clearfix"></div>
                        <div class="row margin">
                          <h1>Packing</h1>
                        </div>
                        <div class="col s12">
                          <table style="margin-top: 20px;"
                                 class="bordered responsive-table table dataTable">
                            <thead>
                              <th>S NO</th>
                              <th>Action</th>
                              <th>Item Name</th>
                              <th>Qty</th>
                            </thead>
                            <tbody id="addNewPacking">
                            </tbody>
                          </table>
                        </div>
                        <br>
                        <div class="clearfix"></div>
                        <div class="col s12">
                          <div class="input-field col m3 col s12">
                            <?php
                $qry = IngSetup::GetIngSetupListPacking($filter, $pageno = "null", $pagesize = "null");
                if ($qry) {
                  echo '<select id="ingItemPacking" style="width: 100%!important;" class="form-control"><option></option>';
                  foreach ($qry as $qery) {
                    echo '<option value=' . $qery->id . '>' . $qery->name . '</option>';
                  }
                  echo '</select>';
                  echo '<label for="ingItemPacking">Packing</label>';
                }
                            ?>
                          </div>
                        </div>
                        <div class="col s12">
                          <div class="clearfix"></div>
                          <div class="col m12 col s12">
                            <div class="btn-group">
                              <button id="newPacking" type="button" class="btn waves-effect waves-light">
                                Add Packing <i class="fa fa-plus"></i>
                              </button>
                            </div>
                          </div>
                        </div>

                       <div class="clearfix"></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='batch_setup.php?view'">Cancel
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
                <?php
            } // add close

            if (isset($_GET['view'])) {

                ?>
                 <?php if (!empty($successMsg)) { ?>
                <div id='card-alert' class='card green lighten-5'>
                    <div class='card-content green-text'>
                        <p>SUCCESS : <strong><?php echo $successMsg ?></strong></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>Batch Name</th>
                          <th>Description</th>
                            <th>Product Name</th>
                            <th>Status</th>
                            <th>Date</th>
                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th>Action</th>
                            <th>Batch Name</th>
                          <th>Description</th>
                            <th>Product Name</th>
                            <th>Status</th>
                            <th>Date</th>
                        </tr>
                        </tfoot>
                        <tbody>
                        <?php
                        $qry = BatchSetup::GetBatchSetupList();
                        if ($qry) {
                            foreach ($qry as $qery) {
                                $product = ProductSetup::GetProductSetupById($qery->product_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 } ?>
                                        <a style="color: #fff; padding: 5px; border-radius: 5px; font-size: 12px;"
                                         class="waves-effect waves-light btn-sm light-blue"
                                         href="check_batch_qty.php?batch_id=<?php echo $qery->id; ?>">Create</a>

                                        <script>
                                            $(function () {
                                                $('#datepicker<?php echo $qery->id; ?>').pickadate({
                                                    format: 'dd-mm-yyyy',
                                                    selectMonths: true,
                                                });
                                            });
                                        </script>
                                        <form action="" method="post" id="">
                                            <div id="modal<?php echo $qery->id; ?>" class="modal">
                                                <div class="modal-content">
                                                    <h3><?= ucwords($qery->name) ?></h3>
                                                    <div class="row margin">
                                                        <div class="input-field col s12">
                                                            <input type="text" name="batch_qty" required="required"
                                                                   id="batch_qty" class="form-control"/>
                                                            <label for="batch_qty" class="center-align">Batch Quantity
                                                                *</label>
                                                        </div>
                                                    </div>
                                                    <div class="row margin">
                                                        <div class="input-field col s12">
                                                            <input type="text" name="batch_date"
                                                                   id="datepicker<?php echo $qery->id; ?>"
                                                                   value="<?= $batch_date ?>" class="form-control"/>
                                                            <label for="datepicker" class="center-align">Batch Date
                                                                *</label>
                                                        </div>
                                                    </div>
                                                    <input type="hidden" name="batch_id" id="batch_id"
                                                           value='<?php echo $qery->id; ?>'>
                                                    <input type="hidden" name="production" value='1'>
                                                </div>
                                                <div class="modal-footer">
                                                    <button id="btnsubmitQtyCheck" type="submit"
                                                            class="waves-effect waves-red btn-flat">
                                                        Submit
                                                    </button>
                                                    <a href="#"
                                                       class="waves-effect waves-green btn-flat modal-action modal-close">Close</a>
                                                </div>
                                            </div>
                                        </form>
                                    </td>
                                    <td><?php echo ucwords($qery->name); ?></td>
                                  <td><?php echo ucwords($qery->description); ?></td>
                                    <td><?php echo ucwords($product->name); ?></td>
                                  

                                    <td><?= ($qery->status == 'active') ? ucwords($qery->status) : "Inactive"; ?></td>
                                    <td><?php echo date('d-m-Y h:i:s A', strtotime($qery->datetime)); ?></td>

                                </tr>
                                <?php
                            }
                        } ?>
                        </tbody>
                    </table>
                </div>
                <?php

            } // close view

            // START OF MODIFIED EDIT SECTION
           if (isset($_GET['edit']) && !empty($_POST)) {
    extract($_REQUEST);
    $id = $_GET['id'];
    $data['name'] = $name;
    $data['description'] = $description;
    $data['product_id'] = $product_id;
    $data['status'] = $status;
    $data['datetime'] = 'NOW()';

    $batchcheck = BatchSetup::CheckBatchAccount($name, $id);

    $errors = array();
    // Validate the input
    if ((strlen($name) == 0) || (strlen($name) > 255))
        array_push($errors, "Please enter batch name");
    if ((strlen($product_id) == 0))
        array_push($errors, "Please select product");
    if ($batchcheck)
        array_push($errors, "Batch already exist");

    if (count($errors) == 0) {
        $q = BatchSetup::UpdateBatchSetup($id, $data);

        // Update Ingredients
         foreach ($item as $prKey => $prRow) {
            $dataProduct['batch_id'] = $id;
            $dataProduct['ing_id'] = $prRow;
            $dataProduct['qty'] = $per_unit[$prKey];

            // Fetch existing batch item
            $existingBatchItem = BatchSetup::GetBatchItems("WHERE batch_id='$id' AND ing_id='$prRow'");
            if ($existingBatchItem && count($existingBatchItem) > 0) {
                // If the batch item exists, update it with the new quantity
                $dataToUpdate = ['qty' => $per_unit[$prKey]];  // Add other fields to update as needed
                BatchSetup::UpdateBatchItem($existingBatchItem[0]->id, $dataToUpdate);
            } else {
                // If the batch item doesn't exist, add it as a new item
                BatchSetup::AddBatchItem($dataProduct);
            }
        }

        // Update Packing Items
       foreach ($packing_item as $prKey => $prRow) {
          $dataPacking['batch_id'] = $id;
          $dataPacking['ing_id'] = $prRow;
          $dataPacking['qty'] = $packing_per_unit[$prKey];

          // Fetch existing packing item
          $existingPackingItem = BatchSetup::GetBatchItems("WHERE batch_id='$id' AND ing_id='$prRow'");
          if ($existingPackingItem && count($existingPackingItem) > 0) {
              // If the packing item exists, update the stock
              $dataToUpdate = ['qty' => $packing_per_unit[$prKey]];  // Update quantity or other fields as needed
              BatchSetup::UpdateBatchItem($existingPackingItem[0]->id, $dataToUpdate);
          } else {
              // If the packing item doesn't exist, add it as a new item
              BatchSetup::AddBatchItem($dataPacking);
          }
      }

        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 = BatchSetup::GetBatchSetupById($id);
                    $name = $qry->name;
                    $description = $qry->description;
                    $product_id = $qry->product_id;
                    $product = ProductSetup::GetProductSetupById($product_id);
                    $status = $qry->status;
                }

                if ($_REQUEST['id'] && isset($_REQUEST['v'])) {
                  
                   $qry = BatchSetup::GetBatchSetupById($id);
                    $name = $qry->name;
                    $description = $qry->description;
                    $product_id = $qry->product_id;
                    $product = ProductSetup::GetProductSetupById($product_id);
                    $status = $qry->status;
                    ?>
                    <div class="row">
                        <!--  The form that will be parsed by jQuery before submit  -->
                        <div class="col s12">
                            <div class="row">
                                <div class="col s6">Batch Name:</div>
                                <span class="col s6"><?php echo $name; ?></span>
                            </div>
                            <div class="row">
                                <div class="col s6">Product:</div>
                                <span class="col s6"><?php echo $product->name; ?></span>
                            </div>
                            <div class="row">
                                <div class="col s6">Description:</div>
                                <span class="col s6"><?php echo $description; ?></span>
                            </div>
                            <div class="row">
                                <div class="col s6">Status</div>
                                    <span class="col s6">
                                        <?php
                                        if ($status == 'active') {
                                            echo "Active";
                                        } else if ($status == 'inactive') {
                                            echo "Inactive";
                                        } ?>
                                    </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="batch_setup_form" name="batch_setup_form" novalidate="novalidate">
                            <div class="col s12">
                                <div class="row">
                                    <?php echo $output; ?>
                                </div>
                                <div class="row margin">
                                    <span>(*) Mark Fields are mandatory</span><br/><br/>
                                </div>
                                <div class="row margin">
                                    <div class="input-field col s6">
                                        <input class="form-control" type="text" id="name" maxlength="250" name="name" value="<?php echo $name; ?>"/><br/>
                                        <label for="name" class="control-label">Batch Name *</label>
                                    </div>
                                    <div class="input-field col s6">
                                        <?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) {
                                                echo $product_id;
                                                $select = $qery->id == $product_id ? "selected" : "";
                                                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 s6">
                                        <input class="form-control" type="text" id="description" maxlength="30" name="description" value="<?php echo $description; ?>"/><br/>
                                        <label for="description" class="control-label">Description</label>
                                    </div>
                                    <div id="status" class="input-field col s6">
                                        <select class="form-control" name="status">
                                            <option value="active" <?php if ($status == 'active') { echo "selected='selected'"; } ?>>Active</option>
                                            <option value="inactive" <?php if ($status == 'inactive') { echo "selected='selected'"; } ?>>Inactive</option>
                                        </select>
                                        <label for="status" class="control-label">Status</label>
                                    </div>
                                    <br/>
                                </div>
                                <div class="clearfix"></div>

                                <div class="col s12">
                                    <table style="margin-top: 60px;" class="bordered responsive-table table dataTable">
                                        <thead>
                                            <th>Action</th>
                                            <th>Item Name</th>
                                            <th>Qty</th>
                                        </thead>
                                        <tbody id="addNewItem">
                                           <?php
                                              if (isset($_GET['edit'])) {
                                                  $filteritems = " WHERE batch_id = '$id'";
                                                  $batchItems = BatchSetup::GetBatchItems($filteritems);
                                                  if (isset($batchItems[0])) {
                                                      foreach ($batchItems as $batchItem) {
                                                          $ingredient = IngSetup::GetIngSetupById($batchItem->ing_id);
                                                          if ($ingredient) {
                                                              echo "<tr id='tr" . $ingredient->id . "'>";
                                                              echo '<td>';
                                                              echo '<button type="button" class="btn btn-danger deleteItem" data-batch-id="' . $id . '" data-ing-id="' . $ingredient->id . '">Delete</button>';
                                                              echo '</td>';
                                                              echo '<td>';
                                                              echo '<input class="form-control" type="text" readonly value="' . $ingredient->name . '">';
                                                              echo '<input type="hidden" name="item[]" value="' . $ingredient->id . '">';
                                                              echo '</td>';
                                                              echo '<td>';
                                                              echo '<input class="form-control" required maxlength="15" value="' . $batchItem->qty . '" type="text" name="per_unit[]" />';
                                                              echo '</td>';
                                                              echo "</tr>";
                                                          }
                                                      }
                                                  }
                                              }
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                                <br>
                                <div class="clearfix"></div>
                                <br>
                                <div class="row">
                                    <div class="input-field col m3 col s12">
                                        <?php
                                        $filter = " where status = 'active' ORDER BY name";
                                        $qry = IngSetup::GetIngSetupList($filter, $pageno = "null", $pagesize = "null");
                                        if ($qry) {
                                            echo '<select id="ingItem" style="width: 100%!important;" class="form-control"><option></option>';
                                            foreach ($qry as $qery) {
                                                echo '<option value=' . $qery->id . '>' . $qery->name . '</option>';
                                            }
                                            echo '</select>';
                                            echo '<label for="ingItem">Items</label>';
                                        }
                                        ?>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="clearfix"></div>
                                    <div class="col m12 col s12">
                                        <div class="btn-group">
                                            <button id="newItem" type="button" class="btn waves-effect waves-light">Add New <i class="fa fa-plus"></i></button>
                                        </div>
                                    </div>
                                </div>
                                <div class="row margin">
                                    <div class="input-field col s12">
                                        <?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='batch_setup.php?view'">Cancel</button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                <?php } ?>
            </div>
            <?php
            } // end of if GET edit
            // END OF MODIFIED EDIT SECTION
        ?>
    </div>
</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>
<script>
    $(document).ready(function () {
        $(".dropdown-content.select-dropdown li").on("click", function () {
            var that = this;
            setTimeout(function () {
                if ($(that).parent().hasClass('active')) {
                    $(that).parent().removeClass('active');
                    $(that).parent().hide();
                }
            }, 100);
        });
      
    });
  $('#btnsubmitQtyCheckasdasdas').on('click', function(e) {
        e.preventDefault(); // Prevent the form from submitting immediately

        var batch_id = $('#batch_id').val();
        var batch_qty = $('#batch_qty').val();

        // Proceed to check the quantities in the batch_items table
        checkQuantitiesAndRedirect(batch_id, batch_qty);
    });
  
 
}
function checkQuantitiesAndRedirect(batch_id, batch_qty) {
    $.ajax({
        url: 'check_quantities.php', // This is the server-side script that will perform the check
        type: 'POST',
        data: {
            batch_id: batch_id,
            batch_qty: batch_qty
        },
        success: function(response) {
            if(response.success) {
                // Quantities are sufficient, redirect to a new page with the batch_id
                window.location.href = 'new_page.php?batch_id=' + batch_id;
            } else {
                // Quantities are not sufficient, show an error message
                alert('Not enough stock for this batch.');
            }
        },
        error: function() {
            alert('An error occurred while checking quantities.');
        }
    });
}
</script>


<script>
  $(document).ready(function() {
     
     // Handle adding new ingredients
       $('#newIngredient').on('click', function () {
         	
            $('#newIngredient').attr('disabled', true);
            var product = $('#ingItemIngredient').val();

            if (product && !$('#tr' + product).length) {
                $('body #container').block({message: 'Loading...'});
                $.get('addIngredientItem.php?id=' + product, function (data) {
                    // Append the row returned from the PHP script
                    $("#addNewIngredient").append(data);
                    updateSN(); // Update the serial numbers for the rows
                    $('body #container').unblock();
                }).fail(function() {
                    alert("Error loading data.");
                });
            } else {
                alert("This item is already added or not selected.");
            }
            $('#newIngredient').attr('disabled', false);
        });

        // Function to update the serial numbers for rows
        function updateSN() {
            $('#addNewIngredient tr').each(function(index) {
                $(this).find('.sn').text(index + 1);
            });
        }

        // Remove row on clicking delete button
        $(document).on('click', '.mdi-action-delete', function () {
            $(this).closest('tr').remove();
            updateSN();
        });
     // Handle adding new packing items
     $('#newPacking').on('click', function () {
          $('#newPacking').attr('disabled', true);
          var product = $('#ingItemPacking').val();

          if (product && !$('#trPacking' + product).length) {
              $('body #container').block({message: 'Loading...'});
              $.get('addPackingItem.php?id=' + product, function (data) {
                  // Append the row returned from the PHP script
                  $("#addNewPacking").append(data);
                  updatePackingSN(); // Update the serial numbers for the rows
                  $('body #container').unblock();
              }).fail(function() {
                  alert("Error loading data.");
              });
          } else {
              alert("This item is already added or not selected.");
          }
          $('#newPacking').attr('disabled', false);
      });
        function updatePackingSN() {
            $('#addNewPacking tr').each(function(index) {
                $(this).find('.sn').text(index + 1);
            });
        }
        $(document).on('click', '.mdi-action-delete', function () {
            $(this).closest('tr').remove();
            updatePackingSN();
        });
  });
</script>
<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>
<script type="text/javascript">
    /*Show entries on click hide*/
    $(document).ready(function () {
        $(".dropdown-content.select-dropdown li").on("click", function () {
            var that = this;
            setTimeout(function () {
                if ($(that).parent().hasClass('active')) {
                    $(that).parent().removeClass('active');
                    $(that).parent().hide();
                }
            }, 100);
        });
        $('#newItem').on('click', function () {
            $('#newItem').attr('disabled', true);
            var product = $('#ingItem').val();
            var fewSeconds = 2;
            if (!$('#tr' + product).html() && product != '') {
                $('body #container').block({message: 'Loading...'});
                $.get('addPurItem.php?id=' + $('#ingItem').val(), function (data) {
                    $("#addNewItem").append(data);
                    numbering();
                    $('body #container').unblock();
                })
                setTimeout(function () {
                    $('body #container').unblock();
                }, fewSeconds * 500);
            }
            $('#newItem').attr('disabled', false);
        });
    });
</script>
<script>
 $(document).on('click', '.deleteItem', function() {
    var batchId = $(this).data('batch-id');
    var ingId = $(this).data('ing-id');
    var row = $(this).closest('tr');

    $.ajax({
        url: 'delete_batch_item.php',
        type: 'POST',
        data: {
            batch_id: batchId,
            ing_id: ingId
        },
        success: function(response) {
            if (response == 'success') {
                row.remove(); // Remove the row from the table
            } else {
                alert('Error deleting item.');
            }
        },
        error: function() {
            alert('AJAX error occurred.');
        }
    });
});
 
 </script>
<script type="text/javascript">
    $(document).ready(function () {
        // Destroy the existing DataTable if already initialized
        if ($.fn.DataTable.isDataTable('#data-table-simple')) {
            $('#data-table-simple').DataTable().destroy();
        }

        // Initialize the DataTable with ascending sorting on the "Batch Name" column (index 1)
        $('#data-table-simple').DataTable({
            "order": [[1, "asc"]] // Column index 1 (Batch Name) sorted in ascending order
        });
    });
</script>


</body>
</html>
