<?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);

              
              // --- usage_percent: read & sanitize ---
$usage_percent = isset($_POST['usage_percent']) ? trim($_POST['usage_percent']) : '';
if ($usage_percent === '') {
    $usage_percent_val = null; // optional
} else {
    $usage_percent_val = (float)$usage_percent;
    if ($usage_percent_val < 0) { $usage_percent_val = 0; }
    if ($usage_percent_val >= 100) { $usage_percent_val = 99.999999; } // prevent 100
}

// save into $data for INSERT
$data['usage_percent'] = $usage_percent_val;

                $errors = array();
                // Validate the input
				// NEW: force deductible selection on Add
            if (empty($_POST['deductible_ing_id'])) {
                $errors[] = "Please select a deductible ingredient.";
            }
                 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) {

                  // NEW (deductible): read the selected deductible ingredient from radio group
                  $ded_ing_id = isset($_POST['deductible_ing_id']) ? (int)$_POST['deductible_ing_id'] : 0; // NEW (deductible)

                  foreach ($item AS $prKey => $prRow) {
                      $dataProduct['batch_id'] = $q;
                      $dataProduct['ing_id'] = $prRow;
                      $dataProduct['qty'] = $per_unit[$prKey];

                      // NEW (deductible): store is_deductible=1 only for the chosen ingredient row
                      if ((int)$prRow === $ded_ing_id) {           // NEW (deductible)
                          $dataProduct['is_deductible'] = 1;        // NEW (deductible)
                      } else {                                      // NEW (deductible)
                          $dataProduct['is_deductible'] = 0;        // NEW (deductible)
                      }                                             // NEW (deductible)

                      $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

                      // NEW (deductible): packing is never deductible
                      $dataPacking['is_deductible'] = 0;                 // NEW (deductible)

                      $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";
                                    // ADD PAGE — product <select> (same idea in EDIT)
                                      $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.'" '.
                                               'data-ppc="'.(float)$qery->carton_pieces.'" ' .     // exact column
                                               'data-w="'.(float)$qery->weight.'" ' .              // weight is in grams
                                               'data-unit="'.htmlspecialchars($qery->unit, ENT_QUOTES).'">'.
                                               htmlspecialchars($qery->name, ENT_QUOTES).
                                               '</option>';
                                        }
                                        echo '</select>';
                                      }


                                    ?>
                                    <label for="product_id" class="control-label">Product *</label>
                                </div>
                            </div>
                          
                          <div class="row margin">
    <div class="input-field col s3">
      <input type="number" id="usage_percent" name="usage_percent"
             min="0" max="99.9999999999" step="0.0000000001" value="">
      <label for="usage_percent">Usage %</label>
    </div>

    <div class="input-field col s3">
      <input type="text" id="prod_carton_pieces" readonly>
      <label for="prod_carton_pieces">Carton Pieces</label>
    </div>

    <div class="input-field col s3">
      <input type="text" id="prod_weight_kg" readonly>
      <label for="prod_weight_kg">Product Weight (kg)</label>
    </div>

    <div class="input-field col s3">
      <input type="text" id="prod_base_kg" readonly>
      <label for="prod_base_kg">Pieces × Weight (kg)</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>Deductible</th>  <!-- NEW (deductible): column shown on Add screen -->
                              <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'])) {
              // Read selected status or default to 'active'
$status_filter = isset($_GET['status_filter']) ? $_GET['status_filter'] : 'active';

// Build SQL filter
$filter = "";
if (!empty($status_filter) && $status_filter !== "All") {
    $filter = " WHERE status = '" . $status_filter . "' ";
}
// Sort: active first, then by name
$filter .= " ORDER BY CASE WHEN status='active' THEN 0 ELSE 1 END, name ASC";

                ?>
                 <?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 } ?>
          
  <form action="" method="get" id="searchfrm" style="margin-bottom:15px;">
  <table class="table">
    <tr>
      <td class="col l4">
        Status<br>
        <select class="form-control" id="status_filter" name="status_filter">
          <option value="All"      <?= ($status_filter === 'All')      ? 'selected' : '' ?>>All</option>
          <option value="active"   <?= ($status_filter === 'active')   ? 'selected' : '' ?>>Active</option>
          <option value="inactive" <?= ($status_filter === 'inactive') ? 'selected' : '' ?>>Inactive</option>
        </select>
        <input type="hidden" name="view" value="1">
      </td>
      <td class="col l4">&nbsp;<br>
        <button type="submit" class="btn waves-effect waves-light">Search</button>
      </td>
    </tr>
  </table>
