<?php
// ajax/get_batches.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../../assets/db_connect.php';

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if product_id is provided
$product_id = $_GET['product_id'] ?? 0;

if ($product_id <= 0) {
    echo '<div class="alert alert-danger">Invalid product ID</div>';
    exit;
}

// Get product details
$stmt_product = $pdo->prepare("SELECT id, name, sku FROM products WHERE id = ?");
$stmt_product->execute([$product_id]);
$product = $stmt_product->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    echo '<div class="alert alert-danger">Product not found</div>';
    exit;
}

// Get all batches for this product using the batch_stock_view
$sql = "SELECT 
            bs.batch_id,
            bs.product_id,
            bs.batch_no,
            bs.current_qty,
            bs.expiry_date,
            bs.cost_price,
            bs.sell_price,
            bs.shop_id,
            bs.is_active,
            pb.supplier_id,
            pb.created_by,
            pb.created_at,
            pb.updated_at,
            s.name as supplier_name,
            u.username as created_by_user,
            DATEDIFF(bs.expiry_date, CURDATE()) as days_to_expiry
        FROM batch_stock_view bs
        LEFT JOIN product_batches pb ON bs.batch_id = pb.id
        LEFT JOIN suppliers s ON pb.supplier_id = s.id
        LEFT JOIN users u ON pb.created_by = u.id
        WHERE bs.product_id = ? 
        ORDER BY 
            bs.is_active DESC,
            bs.expiry_date ASC,
            pb.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute([$product_id]);
