<!DOCTYPE html>
<html>
   <head>
      <!-- TABLES CSS CODE -->
      <?php include"comman/code_css.php"; ?>
      <style>
@media(max-width: 480px){
.small-box h3 {
  font-size: 23px;
  font-weight: bold;
  margin: 0 0 10px 0;
  white-space: nowrap;
  padding: 0;
}
}
.sectionmenu {
    display: block;
    min-height: 110px;
    background: #fff;
    width: 100%;
    box-shadow: 0 1px 1px rgba(0,0,0,0.1);
    border-radius: 5px;
    margin-bottom: 35px;
}
.sectionmenu .info-box-icon {
    border-top-left-radius: 2px;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    border-bottom-left-radius: 2px;
    display: block;
    float: right;
    height: 80px;
    margin-right: 20px;
    margin-top: 13px;
    margin-left: 10px;
    padding: 8px;
    border-radius: 60px;
    background-color: rgb(0 0 0 / 31%);
    color: white;
    width: 80px;
    text-align: center;
    font-size: 40px;
    line-height: 68px;
}
.sectionmenu .info-box-content {
    padding: 24px 10px;
    margin-left: 27px;
}
.info-box-number {
    display: block;
    font-weight: bold;
    font-size: 14px;
}

/* Warning highlight for duplicate items */
.warning {
    background-color: #fff3cd !important;
    border-left: 4px solid #ffc107 !important;
    animation: pulse 1s ease-in-out;
}