</form>

<hr>

                <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
                       // Default filter


// status filter – default = active
$status_filter = $_GET['status_filter'] ?? 'active';

$filter = "";
if (!empty($status_filter) && $status_filter !== "All") {
    $filter = " WHERE status = '" . $status_filter . "' ";
}

// Always sort: active first, then by name
$filter .= " ORDER BY CASE WHEN status='active' THEN 0 ELSE 1 END, name ASC";

              
$qry = BatchSetup::GetBatchSetupList($filter);

                        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 } ?>
                                        <?php if ($qery->status == 'active') { ?>
                                            <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>
                                        <?php } else { ?>
                                            <span style="color: #999; font-size: 12px; padding: 5px;">Inactive</span>
                                        <?php } ?>

                                        <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()';
             // --- usage_percent: read & sanitize ---
$usage_percent = isset($_POST['usage_percent']) ? trim($_POST['usage_percent']) : '';
if ($usage_percent === '') {
    $usage_percent_val = null;
} else {
    $usage_percent_val = (float)$usage_percent;
    if ($usage_percent_val < 0) { $usage_percent_val = 0; }
    if ($usage_percent_val >= 100) { $usage_percent_val = 99.999999; }
}

// save into $data for UPDATE
$data['usage_percent'] = $usage_percent_val;


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

    $errors = array();
    // Validate the input
             // NEW: force deductible selection on Add
if (empty($_POST['deductible_ing_id'])) {
    $errors[] = "Please select a deductible ingredient.";
}
    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);

        // NEW (deductible): read selected radio in Edit mode
        $ded_ing_id = isset($_POST['deductible_ing_id']) ? (int)$_POST['deductible_ing_id'] : 0; // NEW (deductible)

        // NEW (deductible): clear all rows' is_deductible for this batch in one go (implement this helper)
        if (method_exists('BatchSetup','ClearDeductibleForBatch')) {      // NEW (deductible)
            BatchSetup::ClearDeductibleForBatch($id);                     // NEW (deductible)
        }                                                                 // NEW (deductible)

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

            // NEW (deductible): set flag as per chosen radio
            $dataProduct['is_deductible'] = ((int)$prRow === $ded_ing_id) ? 1 : 0; // NEW (deductible)

            // 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],
                    'is_deductible' => $dataProduct['is_deductible']   // NEW (deductible)
                ];  // 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];

          // NEW (deductible): packing is never deductible
          $dataPacking['is_deductible'] = 0; // NEW (deductible)

          // 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],
                  'is_deductible' => 0            // NEW (deductible)
              ];  // 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;
                  	$usage_percent = isset($qry->usage_percent) ? $qry->usage_percent : '';
                  	$carton_pieces = $product->carton_pieces;
                    $weight_kg = $product->weight / 1000; // convert grams → kg
                    $total_kg = $carton_pieces * $weight_kg;
                }

                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;
                  	$carton_pieces = $product->carton_pieces;
$weight_kg = $product->weight / 1000; // convert grams → kg
$total_kg = $carton_pieces * $weight_kg;
                    ?>
                    <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";
                                       // ADD PAGE — product <select> (same idea in EDIT)
                                          $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) {
    $select = ($qery->id == $product_id) ? "selected" : "";
    echo '<option '.$select.' value="'.$qery->id.'" '.
         'data-ppc="'.(float)$qery->carton_pieces.'" '.
         'data-w="'.(float)$qery->weight.'" '.
         'data-unit="'.htmlspecialchars($qery->unit, ENT_QUOTES).'">'.
         htmlspecialchars($qery->name, ENT_QUOTES).
         '</option>';
  }
  echo '</select>';
}

                                        ?>
                                        <label for="product_id" class="control-label">Product *</label>
                                    </div>
                                </div>
                                <div class="row margin">
                                  	  <div class="input-field col s3">
    <input class="form-control" type="number" id="usage_percent" name="usage_percent"
       min="0" max="99.9999999999" step="0.0000000001"
       value="<?php echo htmlspecialchars($usage_percent, ENT_QUOTES); ?>">