$batches = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid p-0">
    <!-- Product Header -->
    <div class="card bg-light mb-3">
        <div class="card-body">
            <div class="row">
                <div class="col-md-8">
                    <h5 class="card-title mb-1">
                        <i class="fas fa-boxes text-primary"></i> 
                        <?= htmlspecialchars($product['name']) ?>
                    </h5>
                    <p class="card-text mb-0">
                        <small class="text-muted">
                            SKU: <strong><?= htmlspecialchars($product['sku'] ?? 'N/A') ?></strong> | 
                            Product ID: <strong>#<?= $product['id'] ?></strong>
                        </small>
                    </p>
                </div>
                <div class="col-md-4 text-right">
                    <a href="add_purchase.php?product_id=<?= $product_id ?>" 
                       class="btn btn-success btn-sm">
                        <i class="fas fa-plus"></i> Add New Batch
                    </a>
                    <button class="btn btn-secondary btn-sm" onclick="$('#batchModal').modal('hide')">
                        <i class="fas fa-times"></i> Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php if (empty($batches)): ?>
    <div class="alert alert-info">
        <div class="text-center py-3">
            <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
            <h5>No Batches Found</h5>
            <p class="mb-3">This product doesn't have any batches yet.</p>
            <a href="add_purchase.php?product_id=<?= $product_id ?>" class="btn btn-primary">
                <i class="fas fa-plus-circle"></i> Create First Batch
            </a>
        </div>
    </div>
    <?php else: ?>
    
    <!-- Summary Cards -->
    <div class="row mb-3">
        <?php
        $total_qty = 0;
        $total_value = 0;
        $active_batches = 0;
        $expired_batches = 0;
        $expiring_soon = 0;
        $inactive_batches = 0;
        
        foreach ($batches as $batch) {
            $current_qty = $batch['current_qty'] ?? 0;
            $batch_value = $current_qty * $batch['cost_price'];
            $total_qty += $current_qty;
            $total_value += $batch_value;
            
            if ($batch['is_active'] == 1) {
                $active_batches++;
                
                if ($batch['days_to_expiry'] < 0) {
                    $expired_batches++;
                } elseif ($batch['days_to_expiry'] <= 30) {
                    $expiring_soon++;
                }
            } else {
                $inactive_batches++;
            }
        }
        ?>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="card border-primary">
                <div class="card-body p-3 text-center">
                    <h6 class="card-title text-muted mb-1">Total Batches</h6>
                    <h3 class="mb-0 text-primary"><?= count($batches) ?></h3>
                </div>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="card border-success">
                <div class="card-body p-3 text-center">
                    <h6 class="card-title text-muted mb-1">Active</h6>
                    <h3 class="mb-0 text-success"><?= $active_batches ?></h3>
                </div>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="card border-secondary">
                <div class="card-body p-3 text-center">
                    <h6 class="card-title text-muted mb-1">Inactive</h6>
                    <h3 class="mb-0 text-secondary"><?= $inactive_batches ?></h3>
                </div>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="card <?= $expired_batches > 0 ? 'border-danger' : 'border-secondary' ?>">
                <div class="card-body p-3 text-center">
                    <h6 class="card-title text-muted mb-1">Expired</h6>
                    <h3 class="mb-0 <?= $expired_batches > 0 ? 'text-danger' : 'text-secondary' ?>"><?= $expired_batches ?></h3>
                </div>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="card <?= $expiring_soon > 0 ? 'border-warning' : 'border-secondary' ?>">
                <div class="card-body p-3 text-center">
                    <h6 class="card-title text-muted mb-1">Expiring Soon</h6>
                    <h3 class="mb-0 <?= $expiring_soon > 0 ? 'text-warning' : 'text-secondary' ?>"><?= $expiring_soon ?></h3>
                </div>
            </div>
        </div>
        
        <div class="col-xl-2 col-md-4 col-sm-6 mb-3">
            <div class="card border-info">
                <div class="card-body p-3 text-center">
                    <h6 class="card-title text-muted mb-1">Total Value</h6>
                    <h3 class="mb-0 text-info"><?= number_format($total_value, 2) ?></h3>
                </div>
            </div>
        </div>
    </div>

    <!-- Batch Filters -->
    <div class="card mb-3">
        <div class="card-body p-2">
            <div class="btn-group btn-group-sm" role="group">
                <button type="button" class="btn btn-outline-primary active batch-filter" data-filter="all">
                    All (<?= count($batches) ?>)
                </button>
                <button type="button" class="btn btn-outline-success batch-filter" data-filter="active">
                    Active (<?= $active_batches ?>)
                </button>
                <button type="button" class="btn btn-outline-secondary batch-filter" data-filter="inactive">
                    Inactive (<?= $inactive_batches ?>)
                </button>
                <button type="button" class="btn btn-outline-danger batch-filter" data-filter="expired">
                    Expired (<?= $expired_batches ?>)
                </button>
                <button type="button" class="btn btn-outline-warning batch-filter" data-filter="expiring">
                    Expiring Soon (<?= $expiring_soon ?>)
                </button>
            </div>
        </div>
    </div>

    <!-- Batches Table -->
    <div class="table-responsive">
        <table class="table table-sm table-bordered table-hover mb-0" id="batchesTable">
            <thead class="thead-dark">
                <tr>
                    <th width="80">Status</th>
                    <th width="100">Batch No</th>
                    <th width="80" class="text-right">Quantity</th>
                    <th width="100" class="text-right">Cost Price</th>
                    <th width="100" class="text-right">Sell Price</th>
                    <th width="120">Expiry Date</th>
                    <th width="120">Supplier</th>
                    <th width="100">Created</th>
                    <th width="100" class="text-right">Value</th>
                    <th width="140" class="text-center">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($batches as $batch): 
                    $current_qty = $batch['current_qty'] ?? 0;
                    $batch_value = $current_qty * $batch['cost_price'];
                    $is_active = $batch['is_active'] == 1;
                    $days_to_expiry = $batch['days_to_expiry'];
                    
                    // Determine status
                    if (!$is_active) {
                        $status_class = 'secondary';
                        $status_text = 'Inactive';
                        $status_icon = 'ban';
                        $row_class = 'table-secondary';
                        $filter_class = 'inactive';
                    } elseif ($days_to_expiry < 0) {
                        $status_class = 'danger';
                        $status_text = 'Expired';
                        $status_icon = 'skull-crossbones';
                        $row_class = 'table-danger';
                        $filter_class = 'expired';
                    } elseif ($days_to_expiry <= 30) {
                        $status_class = 'warning';
                        $status_text = 'Expiring Soon';
                        $status_icon = 'exclamation-triangle';
                        $row_class = 'table-warning';
                        $filter_class = 'expiring';
                    } elseif ($current_qty <= 0) {
                        $status_class = 'light';
                        $status_text = 'Empty';
                        $status_icon = 'box-open';
                        $row_class = 'table-light';
                        $filter_class = 'active';
                    } else {
                        $status_class = 'success';
                        $status_text = 'Active';
                        $status_icon = 'check-circle';
                        $row_class = '';
                        $filter_class = 'active';
                    }
                ?>
                <tr class="<?= $row_class ?> batch-row" data-status="<?= $filter_class ?>" data-active="<?= $is_active ?>">
                    <td>
                        <span class="badge badge-<?= $status_class ?> p-2 d-block text-center">
                            <i class="fas fa-<?= $status_icon ?>"></i>
                            <br>
                            <small><?= $status_text ?></small>
                        </span>
                    </td>
                    <td>
                        <strong class="font-monospace"><?= htmlspecialchars($batch['batch_no']) ?></strong>
                        <?php if(!$is_active): ?>
                        <br><small class="text-muted"><i>Inactive</i></small>
                        <?php endif; ?>
                    </td>
                    <td class="text-right">
                        <span class="<?= $current_qty <= 0 ? 'text-muted' : 'font-weight-bold' ?>">
                            <?= number_format($current_qty) ?>
                        </span>
                    </td>
                    <td class="text-right">
                        <?= number_format($batch['cost_price'], 2) ?>
                    </td>
                    <td class="text-right">
                        <?= number_format($batch['sell_price'], 2) ?>
                    </td>
                    <td>
                        <div class="d-flex flex-column">
                            <span><?= date('d-M-Y', strtotime($batch['expiry_date'])) ?></span>
                            <small class="<?= $days_to_expiry < 0 ? 'text-danger' : ($days_to_expiry <= 30 ? 'text-warning' : 'text-muted') ?>">
                                <?php if($days_to_expiry < 0): ?>
                                    Expired <?= abs($days_to_expiry) ?> days ago
                                <?php else: ?>
                                    <?= $days_to_expiry ?> days left
                                <?php endif; ?>
                            </small>
                        </div>
                    </td>
                    <td>
                        <?= htmlspecialchars($batch['supplier_name'] ?? 'N/A') ?>
                    </td>
                    <td>
                        <?= date('d-M-y', strtotime($batch['created_at'])) ?>
                        <br><small class="text-muted">by <?= htmlspecialchars($batch['created_by_user'] ?? 'System') ?></small>
                    </td>
                    <td class="text-right font-weight-bold">
                        <?= number_format($batch_value, 2) ?>
                    </td>
                    <td class="text-center">
                        <div class="btn-group btn-group-sm" role="group">
                            <!-- Active Batch Actions -->
                            <?php if ($is_active): ?>
                                <?php if ($current_qty > 0): ?>
                                <button class="btn btn-outline-primary btn-sm adjust-stock-btn" 
                                        data-batch-id="<?= $batch['batch_id'] ?>"
                                        data-batch-no="<?= htmlspecialchars($batch['batch_no']) ?>"
                                        data-current-qty="<?= $current_qty ?>"
                                        title="Adjust Stock">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <?php endif; ?>
                                
                                <button class="btn btn-outline-info btn-sm view-history-btn" 
                                        data-batch-id="<?= $batch['batch_id'] ?>"
                                        data-batch-no="<?= htmlspecialchars($batch['batch_no']) ?>"
                                        title="View History">
                                    <i class="fas fa-history"></i>
                                </button>
                                
                                <button class="btn btn-outline-danger btn-sm deactivate-batch-btn" 
                                        data-batch-id="<?= $batch['batch_id'] ?>"
                                        data-batch-no="<?= htmlspecialchars($batch['batch_no']) ?>"
                                        title="Deactivate Batch">
                                    <i class="fas fa-ban"></i>
                                </button>
                            
                            <!-- Inactive Batch Actions -->
                            <?php else: ?>
                                <button class="btn btn-outline-success btn-sm restore-batch-btn" 
                                        data-batch-id="<?= $batch['batch_id'] ?>"
                                        data-batch-no="<?= htmlspecialchars($batch['batch_no']) ?>"
                                        title="Restore Batch">
                                    <i class="fas fa-check"></i>
                                </button>
                                
                                <button class="btn btn-outline-info btn-sm view-history-btn" 
                                        data-batch-id="<?= $batch['batch_id'] ?>"
                                        data-batch-no="<?= htmlspecialchars($batch['batch_no']) ?>"
                                        title="View History">
                                    <i class="fas fa-history"></i>
                                </button>
                                
                                <button class="btn btn-outline-danger btn-sm delete-batch-btn" 
                                        data-batch-id="<?= $batch['batch_id'] ?>"
                                        data-batch-no="<?= htmlspecialchars($batch['batch_no']) ?>"
                                        data-has-stock="<?= $current_qty > 0 ? '1' : '0' ?>"
                                        title="Delete Batch">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot class="table-secondary">
                <tr>
                    <td colspan="2" class="text-right"><strong>Totals:</strong></td>
                    <td class="text-right"><strong><?= number_format($total_qty) ?></strong></td>
                    <td colspan="4"></td>
                    <td><strong>Total Value:</strong></td>
                    <td class="text-right"><strong><?= number_format($total_value, 2) ?></strong></td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>
    
    <!-- Batch Actions Footer -->
    <div class="card mt-3">
        <div class="card-body p-3">
            <div class="row">
                <div class="col-md-6">
                    <small class="text-muted">
                        <i class="fas fa-info-circle"></i> 
                        Showing <?= count($batches) ?> batch(es) for this product.
                    </small>
                </div>
                <div class="col-md-6 text-right">
                    <button class="btn btn-outline-secondary btn-sm" onclick="printBatches()">
                        <i class="fas fa-print"></i> Print
                    </button>
                    <button class="btn btn-outline-secondary btn-sm" onclick="exportBatches(<?= $product_id ?>)">
                        <i class="fas fa-download"></i> Export
                    </button>
                    <button class="btn btn-outline-primary btn-sm" onclick="refreshBatchList()">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <?php endif; ?>