@keyframes pulse {
    0% { background-color: #fff3cd; }
    50% { background-color: #ffeaa7; }
    100% { background-color: #fff3cd; }
}

</style>
      <link rel="stylesheet" href="<?php echo $theme_link; ?>plugins/datepicker/datepicker3.css">
      <link rel="stylesheet" href="<?php echo $theme_link; ?>toastr/toastr.min.css">
   </head>
   <body class="hold-transition skin-blue sidebar-mini">
      <!-- Change the theme color if it is set -->
      <div class="wrapper">
         <!-- Left side column. contains the logo and sidebar -->
         <?php include"sidebar.php"; ?>
         <!-- Content Wrapper. Contains page content -->
         <div class="content-wrapper">
            <!-- Content Header (Page header) -->
            <section class="content-header">
               <h1>
                  <i class="fa fa-edit text-warning"></i>
                  <?= $page_title; ?>
                  <small>Edit Purchase Requisition Order</small>
               </h1>
               <ol class="breadcrumb">
                  <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
                  <li><a href="<?php echo $base_url; ?>purchase_requisitions">Purchase Requisitions</a></li>
                  <li class="active"><?= $page_title; ?></li>
               </ol>
            </section>
            <!-- Main content -->
            <section class="content">
               <!-- Alert Messages -->
               <div class="row">
                  <?php include "comman/code_flashdata.php"; ?>
               </div>
               
               <div class="row">
                  <div class="col-md-12">
                     <div class="box box-warning">
                        <div class="box-header with-border">
                           <h3 class="box-title">
                              <i class="fa fa-file-text-o"></i> Requisition Details
                           </h3>
                        </div>
                        
                        <div class="box-body">
                           <form id="requisition-form" class="form-horizontal">
                              <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                              
                              <div class="row">
                                 <div class="col-md-6">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">Requisition Code:</label>
                                       <div class="col-sm-8">
                                          <input type="text" class="form-control" value="<?= $requisition->requisition_code; ?>" readonly>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="col-md-6">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">Status:</label>
                                       <div class="col-sm-8">
                                          <span class="label label-<?= $requisition->status == 'Pending' ? 'warning' : ($requisition->status == 'Approved' ? 'success' : ($requisition->status == 'Rejected' ? 'danger' : 'info')); ?>">
                                             <?= ucfirst($requisition->status); ?>
                                          </span>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                              
                              <div class="row">
                                 <div class="col-md-6">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">Requisition Date:</label>
                                       <div class="col-sm-8">
                                          <input type="text" class="form-control datepicker" name="requisition_date" id="requisition_date" value="<?= $requisition->requisition_date; ?>" required>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="col-md-6">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">Requested By:</label>
                                       <div class="col-sm-8">
                                          <input type="text" class="form-control" value="<?= $requisition->requested_by_name; ?>" readonly>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                              
                              <div class="row">
                                 <div class="col-md-6">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">Priority:</label>
                                       <div class="col-sm-8">
                                          <select class="form-control" name="priority" id="priority" required>
                                             <option value="Low" <?= ($requisition->priority == 'Low') ? 'selected' : ''; ?>>Low</option>
                                             <option value="Medium" <?= ($requisition->priority == 'Medium') ? 'selected' : ''; ?>>Medium</option>
                                             <option value="High" <?= ($requisition->priority == 'High') ? 'selected' : ''; ?>>High</option>
                                          </select>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="col-md-6">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">Store:</label>
                                       <div class="col-sm-8">
                                          <input type="text" class="form-control" value="<?= $requisition->store_name; ?>" readonly>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                              
                              <div class="row">
                                 <div class="col-md-6">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">Warehouse:</label>
                                       <div class="col-sm-8">
                                          <select class="form-control" name="warehouse_id" id="warehouse_id" required>
                                             <option value="">Select Warehouse</option>
                                             <?php foreach($warehouses as $warehouse): ?>
                                             <option value="<?= $warehouse->id; ?>" <?= ($warehouse->id == $requisition->warehouse_id) ? 'selected' : ''; ?>>
                                                <?= $warehouse->warehouse_name; ?>
                                             </option>
                                             <?php endforeach; ?>
                                          </select>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="col-md-6">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">Currency:</label>
                                       <div class="col-sm-8">
                                          <input type="text" class="form-control" value="<?= $currency_name; ?><?= !empty($currency_symbol) ? ' (' . $currency_symbol . ')' : ''; ?>" readonly>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                              
                              <div class="row">
                                 <div class="col-md-12">
                                    <div class="form-group">
                                       <label class="control-label col-sm-2">Notes:</label>
                                       <div class="col-sm-10">
                                          <textarea class="form-control" name="notes" id="notes" rows="3" placeholder="Additional notes or comments"><?= $requisition->notes; ?></textarea>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                           </form>
                        </div>
                     </div>
                  </div>
               </div>
               
               <div class="row">
                  <div class="col-md-12">
                     <div class="box box-info">
                        <div class="box-header with-border">
                           <h3 class="box-title">
                              <i class="fa fa-shopping-cart"></i> Requisition Items
                           </h3>
                           <div class="box-tools pull-right">
                              <button type="button" class="btn btn-success btn-sm" onclick="addNewItem()">
                                 <i class="fa fa-plus"></i> Add Item
                              </button>
                           </div>
                        </div>
                        
                        <div class="box-body">
                           <div class="table-responsive">
                              <table id="items-table" class="table table-bordered table-striped">
                                 <thead>
                                    <tr>
                                       <th>Item</th>
                                       <th>Description</th>
                                       <th>Quantity</th>
                                       <th>Unit Price</th>
                                       <th>Total</th>
                                       <th>Supplier <small class="text-muted">(Recommended)</small></th>
                                       <th>Actions</th>
                                    </tr>
                                 </thead>
                                 <tbody id="items-tbody">
                                    <!-- Items will be loaded from existing data -->
                                 </tbody>
                                 <tfoot>
                                    <tr>
                                       <th colspan="4" class="text-right">Grand Total:</th>
                                       <th id="grand-total"><?= number_format($requisition->total_amount, 2); ?></th>
                                       <th colspan="2"></th>
                                    </tr>
                                 </tfoot>
                              </table>
                           </div>
                        </div>
                        
                        <div class="box-footer">
                           <div class="row">
                              <div class="col-md-12 text-center">
                                 <button type="button" class="btn btn-warning" onclick="updateRequisition()">
                                    <i class="fa fa-save"></i> Update Requisition
                                 </button>
                                 <a href="<?=base_url('purchase_requisitions')?>" class="btn btn-default">
                                    <i class="fa fa-times"></i> Cancel
                                 </a>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </section>
         </div>
         
         <!-- Footer -->
         <?php include"footer.php"; ?>
      </div>
      <!-- ./wrapper -->

      <!-- TABLES JS CODE -->
      <?php include"comman/code_js.php"; ?>
      <script src="<?php echo $theme_link; ?>toastr/toastr.min.js"></script>

      <script>
      var itemCounter = 0;
      var requisitionId = <?= $requisition->id; ?>;

      $(document).ready(function() {
          // Initialize datepicker
          $('.datepicker').datepicker({
              autoclose: true,
              format: 'yyyy-mm-dd'
          });
          
          // Initialize toastr
          toastr.options = {
              "closeButton": true,
              "debug": false,
              "newestOnTop": true,
              "progressBar": true,
              "positionClass": "toast-top-right",
              "preventDuplicates": false,
              "onclick": null,
              "showDuration": "300",
              "hideDuration": "1000",
              "timeOut": "5000",
              "extendedTimeOut": "1000",
              "showEasing": "swing",
              "hideEasing": "linear",
              "showMethod": "fadeIn",
              "hideMethod": "fadeOut"
          };
          
          // Load existing items
          loadExistingItems();
      });

      function loadExistingItems() {
          <?php if (!empty($requisition_items)): ?>
              <?php foreach($requisition_items as $item): ?>
                  itemCounter++;
                  var itemRow = `
                      <tr id="item-row-${itemCounter}">
                          <td>
                              <select class="form-control item-select" name="items[${itemCounter}][item_id]" id="item-id-${itemCounter}" required onchange="checkDuplicateItem(${itemCounter})">
                                  <option value="">Select Item</option>
                                  <?php foreach($items as $item_option): ?>
                                  <option value="<?= $item_option->id; ?>" data-price="<?= $item_option->sales_price; ?>" data-name="<?= htmlspecialchars($item_option->item_name); ?>" <?= ($item_option->id == $item->item_id) ? 'selected' : ''; ?>>
                                      <?= $item_option->item_name; ?> (Stock: <?= $item_option->stock; ?>)
                                  </option>
                                  <?php endforeach; ?>
                              </select>
                          </td>
                          <td>
                              <input type="text" class="form-control" name="items[${itemCounter}][description]" 
                                     id="item-description-${itemCounter}" value="<?= htmlspecialchars($item->description); ?>" placeholder="Item description">
                          </td>
                          <td>
                              <input type="number" class="form-control quantity" name="items[${itemCounter}][quantity]" 
                                     id="quantity-${itemCounter}" value="<?= $item->requested_qty; ?>" min="1" step="0.01" onchange="calculateTotal(${itemCounter})">
                          </td>
                          <td>
                              <input type="number" class="form-control unit-price" name="items[${itemCounter}][unit_price]" 
                                     id="unit-price-${itemCounter}" value="<?= $item->unit_price; ?>" min="0" step="0.01" onchange="calculateTotal(${itemCounter})">
                          </td>
                          <td>
                              <input type="text" class="form-control total" name="items[${itemCounter}][total]" 
                                     id="total-${itemCounter}" value="<?= $item->total_price; ?>" readonly>
                          </td>
                          <td>
                              <select class="form-control" name="items[${itemCounter}][supplier_id]" id="supplier-${itemCounter}" title="Recommended: Select supplier for better procurement workflow">
                                  <option value="">Select Supplier (Recommended)</option>
                                  <?php foreach($suppliers as $supplier): ?>
                                  <option value="<?= $supplier->id; ?>" <?= ($supplier->id == $item->supplier_id) ? 'selected' : ''; ?>><?= $supplier->supplier_name; ?></option>
                                  <?php endforeach; ?>
                              </select>
                          </td>
                          <td>
                              <button type="button" class="btn btn-danger btn-sm" onclick="removeItem(${itemCounter})">
                                  <i class="fa fa-trash"></i>
                              </button>
                          </td>
                      </tr>
                  `;
                  $('#items-tbody').append(itemRow);
              <?php endforeach; ?>
          <?php endif; ?>
      }

      function addNewItem() {
          itemCounter++;
          var itemRow = `
              <tr id="item-row-${itemCounter}">
                  <td>
                      <select class="form-control item-select" name="items[${itemCounter}][item_id]" id="item-id-${itemCounter}" required onchange="checkDuplicateItem(${itemCounter})">
                          <option value="">Select Item</option>
                          <?php foreach($items as $item): ?>
                          <option value="<?= $item->id; ?>" data-price="<?= $item->sales_price; ?>" data-name="<?= htmlspecialchars($item->item_name); ?>">
                              <?= $item->item_name; ?> (Stock: <?= $item->stock; ?>)
                          </option>
                          <?php endforeach; ?>
                      </select>
                  </td>
                  <td>
                      <input type="text" class="form-control" name="items[${itemCounter}][description]" 
                             id="item-description-${itemCounter}" placeholder="Item description">
                  </td>
                  <td>
                      <input type="number" class="form-control quantity" name="items[${itemCounter}][quantity]" 
                             id="quantity-${itemCounter}" min="1" step="0.01" onchange="calculateTotal(${itemCounter})">
                  </td>
                  <td>
                      <input type="number" class="form-control unit-price" name="items[${itemCounter}][unit_price]" 
                             id="unit-price-${itemCounter}" min="0" step="0.01" onchange="calculateTotal(${itemCounter})">
                  </td>
                  <td>
                      <input type="text" class="form-control total" name="items[${itemCounter}][total]" 
                             id="total-${itemCounter}" readonly>
                  </td>
                  <td>
                      <select class="form-control" name="items[${itemCounter}][supplier_id]" id="supplier-${itemCounter}" title="Recommended: Select supplier for better procurement workflow">
                          <option value="">Select Supplier (Recommended)</option>
                          <?php foreach($suppliers as $supplier): ?>
                          <option value="<?= $supplier->id; ?>"><?= $supplier->supplier_name; ?></option>
                          <?php endforeach; ?>
                      </select>
                  </td>
                  <td>
                      <button type="button" class="btn btn-danger btn-sm" onclick="removeItem(${itemCounter})">
                          <i class="fa fa-trash"></i>
                      </button>
                  </td>
              </tr>
          `;
          $('#items-tbody').append(itemRow);
      }

      function calculateTotal(counter) {
          var quantity = parseFloat($('#quantity-' + counter).val()) || 0;
          var unitPrice = parseFloat($('#unit-price-' + counter).val()) || 0;
          var total = quantity * unitPrice;
          $('#total-' + counter).val(total.toFixed(2));
          calculateGrandTotal();
      }

      // Handle item selection to auto-fill price (moved to checkDuplicateItem function)

      function calculateGrandTotal() {
          var grandTotal = 0;
          $('.total').each(function() {
              grandTotal += parseFloat($(this).val()) || 0;
          });
          $('#grand-total').text(grandTotal.toFixed(2));
      }

      function removeItem(counter) {
          $('#item-row-' + counter).remove();
          calculateGrandTotal();
      }

      function checkDuplicateItem(counter) {
          var selectedItemId = $('#item-id-' + counter).val();
          var selectedItemName = $('#item-id-' + counter).find('option:selected').data('name');
          
          if (!selectedItemId) return;
          
          var isDuplicate = false;
          var existingRow = null;
          
          // Check all other rows for duplicate items
          $('#items-tbody tr').each(function() {
              var rowId = $(this).attr('id');
              if (rowId && rowId !== 'item-row-' + counter) {
                  var existingItemId = $(this).find('.item-select').val();
                  if (existingItemId === selectedItemId) {
                      isDuplicate = true;
                      existingRow = rowId;
                      return false; // Break the loop
                  }
              }
          });
          
          if (isDuplicate) {
              toastr.warning('Item "' + selectedItemName + '" has already been added. You can adjust the quantity in the existing row.');
              
              // Reset the current selection
              $('#item-id-' + counter).val('');
              
              // Highlight the existing row
              $('#' + existingRow).addClass('warning');
              setTimeout(function() {
                  $('#' + existingRow).removeClass('warning');
              }, 3000);
              
              return false;
          }
          
          // Auto-fill price if not duplicate
          var selectedOption = $('#item-id-' + counter).find('option:selected');
          var price = selectedOption.data('price');
          
          if (price) {
              $('#unit-price-' + counter).val(price);
              calculateTotal(counter);
          }
      }

      function updateRequisition() {
          // Validate form
          if (!$('#requisition_date').val()) {
              toastr.error('Please select requisition date');
              return;
          }
          
          if ($('#items-tbody tr').length === 0) {
              toastr.error('Please add at least one item');
              return;
          }
          
          // Collect form data
          var formData = {
              requisition_date: $('#requisition_date').val(),
              priority: $('#priority').val(),
              warehouse_id: $('#warehouse_id').val(),
              notes: $('#notes').val(),
              items: []
          };
          
          // Collect items data
          $('#items-tbody tr').each(function() {
              var row = $(this);
              var itemData = {
                  item_id: row.find('.item-select').val(),
                  description: row.find('input[name*="[description]"]').val(),
                  quantity: row.find('input[name*="[quantity]"]').val(),
                  unit_price: row.find('input[name*="[unit_price]"]').val(),
                  total: row.find('input[name*="[total]"]').val(),
                  supplier_id: row.find('select[name*="[supplier_id]"]').val()
              };
              formData.items.push(itemData);
          });
          
          // Send AJAX request
          $.ajax({
              url: '<?= base_url(); ?>purchase_requisitions/update/' + requisitionId,
              type: 'POST',
              data: formData,
              dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      toastr.success('Requisition updated successfully!');
                      setTimeout(function() {
                          window.location.href = '<?= base_url(); ?>purchase_requisitions';
                      }, 1500);
                  } else {
                      toastr.error('Error: ' + (response.message || 'Failed to update requisition'));
                  }
              },
              error: function() {
                  toastr.error('Error: Failed to update requisition');
              }
          });
      }
      </script>

      <!-- Make sidebar menu highlighter/selector -->
      <script>$(".purchase-requisition-active-li").addClass("active");</script>
   </body>
</html>