<label for="usage_percent" class="control-label">Usage %</label>
  </div>

                                  
                                  <div class="row margin">
  <div class="input-field col s3">
    <input class="form-control" type="text" readonly
           value="<?php echo htmlspecialchars($carton_pieces, ENT_QUOTES); ?>">
    <label>Carton Pieces</label>
  </div>

  <div class="input-field col s3">
    <input class="form-control" type="text" readonly
           value="<?php echo number_format($weight_kg, 3); ?>">
    <label>Product Weight (kg)</label>
  </div>

  <div class="input-field col s3">
    <input class="form-control" type="text" readonly
           value="<?php echo number_format($total_kg, 3); ?>">
    <label>Pieces × Weight (kg)</label>
  </div>
</div>
                                  
                                  
                                    <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>Deductible</th> <!-- NEW (deductible): column on Edit screen -->
                                            <th>Item Name</th>
                                            <th>Qty</th>
                                          	
                                        </thead>
                                        <tbody id="addNewIngredient">
                                           <?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>'; // NEW (deductible): radio cell
$checked = (!empty($batchItem->is_deductible) && (int)$batchItem->is_deductible === 1) ? ' checked' : '';
$rid = 'ded_ing_' . (int)$ingredient->id; // unique id per radio
echo '<input type="radio" id="'.$rid.'" name="deductible_ing_id" class="with-gap ded-radio" value="'.(int)$ingredient->id.'"'.$checked.'>';
echo '<label for="'.$rid.'" style="margin:0;">&nbsp;</label>';
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="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">Items</label>';
                                        }
                                        ?>
                                    </div>
                                </div>
                                <div class="row">
                                    <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 Newww <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>
/* global helpers – accessible to injected row scripts */
function updateSN() {
  $('#addNewIngredient tr').each(function(i){ $(this).find('.sn').text(i+1); });
}
function updatePackingSN() {
  $('#addNewPacking tr').each(function(i){ $(this).find('.sn').text(i+1); });
}
function ensureDeductibleRequired() {
  const anyChecked = $('#addNewIngredient input[name="deductible_ing_id"]:checked').length > 0;
  $('#addNewIngredient input[name="deductible_ing_id"]').prop('required', !anyChecked);
}

