<!DOCTYPE html>
<html>
   <head>
      <!-- TABLES CSS CODE -->
      <?php include"comman/code_css.php"; ?>
      <style>
/* Dashboard-style KPI cards */
.kpi-row {
    display: grid;
    grid-template-columns: repeat(6, minmax(0, 1fr));
    gap: 14px;
    margin-bottom: 20px;
}

.kpi {
    position: relative;
    border-radius: 14px;
    min-height: 88px;
    padding: 14px 16px;
    color: #fff;
    box-shadow: 0 8px 28px rgba(15,23,42,.08), 0 2px 8px rgba(15,23,42,.05);
    overflow: hidden;
}

.kpi .value {
    font-size: 24px;
    font-weight: 900;
    line-height: 1;
    margin-bottom: 4px;
}

.kpi .label {
    letter-spacing: .3px;
    text-transform: uppercase;
    font-size: 11px;
    font-weight: 700;
    opacity: .9;
}

.kpi .kico {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 36px;
    opacity: .18;
}

/* Gradient backgrounds for different card types */
.kpi.p1 { background: linear-gradient(135deg, #a78bfa 0%, #ec4899 100%); }
.kpi.p2 { background: linear-gradient(135deg, #f43f5e 0%, #ef4444 50%, #ec4899 100%); }
.kpi.p3 { background: linear-gradient(135deg, #10b981 0%, #22c55e 100%); }
.kpi.p4 { background: linear-gradient(135deg, #0f172a 0%, #0ea5e9 100%); }
.kpi.p5 { background: linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%); }
.kpi.p6 { background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%); }

/* Responsive adjustments */
@media(max-width: 1200px) {
    .kpi-row {
        grid-template-columns: repeat(3, 1fr);
    }
    .kpi .value {
        font-size: 22px;
    }
    .kpi .kico {
        font-size: 32px;
    }
}

@media(max-width: 768px) {
    .kpi-row {
        grid-template-columns: repeat(2, 1fr);
    }
    .kpi {
        min-height: 80px;
        padding: 12px 14px;
    }
    .kpi .value {
        font-size: 20px;
    }
    .kpi .label {
        font-size: 10px;
    }
    .kpi .kico {
        font-size: 28px;
    }
}

@media(max-width: 480px) {
    .kpi-row {
        grid-template-columns: 1fr;
    }
    .kpi {
        min-height: 70px;
        padding: 10px 12px;
    }
    .kpi .value {
        font-size: 18px;
    }
    .kpi .label {
        font-size: 9px;
    }
    .kpi .kico {
        font-size: 24px;
    }
}

/* Filter form responsive */
@media(max-width: 768px) {
    .filter-form .form-group {
        margin-bottom: 10px;
    }
    .filter-form .control-label {
        padding-top: 7px;
        margin-bottom: 0;
        text-align: left !important;
    }
    .filter-form .col-sm-8 {
        width: 100%;
        padding-left: 0;
    }
}

/* Table responsive improvements */
@media(max-width: 768px) {
    .table-responsive {
        border: none;
    }
    .table th, .table td {
        padding: 8px 4px;
        font-size: 12px;
    }
    .btn-xs {
        padding: 2px 4px;
        font-size: 10px;
    }
}

/* Status and priority styling */
.status-pending { color: #f39c12; font-weight: bold; }
.status-approved { color: #27ae60; font-weight: bold; }
.status-rejected { color: #e74c3c; font-weight: bold; }
.status-draft { color: #95a5a6; font-weight: bold; }

.priority-high { color: #e74c3c; font-weight: bold; }
.priority-medium { color: #f39c12; font-weight: bold; }
.priority-low { color: #27ae60; font-weight: bold; }

/* Action buttons spacing */
.btn-group-xs > .btn, .btn-xs {
    margin-right: 2px;
}

/* Modal responsive */
@media(max-width: 768px) {
    .modal-dialog {
        margin: 10px;
    }
    .modal-lg {
        width: 95%;
    }
}

</style>
      <link rel="stylesheet" href="<?php echo $theme_link; ?>plugins/datepicker/datepicker3.css">
      <link rel="stylesheet" href="<?php echo $theme_link; ?>toastr/toastr.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-file-text-o text-primary"></i>
                  <?= $page_title; ?>
                  <small>Manage Purchase Requisition Orders</small>
               </h1>
               <ol class="breadcrumb">
                  <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</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>
               
               <!-- Dashboard-style KPI cards -->
               <div class="kpi-row">
                  <div class="kpi p1">
                     <div class="value"><?= isset($stats->total) ? $stats->total : 0; ?></div>
                     <div class="label">Total</div>
                     <i class="fa fa-file-text-o kico"></i>
                  </div>
                  <div class="kpi p2">
                     <div class="value" id="total-value"><?= isset($stats->total_value) ? store_currency_format($stats->total_value) : store_currency_format(0); ?></div>
                     <div class="label">Value</div>
                     <i class="fa fa-dollar kico"></i>
                  </div>
                  <div class="kpi p3">
                     <div class="value"><?= isset($stats->pending) ? $stats->pending : 0; ?></div>
                     <div class="label">Pending</div>
                     <i class="fa fa-clock-o kico"></i>
                  </div>
                  <div class="kpi p4">
                     <div class="value"><?= isset($stats->approved) ? $stats->approved : 0; ?></div>
                     <div class="label">Approved</div>
                     <i class="fa fa-check kico"></i>
                  </div>
                  <div class="kpi p5">
                     <div class="value"><?= isset($stats->converted) ? $stats->converted : 0; ?></div>
                     <div class="label">Converted</div>
                     <i class="fa fa-shopping-cart kico"></i>
                  </div>
                  <div class="kpi p6">
                     <div class="value"><?= isset($stats->rejected) ? $stats->rejected : 0; ?></div>
                     <div class="label">Rejected</div>
                     <i class="fa fa-times kico"></i>
                  </div>
               </div>
               <!-- /.row -->
               
               <div class="row">
                  <div class="col-md-12">
                     <div class="box box-primary">
                        <div class="box-header with-border">
                           <h3 class="box-title">
                              <i class="fa fa-filter"></i> Filter Requisitions
                           </h3>
                           <div class="box-tools pull-right">
                              <a href="<?=base_url('purchase_requisitions/add')?>" class="btn btn-success btn-sm">
                                 <i class="fa fa-plus"></i> Add New Requisition
                              </a>
                           </div>
                        </div>
                        
                        <div class="box-body">
                           <form class="form-horizontal filter-form" id="filter-form">
                              <div class="row">
                                 <div class="col-lg-3 col-md-6 col-sm-12">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">Status:</label>
                                       <div class="col-sm-8">
                                          <select class="form-control" name="status" id="status">
                                             <option value="">All Status</option>
                                             <option value="Draft">Draft</option>
                                             <option value="Pending">Pending</option>
                                             <option value="Approved">Approved</option>
                                             <option value="Rejected">Rejected</option>
                                             <option value="Converted">Converted</option>
                                          </select>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="col-lg-3 col-md-6 col-sm-12">
                                    <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">
                                             <option value="">All Priority</option>
                                             <option value="High">High</option>
                                             <option value="Medium">Medium</option>
                                             <option value="Low">Low</option>
                                          </select>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="col-lg-3 col-md-6 col-sm-12">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">From Date:</label>
                                       <div class="col-sm-8">
                                          <input type="text" class="form-control datepicker" name="from_date" id="from_date" placeholder="From Date">
                                       </div>
                                    </div>
                                 </div>
                                 <div class="col-lg-3 col-md-6 col-sm-12">
                                    <div class="form-group">
                                       <label class="control-label col-sm-4">To Date:</label>
                                       <div class="col-sm-8">
                                          <input type="text" class="form-control datepicker" name="to_date" id="to_date" placeholder="To Date">
                                       </div>
                                    </div>
                                 </div>
                              </div>
                              <div class="row">
                                 <div class="col-md-12 text-center">
                                    <button type="button" class="btn btn-primary" onclick="filterRequisitions()">
                                       <i class="fa fa-search"></i> Filter
                                    </button>
                                    <button type="button" class="btn btn-default" onclick="clearFilters()">
                                       <i class="fa fa-refresh"></i> Clear
                                    </button>
                                 </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-list"></i> Purchase Requisitions List
                           </h3>
                        </div>
                        
                        <div class="box-body">
                           <div class="table-responsive">
                              <table id="requisitions-table" class="table table-bordered table-striped">
                                 <thead>
                                    <tr>
                                       <th>Requisition #</th>
                                       <th>Date</th>
                                       <th>Requested By</th>
                                       <th>Priority</th>
                                       <th>Status</th>
                                       <th>Total Amount</th>
                                       <th>Items Count</th>
                                       <th>Actions</th>
                                    </tr>
                                 </thead>
                                 <tbody>
                                    <!-- DataTables will populate this via AJAX -->
                                 </tbody>
                              </table>
                           </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.js"></script>
      <script>$(".purchase-requisition-list-active-li").addClass("active");</script>


      <script>
      $(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"
          };
          
          // Format KPI value to readable format
          var totalValueElement = $('#total-value');
          if (totalValueElement.length) {
              var currentText = totalValueElement.text();
              var currencySymbol = currentText.match(/^[^\d]*/)[0]; // Extract currency symbol
              var amount = parseFloat(currentText.replace(/[^\d.]/g, '')); // Extract number
              if (!isNaN(amount)) {
                  totalValueElement.text(currencySymbol + format_amount_readable(amount));
              }
          }
          
          // Initialize DataTables with AJAX
          window.requisitionsTable = $('#requisitions-table').DataTable({
              "processing": true,
              "serverSide": true,
              "ajax": {
                  "url": "<?= base_url('purchase_requisitions/get_requisitions_data'); ?>",
                  "type": "GET"
              },
              "responsive": true,
              "lengthChange": false,
              "autoWidth": false,
              "pageLength": 25,
              "order": [[ 0, "desc" ]],
              "columnDefs": [
                  { "orderable": false, "targets": 7 } // Actions column
              ]
          });
          
          // Function to refresh the table
          window.refreshRequisitionsTable = function() {
              if (window.requisitionsTable) {
                  window.requisitionsTable.ajax.reload();
              }
          };
          
          // Check if we need to refresh after returning from conversion
          <?php if(isset($refresh_table) && $refresh_table): ?>
          setTimeout(function() {
              window.refreshRequisitionsTable();
          }, 1000);
          <?php endif; ?>
          
          // Event delegation for dynamically created buttons
          $(document).on('click', '.btn-approve', function() {
              var id = $(this).data('id');
              approveRequisition(id);
          });
          
          $(document).on('click', '.btn-reject', function() {
              var id = $(this).data('id');
              rejectRequisition(id);
          });
          
          $(document).on('click', '.btn-delete', function() {
              var id = $(this).data('id');
              deleteRequisition(id);
          });
          
          $(document).on('click', '.btn-view', function() {
              var id = $(this).data('id');
              viewRequisition(id);
          });
          
          $(document).on('click', '.btn-convert', function() {
              var id = $(this).data('id');
              convertToPurchase(id);
          });
          
          $(document).on('click', '.btn-view-purchase', function() {
              var purchaseId = $(this).data('id');
              window.open('<?= base_url(); ?>purchase/invoice/' + purchaseId, '_blank');
          });
          
          $(document).on('click', '.btn-unapprove', function() {
              var id = $(this).data('id');
              unapproveRequisition(id);
          });
          
          $(document).on('click', '.btn-edit', function() {
              var id = $(this).data('id');
              editRequisition(id);
          });
          
      });

      function filterRequisitions() {
          var status = $('#status').val();
          var priority = $('#priority').val();
          var fromDate = $('#from_date').val();
          var toDate = $('#to_date').val();
          
          // Reload DataTable with filters
          if (window.requisitionsTable) {
              window.requisitionsTable.ajax.url('<?= base_url('purchase_requisitions/get_requisitions_data'); ?>?status=' + encodeURIComponent(status) + 
                  '&priority=' + encodeURIComponent(priority) + 
                  '&from_date=' + encodeURIComponent(fromDate) + 
                  '&to_date=' + encodeURIComponent(toDate)).load();
          }
      }

      function clearFilters() {
          $('#filter-form')[0].reset();
          // Reload table without filters
          if (window.requisitionsTable) {
              window.requisitionsTable.ajax.url('<?= base_url('purchase_requisitions/get_requisitions_data'); ?>').load();
          }
      }

      // View requisition details in modal
      function viewRequisition(id) {
          // Show loading
          $('#view-modal-body').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading...</div>');
          $('#view-modal').modal('show');
          
          // Load requisition details via AJAX
          $.ajax({
              url: '<?= base_url(); ?>purchase_requisitions/get_requisition_details/' + id,
              type: 'GET',
              dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      displayRequisitionDetails(response.data);
                  } else {
                      $('#view-modal-body').html('<div class="alert alert-danger">Error: ' + (response.message || 'Failed to load requisition details') + '</div>');
                  }
              },
              error: function() {
                  $('#view-modal-body').html('<div class="alert alert-danger">Error: Failed to load requisition details</div>');
              }
          });
      }
      
      // Display requisition details in modal
      function displayRequisitionDetails(data) {
          var html = '<div class="row">';
          
          // Left column - Basic info
          html += '<div class="col-md-6">';
          html += '<table class="table table-bordered">';
          html += '<tr><th width="30%">Requisition Code:</th><td>' + data.requisition_code + '</td></tr>';
          html += '<tr><th>Date:</th><td>' + data.requisition_date + '</td></tr>';
          html += '<tr><th>Requested By:</th><td>' + (data.requested_by_name || 'Unknown') + '</td></tr>';
          html += '<tr><th>Priority:</th><td><span class="label label-' + getPriorityClass(data.priority) + '">' + data.priority + '</span></td></tr>';
          html += '<tr><th>Status:</th><td><span class="label label-' + getStatusClass(data.status) + '">' + data.status + '</span></td></tr>';
          html += '</table>';
          html += '</div>';
          
          // Right column - Additional info
          html += '<div class="col-md-6">';
          html += '<table class="table table-bordered">';
          html += '<tr><th width="30%">Warehouse:</th><td>' + (data.warehouse_name || 'Not specified') + '</td></tr>';
          html += '<tr><th>Store:</th><td>' + (data.store_name || 'Not specified') + '</td></tr>';
          html += '<tr><th>Currency:</th><td>' + (data.currency_name || 'US Dollar') + (data.symbol ? ' (' + data.symbol + ')' : '') + '</td></tr>';
          html += '<tr><th>Total Amount:</th><td><strong>' + format_currency(data.total_amount, data.symbol || data.currency_symbol) + '</strong></td></tr>';
          if (data.approved_by) {
              html += '<tr><th>Approved By:</th><td>' + (data.approved_by_name || data.approved_by) + '</td></tr>';
              html += '<tr><th>Approved Date:</th><td>' + data.approved_date + '</td></tr>';
          }
          if (data.rejected_by) {
              html += '<tr><th>Rejected By:</th><td>' + (data.rejected_by_name || data.rejected_by) + '</td></tr>';
              html += '<tr><th>Rejected Date:</th><td>' + data.rejected_date + '</td></tr>';
              if (data.rejection_reason) {
                  html += '<tr><th>Rejection Reason:</th><td>' + data.rejection_reason + '</td></tr>';
              }
          }
          html += '</table>';
          html += '</div>';
          html += '</div>';
          
          // Notes section
          if (data.notes) {
              html += '<div class="row"><div class="col-md-12"><h4>Notes:</h4><div class="well">' + data.notes.replace(/\n/g, '<br>') + '</div></div></div>';
          }
          
          // Items section
          html += '<div class="row"><div class="col-md-12"><h4>Items:</h4>';
          html += '<div class="table-responsive"><table class="table table-striped table-bordered">';
          html += '<thead><tr><th>Item</th><th>Description</th><th>Quantity</th><th>Unit Price</th><th>Total Price</th><th>Supplier</th><th>Status</th></tr></thead>';
          html += '<tbody>';
          
          if (data.items && data.items.length > 0) {
              for (var i = 0; i < data.items.length; i++) {
                  var item = data.items[i];
                  html += '<tr>';
                  html += '<td>' + (item.item_name || 'N/A') + '</td>';
                  html += '<td>' + (item.description || 'N/A') + '</td>';
                  html += '<td>' + number_format(item.requested_qty, 2) + '</td>';
                  html += '<td>' + format_currency(item.unit_price, data.symbol || data.currency_symbol) + '</td>';
                  html += '<td>' + format_currency(item.total_price, data.symbol || data.currency_symbol) + '</td>';
                  html += '<td>' + (item.supplier_name || 'N/A') + '</td>';
                  html += '<td><span class="label label-' + getStatusClass(item.status) + '">' + item.status + '</span></td>';
                  html += '</tr>';
              }
          } else {
              html += '<tr><td colspan="7" class="text-center">No items found</td></tr>';
          }
          
          html += '</tbody></table></div></div></div>';
          
          $('#view-modal-body').html(html);
      }
      
      // Helper functions
      function getPriorityClass(priority) {
          return priority == 'High' ? 'danger' : (priority == 'Medium' ? 'warning' : 'info');
      }
      
      function getStatusClass(status) {
          return status.toLowerCase() == 'pending' ? 'warning' : 
                 (status.toLowerCase() == 'approved' ? 'success' : 
                 (status.toLowerCase() == 'rejected' ? 'danger' : 'info'));
      }
      
      function number_format(num, decimals) {
          return parseFloat(num).toFixed(decimals);
      }
      
      // Format numbers in readable format (12K, 12M, 12B, 12T, etc.)
      function format_amount_readable(amount) {
          amount = parseFloat(amount);
          
          if (amount >= 1000000000000) {
              return (amount / 1000000000000).toFixed(1) + 'T';
          } else if (amount >= 1000000000) {
              return (amount / 1000000000).toFixed(1) + 'B';
          } else if (amount >= 1000000) {
              return (amount / 1000000).toFixed(1) + 'M';
          } else if (amount >= 1000) {
              return (amount / 1000).toFixed(1) + 'K';
          } else {
              return amount.toFixed(0);
          }
      }
      
      // Format currency with proper placement
      function format_currency(amount, symbol) {
          var currencySymbol = symbol || '<?= get_store_currency()->symbol ?? get_store_currency()->currency_symbol ?? "$"; ?>';
          var placement = '<?= $this->session->userdata("currency_placement") ?: "Left"; ?>';
          var formattedAmount = format_amount_readable(amount);
          
          if (placement == 'Right') {
              return formattedAmount + ' ' + currencySymbol;
          } else {
              return currencySymbol + formattedAmount;
          }
      }

      // Approve requisition
      function approveRequisition(id) {
          window.currentRequisitionId = id;
          $('#approve-modal').modal('show');
      }

      // Confirm approval
      function confirmApproval() {
          var id = window.currentRequisitionId;
          $('#approve-modal').modal('hide');
          
          toastr.info('Processing approval...', 'Please wait', {
              timeOut: 0,
              extendedTimeOut: 0,
              closeButton: false,
              tapToDismiss: false
          });
          
          $.ajax({
              url: '<?= base_url(); ?>purchase_requisitions/approve/' + id,
              type: 'POST',
              data: {
                  '<?php echo $this->security->get_csrf_token_name();?>': '<?php echo $this->security->get_csrf_hash();?>'
              },
              dataType: 'json',
              success: function(response) {
                  toastr.clear();
                  if (response.success) {
                      toastr.success('Requisition approved successfully!', 'Success', {
                          timeOut: 3000,
                          progressBar: true
                      });
                      setTimeout(function() {
                          window.refreshRequisitionsTable();
                      }, 1000);
                  } else {
                      toastr.error('Error: ' + (response.message || 'Failed to approve requisition'), 'Error', {
                          timeOut: 5000,
                          progressBar: true
                      });
                  }
              },
              error: function() {
                  toastr.clear();
                  toastr.error('Error: Failed to approve requisition', 'Error', {
                      timeOut: 5000,
                      progressBar: true
                  });
              }
          });
      }

      // Reject requisition
      function rejectRequisition(id) {
          window.currentRequisitionId = id;
          $('#rejection-reason').val(''); // Clear previous reason
          $('#reject-modal').modal('show');
      }

      // Confirm rejection
      function confirmRejection() {
          var id = window.currentRequisitionId;
          var reason = $('#rejection-reason').val().trim();
          
          if (!reason) {
              toastr.warning('Please provide a rejection reason', 'Required Field', {
                  timeOut: 3000,
                  progressBar: true
              });
              $('#rejection-reason').focus();
              return;
          }
          
          $('#reject-modal').modal('hide');
          
          toastr.info('Processing rejection...', 'Please wait', {
              timeOut: 0,
              extendedTimeOut: 0,
              closeButton: false,
              tapToDismiss: false
          });
          
          $.ajax({
              url: '<?= base_url(); ?>purchase_requisitions/reject/' + id,
              type: 'POST',
              data: {
                  reason: reason,
                  '<?php echo $this->security->get_csrf_token_name();?>': '<?php echo $this->security->get_csrf_hash();?>'
              },
              dataType: 'json',
              success: function(response) {
                  toastr.clear();
                  if (response.success) {
                      toastr.success('Requisition rejected successfully!', 'Success', {
                          timeOut: 3000,
                          progressBar: true
                      });
                      setTimeout(function() {
                          window.refreshRequisitionsTable();
                      }, 1000);
                  } else {
                      toastr.error('Error: ' + (response.message || 'Failed to reject requisition'), 'Error', {
                          timeOut: 5000,
                          progressBar: true
                      });
                  }
              },
              error: function() {
                  toastr.clear();
                  toastr.error('Error: Failed to reject requisition', 'Error', {
                      timeOut: 5000,
                      progressBar: true
                  });
              }
          });
      }

      // Delete requisition
      function deleteRequisition(id) {
          window.currentRequisitionId = id;
          $('#delete-modal').modal('show');
      }

      // Confirm delete
      function confirmDelete() {
          var id = window.currentRequisitionId;
          $('#delete-modal').modal('hide');
          
          toastr.info('Processing deletion...', 'Please wait', {
              timeOut: 0,
              extendedTimeOut: 0,
              closeButton: false,
              tapToDismiss: false
          });
          
          $.ajax({
              url: '<?= base_url(); ?>purchase_requisitions/delete/' + id,
              type: 'POST',
              data: {
                  '<?php echo $this->security->get_csrf_token_name();?>': '<?php echo $this->security->get_csrf_hash();?>'
              },
              dataType: 'json',
              success: function(response) {
                  toastr.clear();
                  if (response.success) {
                      toastr.success('Requisition deleted successfully!', 'Success', {
                          timeOut: 3000,
                          progressBar: true
                      });
                      setTimeout(function() {
                          window.refreshRequisitionsTable();
                      }, 1000);
                  } else {
                      toastr.error('Error: ' + (response.message || 'Failed to delete requisition'), 'Error', {
                          timeOut: 5000,
                          progressBar: true
                      });
                  }
              },
              error: function() {
                  toastr.clear();
                  toastr.error('Error: Failed to delete requisition', 'Error', {
                      timeOut: 5000,
                      progressBar: true
                  });
              }
          });
      }

      // Convert to purchase
      function convertToPurchase(id) {
          window.currentRequisitionId = id;
          $('#convert-modal').modal('show');
      }

      // Confirm convert
      function confirmConvert() {
          var id = window.currentRequisitionId;
          $('#convert-modal').modal('hide');
          
          toastr.info('Converting to purchase...', 'Please wait', {
              timeOut: 0,
              extendedTimeOut: 0,
              closeButton: false,
              tapToDismiss: false
          });
          
          window.location.href = '<?= base_url(); ?>purchase_requisitions/convert_to_purchase/' + id;
      }

      // Unapprove requisition
      function unapproveRequisition(id) {
          window.currentRequisitionId = id;
          $('#unapprove-modal').modal('show');
      }

      // Confirm unapprove
      function confirmUnapprove() {
          var id = window.currentRequisitionId;
          $('#unapprove-modal').modal('hide');
          
          toastr.info('Processing unapproval...', 'Please wait', {
              timeOut: 0,
              extendedTimeOut: 0,
              closeButton: false,
              tapToDismiss: false
          });
          
          $.ajax({
              url: '<?= base_url(); ?>purchase_requisitions/unapprove/' + id,
              type: 'POST',
              data: {
                  '<?php echo $this->security->get_csrf_token_name();?>': '<?php echo $this->security->get_csrf_hash();?>'
              },
              dataType: 'json',
              success: function(response) {
                  toastr.clear();
                  if (response.success) {
                      toastr.success('Requisition unapproved successfully!', 'Success', {
                          timeOut: 3000,
                          progressBar: true
                      });
                      setTimeout(function() {
                          window.refreshRequisitionsTable();
                      }, 1000);
                  } else {
                      toastr.error('Error: ' + (response.message || 'Failed to unapprove requisition'), 'Error', {
                          timeOut: 5000,
                          progressBar: true
                      });
                  }
              },
              error: function() {
                  toastr.clear();
                  toastr.error('Error: Failed to unapprove requisition', 'Error', {
                      timeOut: 5000,
                      progressBar: true
                  });
              }
          });
      }

      // Edit requisition
      function editRequisition(id) {
          window.location.href = '<?= base_url(); ?>purchase_requisitions/edit/' + id;
      }
      </script>

      <!-- View Requisition Modal -->
      <div class="modal fade" id="view-modal" tabindex="-1" role="dialog" aria-labelledby="view-modal-label">
          <div class="modal-dialog modal-lg" role="document">
              <div class="modal-content">
                  <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                      </button>
                      <h4 class="modal-title" id="view-modal-label">
                          <i class="fa fa-eye"></i> View Purchase Requisition
                      </h4>
                  </div>
                  <div class="modal-body" id="view-modal-body">
                      <!-- Content will be loaded here -->
                  </div>
                  <div class="modal-footer">
                      <button type="button" class="btn btn-default" data-dismiss="modal">
                          <i class="fa fa-times"></i> Close
                      </button>
                  </div>
              </div>
          </div>
      </div>

      <!-- Rejection Reason Modal -->
      <div class="modal fade" id="reject-modal" tabindex="-1" role="dialog">
          <div class="modal-dialog" role="document">
              <div class="modal-content">
                  <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal">&times;</button>
                      <h4 class="modal-title"><i class="fa fa-times text-danger"></i> Reject Requisition</h4>
                  </div>
                  <div class="modal-body">
                      <form id="reject-form">
                          <div class="form-group">
                              <label for="rejection-reason">Rejection Reason <span class="text-danger">*</span></label>
                              <textarea class="form-control" id="rejection-reason" name="reason" rows="4" 
                                        placeholder="Please provide a detailed reason for rejecting this requisition..." required></textarea>
                          </div>
                      </form>
                  </div>
                  <div class="modal-footer">
                      <button type="button" class="btn btn-default" data-dismiss="modal">
                          <i class="fa fa-times"></i> Cancel
                      </button>
                      <button type="button" class="btn btn-danger" onclick="confirmRejection()">
                          <i class="fa fa-times"></i> Reject Requisition
                      </button>
                  </div>
              </div>
          </div>
      </div>

      <!-- Approval Confirmation Modal -->
      <div class="modal fade" id="approve-modal" tabindex="-1" role="dialog">
          <div class="modal-dialog" role="document">
              <div class="modal-content">
                  <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal">&times;</button>
                      <h4 class="modal-title"><i class="fa fa-check text-success"></i> Approve Requisition</h4>
                  </div>
                  <div class="modal-body">
                      <div class="alert alert-info">
                          <i class="fa fa-info-circle"></i>
                          <strong>Are you sure you want to approve this requisition?</strong>
                          <br><br>
                          This action will mark the requisition as approved and it will be available for conversion to purchase order.
                      </div>
                  </div>
                  <div class="modal-footer">
                      <button type="button" class="btn btn-default" data-dismiss="modal">
                          <i class="fa fa-times"></i> Cancel
                      </button>
                      <button type="button" class="btn btn-success" onclick="confirmApproval()">
                          <i class="fa fa-check"></i> Approve Requisition
                      </button>
                  </div>
              </div>
          </div>
      </div>

      <!-- Delete Confirmation Modal -->
      <div class="modal fade" id="delete-modal" tabindex="-1" role="dialog">
          <div class="modal-dialog" role="document">
              <div class="modal-content">
                  <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal">&times;</button>
                      <h4 class="modal-title"><i class="fa fa-trash text-danger"></i> Delete Requisition</h4>
                  </div>
                  <div class="modal-body">
                      <div class="alert alert-danger">
                          <i class="fa fa-exclamation-triangle"></i>
                          <strong>Are you sure you want to delete this requisition?</strong>
                          <br><br>
                          This action cannot be undone and will permanently remove the requisition and all its associated data.
                      </div>
                  </div>
                  <div class="modal-footer">
                      <button type="button" class="btn btn-default" data-dismiss="modal">
                          <i class="fa fa-times"></i> Cancel
                      </button>
                      <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                          <i class="fa fa-trash"></i> Delete Requisition
                      </button>
                  </div>
              </div>
          </div>
      </div>

      <!-- Convert Confirmation Modal -->
      <div class="modal fade" id="convert-modal" tabindex="-1" role="dialog">
          <div class="modal-dialog" role="document">
              <div class="modal-content">
                  <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal">&times;</button>
                      <h4 class="modal-title"><i class="fa fa-shopping-cart text-primary"></i> Convert to Purchase</h4>
                  </div>
                  <div class="modal-body">
                      <div class="alert alert-info">
                          <i class="fa fa-info-circle"></i>
                          <strong>Are you sure you want to convert this requisition to a purchase?</strong>
                          <br><br>
                          This action will open the Purchase page with all requisition details pre-filled. You can then review and adjust the details as needed before creating the purchase.
                      </div>
                  </div>
                  <div class="modal-footer">
                      <button type="button" class="btn btn-default" data-dismiss="modal">
                          <i class="fa fa-times"></i> Cancel
                      </button>
                      <button type="button" class="btn btn-primary" onclick="confirmConvert()">
                          <i class="fa fa-shopping-cart"></i> Convert to Purchase
                      </button>
                  </div>
              </div>
          </div>
      </div>

      <!-- Unapprove Confirmation Modal -->
      <div class="modal fade" id="unapprove-modal" tabindex="-1" role="dialog">
          <div class="modal-dialog" role="document">
              <div class="modal-content">
                  <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal">&times;</button>
                      <h4 class="modal-title"><i class="fa fa-undo text-warning"></i> Unapprove Requisition</h4>
                  </div>
                  <div class="modal-body">
                      <div class="alert alert-warning">
                          <i class="fa fa-exclamation-triangle"></i>
                          <strong>Are you sure you want to unapprove this requisition?</strong>
                          <br><br>
                          This action will revert the requisition status from "Approved" back to "Pending". The requisition will need to be approved again before it can be converted to a purchase order.
                      </div>
                  </div>
                  <div class="modal-footer">
                      <button type="button" class="btn btn-default" data-dismiss="modal">
                          <i class="fa fa-times"></i> Cancel
                      </button>
                      <button type="button" class="btn btn-warning" onclick="confirmUnapprove()">
                          <i class="fa fa-undo"></i> Unapprove Requisition
                      </button>
                  </div>
              </div>
          </div>
      </div>

   </body>
</html>