<?php include 'db_connect.php'; ?>

<div class="container-fluid">
  <div class="modern-card">
    <div class="card-header">
      <h3 class="card-title">
        <i class="fas fa-layer-group mr-2"></i>
        Batch Management
      </h3>
      <div class="d-flex gap-2">
        <select id="filter_status" class="form-control" style="width: 150px;">
          <option value="">All Status</option>
          <option value="active">Active</option>
          <option value="depleted">Depleted</option>
          <option value="expired">Expired</option>
        </select>
        <select id="filter_product" class="form-control select2" style="width: 200px;">
          <option value="">All Products</option>
          <?php
          $products = $conn->query("SELECT * FROM product_list ORDER BY name ASC");
          while($prod = $products->fetch_assoc()):
          ?>
          <option value="<?php echo $prod['id']; ?>"><?php echo htmlspecialchars($prod['name']); ?></option>
          <?php endwhile; ?>
        </select>
      </div>
    </div>
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-hover" id="batch-table">
          <thead>
            <tr>
              <th>Batch No.</th>
              <th>Product</th>
              <th>Received</th>
              <th>Sold</th>
              <th>Expired</th>
              <th>Available</th>
              <th>Expiry Date</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $batches = $conn->query("SELECT b.*, p.name as product_name, p.sku,
              (b.quantity_received - b.quantity_sold - b.quantity_expired) as available_qty
              FROM batch_list b
              INNER JOIN product_list p ON p.id = b.product_id
              ORDER BY b.expiry_date ASC");

            if($batches && $batches->num_rows > 0):
              while($row = $batches->fetch_assoc()):
                $status_class = 'badge-success';
                $status_text = 'Active';

                if($row['status'] == 'depleted'){
                  $status_class = 'badge-secondary';
                  $status_text = 'Depleted';
                } elseif($row['status'] == 'expired' || strtotime($row['expiry_date']) <= strtotime('today')){
                  $status_class = 'badge-danger';
                  $status_text = 'Expired';
                } elseif(strtotime($row['expiry_date']) <= strtotime('+30 days')){
                  $status_class = 'badge-warning';
                  $status_text = 'Expiring Soon';
                }

                $available = $row['available_qty'];
            ?>
            <tr data-status="<?php echo $row['status']; ?>" data-product="<?php echo $row['product_id']; ?>">
              <td>
                <strong><?php echo htmlspecialchars($row['batch_number']); ?></strong>
              </td>
              <td>
                <?php echo htmlspecialchars($row['product_name']); ?>
                <br><small class="text-muted">SKU: <?php echo htmlspecialchars($row['sku']); ?></small>
              </td>
              <td class="text-center">
                <span class="badge badge-primary"><?php echo number_format($row['quantity_received']); ?></span>
              </td>
              <td class="text-center">
                <span class="badge badge-info"><?php echo number_format($row['quantity_sold']); ?></span>
              </td>
              <td class="text-center">
                <span class="badge badge-danger"><?php echo number_format($row['quantity_expired']); ?></span>
              </td>
              <td class="text-center">
                <span class="badge <?php echo $available > 0 ? 'badge-success' : 'badge-secondary'; ?>">
                  <?php echo number_format($available); ?>
                </span>
              </td>
              <td>
                <?php echo date('M d, Y', strtotime($row['expiry_date'])); ?>
                <?php if(strtotime($row['expiry_date']) <= strtotime('today')): ?>
                <br><small class="text-danger"><i class="fas fa-exclamation-triangle"></i> Expired!</small>
                <?php elseif(strtotime($row['expiry_date']) <= strtotime('+30 days')): ?>
                <br><small class="text-warning"><i class="fas fa-clock"></i> <?php echo ceil((strtotime($row['expiry_date']) - time()) / 86400); ?> days left</small>
                <?php endif; ?>
              </td>
              <td>
                <span class="badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
              </td>
              <td>
                <button class="btn btn-sm btn-info" onclick="viewBatchHistory(<?php echo $row['id']; ?>)">
                  <i class="fas fa-history"></i>
                </button>
                <?php if($row['status'] == 'active' && $available > 0 && strtotime($row['expiry_date']) <= strtotime('today')): ?>
                <button class="btn btn-sm btn-warning" onclick="markExpired(<?php echo $row['id']; ?>, <?php echo $available; ?>)">
                  <i class="fas fa-exclamation-circle"></i> Mark Expired
                </button>
                <?php endif; ?>
              </td>
            </tr>
            <?php
              endwhile;
            else:
            ?>
            <tr>
              <td colspan="9" class="text-center py-4 text-muted">
                <i class="fas fa-box-open fa-3x mb-3 d-block"></i>
                No batches found. Start by receiving products.
              </td>
            </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- Batch History Modal -->
<div class="modal fade" id="batchHistoryModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-history mr-2"></i>Batch History</h5>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body" id="batchHistoryContent">
        Loading...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<style>
  #batch-table th {
    background: var(--gray-100);
    font-size: 0.8rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
  }
  #batch-table td {
    vertical-align: middle;
  }
  .badge {
    font-size: 0.8rem;
    padding: 0.4em 0.8em;
  }
</style>

<script>
  $(document).ready(function(){
    // Initialize DataTable
    var table = $('#batch-table').DataTable({
      "order": [[6, "asc"]], // Sort by expiry date
      "pageLength": 25
    });

    // Filter by status
    $('#filter_status').change(function(){
      var status = $(this).val();
      if(status){
        table.column(7).search(status).draw();
      } else {
        table.column(7).search('').draw();
      }
    });

    // Filter by product
    $('#filter_product').change(function(){
      var product = $(this).val();
      if(product){
        table.rows().every(function(){
          var row = this.node();
          if($(row).data('product') == product){
            $(row).show();
          } else {
            $(row).hide();
          }
        });
      } else {
        table.rows().every(function(){
          $(this.node()).show();
        });
      }
    });

    $('.select2').select2({
      placeholder: "Select...",
      allowClear: true
    });
  });

  function viewBatchHistory(batchId){
    $('#batchHistoryContent').html('<div class="text-center py-4"><i class="fas fa-spinner fa-spin fa-2x"></i></div>');
    $('#batchHistoryModal').modal('show');

    $.ajax({
      url: 'get_batch_history.php',
      data: { batch_id: batchId },
      success: function(resp){
        $('#batchHistoryContent').html(resp);
      },
      error: function(){
        $('#batchHistoryContent').html('<div class="alert alert-danger">Error loading history</div>');
      }
    });
  }

  function markExpired(batchId, qty){
    if(confirm('Are you sure you want to mark ' + qty + ' units as expired?')){
      start_load();
      $.ajax({
        url: 'ajax.php?action=mark_batch_expired',
        method: 'POST',
        data: { batch_id: batchId, qty: qty },
        success: function(resp){
          if(resp == 1){
            alert_toast('Batch marked as expired', 'success');
            setTimeout(function(){
              location.reload();
            }, 1000);
          } else {
            alert_toast('Error marking batch as expired', 'danger');
            end_load();
          }
        }
      });
    }
  }
</script>