/* one ready block */
$(function () {
  // prevent double submit UX
  $('#btnsubmit').on('click', function () {
    var btn = $(this);
    btn.hide();
    setTimeout(function () { btn.show(); }, 2000);
  });

  // materialize dropdown fix
  $(".dropdown-content.select-dropdown li").on("click", function () {
    var that = this;
    setTimeout(function () {
      if ($(that).parent().hasClass('active')) {
        $(that).parent().removeClass('active').hide();
      }
    }, 100);
  });

  // quantity check button
  $('#btnsubmitQtyCheckasdasdas').on('click', function(e) {
    e.preventDefault();
    checkQuantitiesAndRedirect($('#batch_id').val(), $('#batch_qty').val());
  });

  // add ingredient (AJAX appends row with its own small script)
  $('#newIngredient').on('click', function () {
    var $btn = $(this);
    $btn.prop('disabled', true);
    var product = $('#ingItemIngredient').val();
    if (product && !$('#tr' + product).length) {
      $('body #container').block({message: 'Loading...'});
      $.get('addIngredientItem.php?id=' + product + '&edit=1', function (data) {
        $("#addNewIngredient").append(data);
        updateSN();
        ensureDeductibleRequired();
      })
      .fail(function(){ alert("Error loading data."); })
      .always(function(){
        $('body #container').unblock();
        $btn.prop('disabled', false);
      });
    } else {
      alert("This item is already added or not selected.");
      $btn.prop('disabled', false);
    }
  });

  // remove ingredient row (local delete only)
  $(document).on('click', '#addNewIngredient .mdi-action-delete', function () {
    $(this).closest('tr').remove();
    updateSN();
    ensureDeductibleRequired();
  });

  // add packing
  $('#newPacking').on('click', function () {
    var $btn = $(this);
    $btn.prop('disabled', true);
    var product = $('#ingItemPacking').val();
    if (product && !$('#trPacking' + product).length) {
      $('body #container').block({message: 'Loading...'});
      $.get('addPackingItem.php?id=' + product, function (data) {
        $("#addNewPacking").append(data);
        updatePackingSN();
      })
      .fail(function(){ alert("Error loading data."); })
      .always(function(){
        $('body #container').unblock();
        $btn.prop('disabled', false);
      });
    } else {
      alert("This item is already added or not selected.");
      $btn.prop('disabled', false);
    }
  });

  // remove packing row
  $(document).on('click', '#addNewPacking .mdi-action-delete', function () {
    $(this).closest('tr').remove();
    updatePackingSN();
  });

  // delete existing item via AJAX (edit table)
  $(document).on('click', '.deleteItem', function() {
    var batchId = $(this).data('batch-id');
    var ingId = $(this).data('ing-id');
    var row = $(this).closest('tr');
    $.post('delete_batch_item.php', { batch_id: batchId, ing_id: ingId })
     .done(function(resp){ (resp === 'success') ? row.remove() : alert('Error deleting item.'); })
     .fail(function(){ alert('AJAX error occurred.'); });
  });

  // datatable
  if ($.fn.DataTable.isDataTable('#data-table-simple')) {
    $('#data-table-simple').DataTable().destroy();
  }
  $('#data-table-simple').DataTable({ "order": [[1, "asc"]] });

  // deductible required state on change
  $(document).on('change', 'input[name="deductible_ing_id"]', ensureDeductibleRequired);

  // initial pass
  ensureDeductibleRequired();
});

/* lives outside ready, that’s fine */
function checkQuantitiesAndRedirect(batch_id, batch_qty) {
  $.ajax({
    url: 'check_quantities.php',
    type: 'POST',
    data: { batch_id: batch_id, batch_qty: batch_qty },
    success: function(response) {
      if(response && response.success) {
        window.location.href = 'new_page.php?batch_id=' + batch_id;
      } else {
        alert('Not enough stock for this batch.');
      }
    },
    error: function() {
      alert('An error occurred while checking quantities.');
    }
  });
}
  
// Read PPC and weight+unit from the selected product
function getSelectedProductMetrics() {
  var $opt = $('#product_id option:selected');
  var ppc  = parseFloat($opt.data('ppc'));  // product_setup.carton_pieces
  var w    = parseFloat($opt.data('w'));    // product_setup.weight (number)
  var unit = ($opt.data('unit') || '').toString().trim().toLowerCase();

  if (isNaN(ppc) || isNaN(w)) return null;

  // normalize grams -> kg
  var wKg;
  if (unit === 'gm' || unit === 'g' || unit === 'gram' || unit === 'grams') {
    wKg = w / 1000;
  } else if (unit === 'kg' || unit === 'kilogram' || unit === 'kilograms') {
    wKg = w;
  } else {
    // Unknown unit: assume grams
    wKg = w / 1000;
  }

  return { ppc: ppc, wKg: wKg };
}

// Compute and put the qty ONLY into the selected deductible row (works on Add & Edit)
function computeAndFillDeductibleQty() {
  // Global: find whichever table has the checked radio
  var $radio = $('input[name="deductible_ing_id"]:checked');
  if (!$radio.length) return;

  var m = getSelectedProductMetrics();
  if (!m) return;
  if (m.ppc <= 0 || m.wKg <= 0) return;

  // Usage % (0–<100). If blank, treat as 0.
  var usage = parseFloat($('#usage_percent').val());
  if (isNaN(usage)) usage = 0;
  if (usage < 0 || usage >= 100) return;

  // Base (in KG) = carton_pieces * weight_kg
  var baseKg = m.ppc * m.wKg;

  // qty = (base * 100) / (100 - usage)
  var denom = 100 - usage;
  if (denom <= 0) return;

  var qtyKg = (baseKg * 100) / denom;

  // Limit to 10 decimals
  var qtyStr = qtyKg.toFixed(10);

  // Fill only the deductible row's qty input
  $radio.closest('tr').find('input[name="per_unit[]"]').val(qtyStr);
}

