<!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;
}

.settings-group {
    margin-bottom: 30px;
}

.settings-group h4 {
    color: #3c8dbc;
    border-bottom: 2px solid #3c8dbc;
    padding-bottom: 10px;
    margin-bottom: 20px;
}

.setting-item {
    background: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 15px;
    margin-bottom: 15px;
}

.setting-item .setting-label {
    font-weight: bold;
    color: #333;
    margin-bottom: 5px;
}

.setting-item .setting-description {
    color: #666;
    font-size: 12px;
    margin-bottom: 10px;
}

.setting-item .form-group {
    margin-bottom: 0;
}

.help-text {
    color: #666;
    font-size: 11px;
    font-style: italic;
}

.test-buttons {
    margin-top: 10px;
}

.test-buttons .btn {
    margin-right: 10px;
}

.json-editor {
    font-family: monospace;
    min-height: 100px;
}

</style>
   </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-cogs text-primary"></i>
                  <?= $page_title; ?>
                  <small>Configure Purchase Requisition Order System</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-primary">
                        <div class="box-header with-border">
                           <h3 class="box-title">
                              <i class="fa fa-cogs"></i> System Configuration
                           </h3>
                           <div class="box-tools pull-right">
                              <button type="button" class="btn btn-warning btn-sm" onclick="resetToDefault()">
                                 <i class="fa fa-refresh"></i> Reset to Default
                              </button>
                              <button type="button" class="btn btn-success btn-sm" onclick="saveAllSettings()">
                                 <i class="fa fa-save"></i> Save All Settings
                              </button>
                           </div>
                        </div>
                        
                        <div class="box-body">
                           <form id="settings-form">
                              <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                              
                              <!-- Approval Users Management -->
                              <div class="settings-group">
                                 <h4><i class="fa fa-users"></i> Approval Users Management</h4>
                                 
                                 <div class="setting-item">
                                    <div class="setting-label">Add Approval User</div>
                                    <div class="setting-description">Configure users who can approve requisitions and their amount limits</div>
                                    <div class="form-group">
                                       <div class="row">
                                          <div class="col-md-4">
                                             <label>Select User</label>
                                             <select class="form-control" id="approval_user_select">
                                                <option value="">Select User</option>
                                                <?php foreach($users as $user): ?>
                                                   <option value="<?=$user->id?>"><?=$user->username?> (<?=$user->first_name?> <?=$user->last_name?>)</option>
                                                <?php endforeach; ?>
                                             </select>
                                          </div>
                                          <div class="col-md-3">
                                             <label>Min Amount <small class="text-muted">(0 = no minimum)</small></label>
                                             <input type="number" class="form-control" id="min_amount" step="0.01" min="0" placeholder="0.00" value="0">
                                          </div>
                                          <div class="col-md-3">
                                             <label>Max Amount <small class="text-muted">(0 = unlimited)</small></label>
                                             <input type="number" class="form-control" id="max_amount" step="0.01" min="0" placeholder="0.00" value="0">
                                          </div>
                                          <div class="col-md-2">
                                             <label>&nbsp;</label>
                                             <button type="button" class="btn btn-primary btn-block" onclick="addApprovalUser()">
                                                <i class="fa fa-plus"></i> Add User
                                             </button>
                                          </div>
                                       </div>
                                       <div class="row" style="margin-top: 10px;">
                                          <div class="col-md-12">
                                             <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-sm btn-default" onclick="setUnlimitedApproval()">
                                                   <i class="fa fa-infinity"></i> Set Unlimited Approval
                                                </button>
                                                <button type="button" class="btn btn-sm btn-default" onclick="setLimitedApproval()">
                                                   <i class="fa fa-lock"></i> Set Limited Approval
                                                </button>
                                                <button type="button" class="btn btn-sm btn-default" onclick="clearApprovalForm()">
                                                   <i class="fa fa-refresh"></i> Clear Form
                                                </button>
                                             </div>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 
                                 <div class="setting-item">
                                    <div class="setting-label">Current Approval Users</div>
                                    <div class="setting-description">Users currently configured for approval with their amount ranges</div>
                                    <div class="table-responsive">
                                       <table class="table table-striped" id="approval-users-table">
                                          <thead>
                                             <tr>
                                                <th>User</th>
                                                <th>Min Amount</th>
                                                <th>Max Amount</th>
                                                <th>Approval Type</th>
                                                <th>Actions</th>
                                             </tr>
                                          </thead>
                                          <tbody>
                                             <!-- Approval users will be loaded here via AJAX -->
                                          </tbody>
                                       </table>
                                    </div>
                                 </div>
                              </div>
                           </form>
                        </div>
                        
                        <div class="box-footer">
                           <div class="row">
                              <div class="col-md-12 text-center">
                                 <button type="button" class="btn btn-warning" onclick="resetToDefault()">
                                    <i class="fa fa-refresh"></i> Reset to Default
                                 </button>
                                 <button type="button" class="btn btn-success" onclick="saveAllSettings()">
                                    <i class="fa fa-save"></i> Save All Settings
                                 </button>
                                 <a href="<?=base_url('dashboard')?>" 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>

      <!-- TABLES JS CODE -->
      <?php include"comman/code_js.php"; ?>

      <script>
      $(document).ready(function() {
          // Initialize tooltips
          $('[data-toggle="tooltip"]').tooltip();
          
          // Load approval users on page load
          loadApprovalUsers();
          
          // Validate JSON input
          $('.json-editor').on('blur', function() {
              var value = $(this).val();
              try {
                  JSON.parse(value);
                  $(this).removeClass('error');
              } catch (e) {
                  $(this).addClass('error');
                  alert('Invalid JSON format. Please check your input.');
              }
          });
      });

      function saveAllSettings() {
          var formData = $('#settings-form').serialize();
          
          $.ajax({
              url: base_url + 'pro_settings/save_settings',
              type: 'POST',
              data: formData,
              dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      showNotification('success', response.message);
                      setTimeout(function() {
                          location.reload();
                      }, 1500);
                  } else {
                      showNotification('error', response.message);
                  }
              },
              error: function() {
                  showNotification('error', 'Error saving settings');
              }
          });
      }

      function resetToDefault() {
          if (confirm('Are you sure you want to reset all settings to default values? This action cannot be undone.')) {
              $.ajax({
                  url: base_url + 'pro_settings/reset_to_default',
                  type: 'POST',
                  dataType: 'json',
                  success: function(response) {
                      if (response.success) {
                          showNotification('success', response.message);
                          setTimeout(function() {
                              location.reload();
                          }, 1500);
                      } else {
                          showNotification('error', response.message);
                      }
                  },
                  error: function() {
                      showNotification('error', 'Error resetting settings');
                  }
              });
          }
      }

      function testNotification(type) {
          $.ajax({
              url: base_url + 'pro_settings/test_notifications',
              type: 'POST',
              data: { notification_type: type },
              dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      showNotification('success', response.message);
                  } else {
                      showNotification('error', response.message);
                  }
              },
              error: function() {
                  showNotification('error', 'Error testing notification');
              }
          });
      }

      function showNotification(type, message) {
          // Use toastr if available, otherwise use alert
          if (typeof toastr !== 'undefined') {
              toastr[type](message);
          } else {
              alert(message);
          }
      }

      function loadApprovalUsers() {
          $.ajax({
              url: base_url + 'pro_settings/get_approval_users',
              type: 'GET',
              dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      var tbody = $('#approval-users-table tbody');
                      tbody.empty();
                      
                      if (response.data.length > 0) {
                          $.each(response.data, function(index, user) {
                              var approvalType = getApprovalType(user.min_amount, user.max_amount);
                              var typeBadge = getApprovalTypeBadge(approvalType);
                              
                              var row = '<tr>' +
                                  '<td>' + user.username + ' (' + user.first_name + ' ' + user.last_name + ')</td>' +
                                  '<td>' + formatAmount(user.min_amount) + '</td>' +
                                  '<td>' + formatAmount(user.max_amount) + '</td>' +
                                  '<td>' + typeBadge + '</td>' +
                                  '<td>' +
                                      '<button type="button" class="btn btn-danger btn-xs" onclick="removeApprovalUser(' + user.id + ')">' +
                                          '<i class="fa fa-trash"></i> Remove' +
                                      '</button>' +
                                  '</td>' +
                              '</tr>';
                              tbody.append(row);
                          });
                      } else {
                          tbody.append('<tr><td colspan="5" class="text-center text-muted">No approval users configured</td></tr>');
                      }
                  }
              },
              error: function() {
                  $('#approval-users-table tbody').html('<tr><td colspan="5" class="text-center text-danger">Error loading approval users</td></tr>');
              }
          });
      }

      function getApprovalType(minAmount, maxAmount) {
          if (parseFloat(minAmount) == 0 && parseFloat(maxAmount) == 0) {
              return 'unlimited';
          } else if (parseFloat(maxAmount) == 0) {
              return 'minimum';
          } else if (parseFloat(minAmount) == 0) {
              return 'maximum';
          } else {
              return 'range';
          }
      }

      function getApprovalTypeBadge(type) {
          switch(type) {
              case 'unlimited':
                  return '<span class="label label-success"><i class="fa fa-infinity"></i> Unlimited</span>';
              case 'minimum':
                  return '<span class="label label-info"><i class="fa fa-arrow-up"></i> Minimum Only</span>';
              case 'maximum':
                  return '<span class="label label-warning"><i class="fa fa-arrow-down"></i> Maximum Only</span>';
              case 'range':
                  return '<span class="label label-primary"><i class="fa fa-exchange"></i> Range</span>';
              default:
                  return '<span class="label label-default">Unknown</span>';
          }
      }

      function formatAmount(amount) {
          if (parseFloat(amount) == 0) {
              return '<span class="text-muted">No Limit</span>';
          }
          return parseFloat(amount).toFixed(2);
      }

      function addApprovalUser() {
          var userId = $('#approval_user_select').val();
          var minAmount = $('#min_amount').val();
          var maxAmount = $('#max_amount').val();
          
          if (!userId) {
              showNotification('error', 'Please select a user');
              return;
          }
          
          if (minAmount === '' || minAmount < 0) {
              showNotification('error', 'Please enter a valid minimum amount (0 or greater)');
              return;
          }
          
          if (maxAmount === '' || maxAmount < 0) {
              showNotification('error', 'Please enter a valid maximum amount (0 or greater)');
              return;
          }
          
          // Special case: both 0 means unlimited approval
          if (parseFloat(minAmount) == 0 && parseFloat(maxAmount) == 0) {
              // This is unlimited approval - no validation needed
          } else if (parseFloat(minAmount) > parseFloat(maxAmount) && parseFloat(maxAmount) != 0) {
              showNotification('error', 'Minimum amount cannot be greater than maximum amount');
              return;
          }
          
          $.ajax({
              url: base_url + 'pro_settings/add_approval_user',
              type: 'POST',
              data: {
                  user_id: userId,
                  min_amount: minAmount,
                  max_amount: maxAmount,
                  '<?php echo $this->security->get_csrf_token_name();?>': '<?php echo $this->security->get_csrf_hash();?>'
              },
              dataType: 'json',
              success: function(response) {
                  if (response.success) {
                      showNotification('success', response.message);
                      $('#approval_user_select').val('');
                      $('#min_amount').val('0');
                      $('#max_amount').val('0');
                      loadApprovalUsers();
                  } else {
                      showNotification('error', response.message);
                  }
              },
              error: function() {
                  showNotification('error', 'Error adding approval user');
              }
          });
      }

      function removeApprovalUser(approvalUserId) {
          if (confirm('Are you sure you want to remove this approval user?')) {
              $.ajax({
                  url: base_url + 'pro_settings/remove_approval_user',
                  type: 'POST',
                  data: {
                      user_id: approvalUserId, // This is the approval user record ID
                      '<?php echo $this->security->get_csrf_token_name();?>': '<?php echo $this->security->get_csrf_hash();?>'
                  },
                  dataType: 'json',
                  success: function(response) {
                      if (response.success) {
                          showNotification('success', response.message);
                          loadApprovalUsers();
                      } else {
                          showNotification('error', response.message);
                      }
                  },
                  error: function() {
                      showNotification('error', 'Error removing approval user');
                  }
              });
          }
      }

      function setUnlimitedApproval() {
          $('#min_amount').val('0');
          $('#max_amount').val('0');
          
          // Check if a user is selected
          var userId = $('#approval_user_select').val();
          if (!userId) {
              showNotification('info', 'Please select a user first, then click "Set Unlimited Approval"');
              return;
          }
          
          // Automatically add the user with unlimited approval
          addApprovalUser();
      }

      function setLimitedApproval() {
          $('#min_amount').val('100');
          $('#max_amount').val('5000');
          
          // Check if a user is selected
          var userId = $('#approval_user_select').val();
          if (!userId) {
              showNotification('info', 'Please select a user first, then click "Set Limited Approval"');
              return;
          }
          
          // Automatically add the user with limited approval
          addApprovalUser();
      }

      function clearApprovalForm() {
          $('#approval_user_select').val('');
          $('#min_amount').val('0');
          $('#max_amount').val('0');
          showNotification('info', 'Form cleared');
      }
      </script>

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