</div>

<!-- JavaScript Functions -->
<script>
$(document).ready(function() {
    console.log("✅ Batch modal loaded");
    
    // Initialize tooltips
    $('[title]').tooltip();
    
    // Batch filter buttons
    $('.batch-filter').click(function() {
        const filter = $(this).data('filter');
        
        // Update active button
        $('.batch-filter').removeClass('active');
        $(this).addClass('active');
        
        // Show/hide rows
        if (filter === 'all') {
            $('.batch-row').show();
        } else if (filter === 'active') {
            $('.batch-row').hide();
            $('.batch-row[data-active="1"]').show();
        } else if (filter === 'inactive') {
            $('.batch-row').hide();
            $('.batch-row[data-active="0"]').show();
        } else if (filter === 'expired') {
            $('.batch-row').hide();
            $('.batch-row[data-status="expired"]').show();
        } else if (filter === 'expiring') {
            $('.batch-row').hide();
            $('.batch-row[data-status="expiring"]').show();
        }
    });
    
    // Adjust Stock button
    $(document).on('click', '.adjust-stock-btn', function() {
        const batchId = $(this).data('batch-id');
        const batchNo = $(this).data('batch-no');
        const currentQty = $(this).data('current-qty');
        
        Swal.fire({
            title: 'Adjust Stock',
            html: `
                <div class="text-left">
                    <div class="form-group">
                        <label>Batch: <strong>${batchNo}</strong></label>
                        <div class="small text-muted">Current Quantity: ${currentQty}</div>
                    </div>
                    <div class="form-group">
                        <label>Adjustment Type:</label>
                        <select id="adjustmentType" class="form-control">
                            <option value="ADD">Add Stock</option>
                            <option value="REMOVE">Remove Stock</option>
                            <option value="SET">Set Exact Quantity</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Quantity:</label>
                        <input type="number" id="adjustmentQty" class="form-control" min="1" value="1" step="1">
                    </div>
                    <div class="form-group">
                        <label>Reason for Adjustment:</label>
                        <textarea id="adjustmentReason" class="form-control" rows="3" 
                                  placeholder="Enter reason for adjustment (required)"></textarea>
                        <small class="text-muted">Examples: Physical count, damage found, return from customer, etc.</small>
                    </div>
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: 'Save Adjustment',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#28a745',
            preConfirm: () => {
                const qty = document.getElementById('adjustmentQty').value;
                const reason = document.getElementById('adjustmentReason').value;
                
                if (!qty || qty <= 0) {
                    Swal.showValidationMessage('Please enter a valid quantity');
                    return false;
                }
                if (!reason.trim()) {
                    Swal.showValidationMessage('Please enter a reason for this adjustment');
                    return false;
                }
                return { qty: qty, reason: reason };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Show loading
                Swal.fire({
                    title: 'Processing...',
                    text: 'Saving adjustment',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                // AJAX call to save adjustment
                $.ajax({
                    url: 'ajax/adjust_stock.php',
                    type: 'POST',
                    data: {
                        batch_id: batchId,
                        adjustment_type: $('#adjustmentType').val(),
                        quantity: result.value.qty,
                        reason: result.value.reason
                    },
                    dataType: 'json',
                    success: function(response) {
                        Swal.close();
                        if (response.status === 'success') {
                            Swal.fire({
                                title: 'Success!',
                                text: response.message,
                                icon: 'success',
                                timer: 2000,
                                showConfirmButton: false
                            }).then(() => {
                                // Reload the batch details
                                reloadBatchDetails();
                            });
                        } else {
                            Swal.fire({
                                title: 'Error!',
                                text: response.message,
                                icon: 'error'
                            });
                        }
                    },
                    error: function() {
                        Swal.close();
                        Swal.fire({
                            title: 'Error!',
                            text: 'Failed to save adjustment. Please try again.',
                            icon: 'error'
                        });
                    }
                });
            }
        });
    });
    
    // View History button
    $(document).on('click', '.view-history-btn', function() {
        const batchId = $(this).data('batch-id');
        const batchNo = $(this).data('batch-no');
        
        Swal.fire({
            title: 'Batch History',
            html: `<div class="text-center py-3">
                      <div class="spinner-border text-primary" role="status">
                          <span class="sr-only">Loading...</span>
                      </div>
                      <p class="mt-2">Loading history for batch ${batchNo}...</p>
                   </div>`,
            showConfirmButton: false,
            showCloseButton: true,
            didOpen: () => {
                // Load history via AJAX
                $.ajax({
                    url: 'ajax/get_batch_history.php',
                    type: 'GET',
                    data: { batch_id: batchId },
                    success: function(response) {
                        Swal.getHtmlContainer().innerHTML = response;
                    },
                    error: function() {
                        Swal.getHtmlContainer().innerHTML = `
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle"></i>
                                Failed to load batch history.
                            </div>
                        `;
                    }
                });
            }
        });
    });
    
    // Deactivate batch button
    $(document).on('click', '.deactivate-batch-btn', function() {
        const batchId = $(this).data('batch-id');
        const batchNo = $(this).data('batch-no');
        
        Swal.fire({
            title: 'Deactivate Batch',
            html: `Are you sure you want to deactivate batch <strong>${batchNo}</strong>?<br>
                   <small class="text-muted">Deactivated batches won't appear in sales but remain in records.</small>`,
            icon: 'warning',
            input: 'text',
            inputLabel: 'Reason for deactivation (Optional)',
            inputPlaceholder: 'Enter reason...',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Deactivate',
            cancelButtonText: 'Cancel',
            showLoaderOnConfirm: true,
            preConfirm: (reason) => {
                return $.ajax({
                    url: 'ajax/deactivate_batch.php',
                    type: 'POST',
                    data: {
                        batch_id: batchId,
                        reason: reason || ''
                    },
                    dataType: 'json'
                }).then(response => {
                    if (!response.status) {
                        throw new Error(response.message || 'Unknown error');
                    }
                    return response;
                }).catch(error => {
                    Swal.showValidationMessage(`Request failed: ${error.message}`);
                });
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
            if (result.isConfirmed) {
                const response = result.value;
                
                if (response.status === 'success') {
                    Swal.fire({
                        title: 'Deactivated!',
                        text: response.message,
                        icon: 'success',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        reloadBatchDetails();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message,
                        icon: 'error'
                    });
                }
            }
        });
    });
    
    // Restore batch button
    $(document).on('click', '.restore-batch-btn', function() {
        const batchId = $(this).data('batch-id');
        const batchNo = $(this).data('batch-no');
        
        Swal.fire({
            title: 'Restore Batch',
            html: `Are you sure you want to restore batch <strong>${batchNo}</strong>?`,
            icon: 'question',
            input: 'text',
            inputLabel: 'Reason for restoration (Optional)',
            inputPlaceholder: 'Enter reason...',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Restore',
            cancelButtonText: 'Cancel',
            showLoaderOnConfirm: true,
            preConfirm: (reason) => {
                return $.ajax({
                    url: 'ajax/restore_batch.php',
                    type: 'POST',
                    data: {
                        batch_id: batchId,
                        reason: reason || ''
                    },
                    dataType: 'json'
                }).then(response => {
                    if (!response.status) {
                        throw new Error(response.message || 'Unknown error');
                    }
                    return response;
                }).catch(error => {
                    Swal.showValidationMessage(`Request failed: ${error.message}`);
                });
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
            if (result.isConfirmed) {
                const response = result.value;
                
                if (response.status === 'success') {
                    Swal.fire({
                        title: 'Restored!',
                        text: response.message,
                        icon: 'success',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        reloadBatchDetails();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message,
                        icon: 'error'
                    });
                }
            }
        });
    });
    
    // Delete batch button (for inactive batches)
    $(document).on('click', '.delete-batch-btn', function() {
        const batchId = $(this).data('batch-id');
        const batchNo = $(this).data('batch-no');
        const hasStock = $(this).data('has-stock') == 1;
        
        let warningMessage = `Are you sure you want to delete batch <strong>${batchNo}</strong>?`;
        
        if (hasStock) {
            warningMessage += `<br><span class="text-danger">⚠️ Warning: This batch still has stock! Deleting it will remove the stock from inventory.</span>`;
        }
        
        Swal.fire({
            title: 'Delete Batch',
            html: warningMessage,
            icon: 'warning',
            input: 'text',
            inputLabel: 'Enter batch number to confirm',
            inputPlaceholder: `Type "${batchNo}" to confirm`,
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Delete',
            cancelButtonText: 'Cancel',
            showLoaderOnConfirm: true,
            preConfirm: (confirmation) => {
                if (confirmation !== batchNo) {
                    Swal.showValidationMessage(`Please type "${batchNo}" exactly to confirm deletion`);
                    return false;
                }
                
                return $.ajax({
                    url: 'ajax/delete_batch.php',
                    type: 'POST',
                    data: {
                        batch_id: batchId,
                        confirmation: confirmation
                    },
                    dataType: 'json'
                }).then(response => {
                    if (!response.status) {
                        throw new Error(response.message || 'Unknown error');
                    }
                    return response;
                }).catch(error => {
                    Swal.showValidationMessage(`Request failed: ${error.message}`);
                });
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
            if (result.isConfirmed) {
                const response = result.value;
                
                if (response.status === 'success') {
                    Swal.fire({
                        title: 'Deleted!',
                        text: response.message,
                        icon: 'success',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        reloadBatchDetails();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message,
                        icon: 'error'
                    });
                }
            }
        });
    });
});

// Function to reload batch details
function reloadBatchDetails() {
    const productId = <?= $product_id ?>;
    
    // Show loading
    $('#batchModalBody').html(`
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="sr-only">Loading...</span>
            </div>
            <p class="mt-2">Reloading batch details...</p>
        </div>
    `);
    
    // Reload content
    $.ajax({
        url: 'ajax/get_batches.php',
        type: 'GET',
        data: { 
            product_id: productId,
            _t: new Date().getTime()
        },
        success: function(response) {
            $('#batchModalBody').html(response);
        },
        error: function() {
            $('#batchModalBody').html(`
                <div class="alert alert-danger">
                    Failed to reload batch details. <button class="btn btn-sm btn-primary" onclick="reloadBatchDetails()">
                    Try Again
                    </button>
                </div>
            `);
        }
    });
}

function refreshBatchList() {
    reloadBatchDetails();
}

function printBatches() {
    const printContent = $('#batchModalBody').html();
    const originalContent = document.body.innerHTML;
    
    document.body.innerHTML = `
        <html>
            <head>
                <title>Batch Details - <?= htmlspecialchars($product['name']) ?></title>
                <link rel="stylesheet" href="../../libraries/bootstrap.min.css">
                <style>
                    @media print {
                        .no-print { display: none !important; }
                        body { font-size: 12px; }
                        table { font-size: 11px; }
                        .card { border: none !important; }
                    }
                    .table td, .table th { padding: 4px; }
                </style>
            </head>
            <body>
                <div class="container mt-3">
                    <h4 class="text-center mb-3">Batch Details: <?= htmlspecialchars($product['name']) ?></h4>
                    ${printContent}
                </div>
                <script>
                    window.onload = function() {
                        window.print();
                        setTimeout(function() {
                            document.body.innerHTML = originalContent;
                            location.reload();
                        }, 500);
                    };
                <\/script>
            </body>
        </html>
    `;
}

function exportBatches(productId) {
    window.open(`export_batches.php?product_id=${productId}`, '_blank');
}

// Close modal with Escape key
$(document).on('keydown', function(e) {
    if (e.key === 'Escape') {
        $('#batchModal').modal('hide');
    }
});
</script>

<style>
.table-sm td, .table-sm th {
    padding: 0.4rem;
    vertical-align: middle;
}
.badge {
    min-width: 60px;
}
.font-monospace {
    font-family: 'Courier New', monospace;
}
.btn-group-sm > .btn {
    padding: 0.2rem 0.4rem;
    font-size: 0.875rem;
}
.batch-row {
    transition: all 0.3s ease;
}
</style>