// Events (apply for both Add & Edit)
$(document).on('change',  '#product_id',                    computeAndFillDeductibleQty);
$(document).on('input',   '#usage_percent',                 computeAndFillDeductibleQty);
$(document).on('change',  'input[name="deductible_ing_id"]',computeAndFillDeductibleQty);

// Recompute once after page is ready (helps Edit to prefill)
$(function(){ computeAndFillDeductibleQty(); });
// (Optional) If you want the value to prefill right after user adds a row and immediately selects it,
// just call computeAndFillDeductibleQty() after appending the row or after auto-checking the radio.
  
  // Read PPC and weight+unit from the selected product (shared for Add/Edit)
function getSelectedProductMetrics() {
  var $opt = $('#product_id option:selected');
  var ppc  = parseFloat($opt.data('ppc'));  // product_setup.carton_pieces
  var w    = parseFloat($opt.data('w'));    // product_setup.weight (number)
  var unit = ($opt.data('unit') || '').toString().trim().toLowerCase();

  if (isNaN(ppc) || isNaN(w)) return null;

  // normalize grams -> kg
  var wKg;
  if (unit === 'gm' || unit === 'g' || unit === 'gram' || unit === 'grams') {
    wKg = w / 1000;
  } else if (unit === 'kg' || unit === 'kilogram' || unit === 'kilograms') {
    wKg = w;
  } else {
    // Unknown unit: assume grams
    wKg = w / 1000;
  }

  return { ppc: ppc, wKg: wKg };
}

// Fill the side info row (Carton Pieces, Weight kg, Pieces×Weight)
function fillProductMetricsRow() {
  var m = getSelectedProductMetrics();
  if (!m) {
    // clear fields
    $('#prod_carton_pieces').val('');
    $('#prod_weight_kg').val('');
    $('#prod_base_kg').val('');
    // keep Materialize labels tidy
    $('label[for="prod_carton_pieces"],label[for="prod_weight_kg"],label[for="prod_base_kg"]').removeClass('active');
    return;
  }

  var baseKg = m.ppc * m.wKg;

  // set values (choose your precision preference)
  $('#prod_carton_pieces').val(String(m.ppc));
  $('#prod_weight_kg').val(m.wKg.toFixed(6));     // weight in kg (6 dp looks neat)
  $('#prod_base_kg').val(baseKg.toFixed(6));      // pieces × weight (kg)

  // Materialize labels must be "active" when setting programmatically
  $('label[for="prod_carton_pieces"],label[for="prod_weight_kg"],label[for="prod_base_kg"]').addClass('active');
}

// If you already have computeAndFillDeductibleQty, keep it.
// Otherwise, this is your qty calc that uses the same m/base:
function computeAndFillDeductibleQty() {
  var $radio = $('input[name="deductible_ing_id"]:checked');
  if (!$radio.length) return;

  var m = getSelectedProductMetrics();
  if (!m || m.ppc <= 0 || m.wKg <= 0) return;

  var usage = parseFloat($('#usage_percent').val());
  if (isNaN(usage)) usage = 0;
  if (usage < 0 || usage >= 100) return;

  var baseKg = m.ppc * m.wKg;
  var denom = 100 - usage;
  var qtyKg = (baseKg * 100) / denom;

  $radio.closest('tr').find('input[name="per_unit[]"]').val(qtyKg.toFixed(10));
}

// Wire up events
$(document).on('change', '#product_id', function() {
  fillProductMetricsRow();
  computeAndFillDeductibleQty();
});
$(document).on('input',  '#usage_percent', computeAndFillDeductibleQty);
$(document).on('change', 'input[name="deductible_ing_id"]', computeAndFillDeductibleQty);

// Initial fill on page load (helps Edit to show values immediately)
$(function(){
  fillProductMetricsRow();
  computeAndFillDeductibleQty();
});

  $(function(){
    if ($.fn.material_select) { $('select').material_select(); }  // old Materialize
    if (window.M && M.FormSelect) { M.FormSelect.init(document.querySelectorAll('select')); } // new Materialize
  });


</script>



</body>
</html>
