<div class="page-header">
    <div>
        <a href="<?= APP_URL ?>/settings" class="btn btn-ghost btn-sm mb-4" style="padding-left:0;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
            Back to Settings
        </a>
        <h1>Batch & Expiry Management</h1>
        <div class="page-subtitle">Manage product batch tracking and expiry monitoring</div>
    </div>
</div>

<div class="grid-2 gap-6 mb-6">
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Batch Tracking Overview</h3>
        </div>
        <div class="p-4">
            <div class="text-center mb-4">
                <div class="text-2xl font-bold text-primary"><?= count($batchProducts) ?></div>
                <div class="text-sm text-muted">Products with batch tracking enabled</div>
            </div>
            <div class="space-y-2">
                <?php foreach ($batchProducts as $product): ?>
                <div class="flex justify-between items-center p-2 border rounded">
                    <div>
                        <div class="font-medium"><?= e($product['name']) ?></div>
                        <div class="text-xs text-muted"><?= e($product['sku']) ?> - <?= $product['batch_count'] ?> batches</div>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="badge badge-success">Tracking Enabled</span>
                        <form method="POST" action="<?= APP_URL ?>/settings/update-batch-tracking" style="display:inline;">
                            <?= Security::csrfField() ?>
                            <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                            <input type="hidden" name="enable_batch_tracking" value="0">
                            <button type="submit" class="btn btn-ghost btn-xs" onclick="return confirm('Disable batch tracking for this product?')" title="Disable">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;">
                                    <path d="M10 2v20M14 2v20"></path>
                                </svg>
                            </button>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php if (empty($batchProducts)): ?>
                <div class="text-center text-muted py-4">
                    No products have batch tracking enabled yet.
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Expiry Alerts</h3>
            <span class="badge badge-warning">Next 30 Days</span>
        </div>
        <div class="p-4">
            <div class="text-center mb-4">
                <div class="text-2xl font-bold text-warning"><?= count($expiringBatches) ?></div>
                <div class="text-sm text-muted">Batches expiring soon</div>
            </div>
            <div class="space-y-2 max-h-64 overflow-y-auto">
                <?php foreach ($expiringBatches as $batch): ?>
                <div class="flex justify-between items-center p-2 border rounded <?= (strtotime($batch['expiry_date']) - strtotime(date('Y-m-d'))) <= 7 ? 'border-warning bg-warning/10' : '' ?>">
                    <div>
                        <div class="font-medium"><?= e($batch['product_name']) ?></div>
                        <div class="text-xs text-muted">
                            Batch: <?= e($batch['batch_no']) ?> - 
                            Expires: <?= e(date('M j, Y', strtotime($batch['expiry_date']))) ?>
                            <?php 
                            $daysUntilExpiry = (strtotime($batch['expiry_date']) - strtotime(date('Y-m-d'))) / 86400;
                            if ($daysUntilExpiry <= 0) {
                                echo '<span class="badge badge-danger">Expired</span>';
                            } elseif ($daysUntilExpiry <= 7) {
                                echo '<span class="badge badge-warning">' . e(floor($daysUntilExpiry)) . ' days</span>';
                            } else {
                                echo '<span class="badge badge-info">' . e(floor($daysUntilExpiry)) . ' days</span>';
                            }
                            ?>
                        </div>
                    </div>
                    <form method="POST" action="<?= APP_URL ?>/settings/delete-batch" onsubmit="return confirm('Delete this batch?')" style="display:inline;">
                        <?= Security::csrfField() ?>
                        <input type="hidden" name="batch_id" value="<?= $batch['id'] ?>">
                        <button type="submit" class="btn btn-ghost btn-icon text-danger" title="Delete Batch">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;">
                                <polyline points="3,6 5,6 21,6"></polyline>
                                <path d="m19,6v14a2,2 0 0,1 -2,2H7a2,2 0 0,1 -2,-2V6m3,0V4a2,2 0 0,1 2,-2h4a2,2 0 0,1 2,2v2"></path>
                            </svg>
                        </button>
                    </form>
                </div>
                <?php endforeach; ?>
                <?php if (empty($expiringBatches)): ?>
                <div class="text-center text-muted py-4">
                    No batches expiring in the next 30 days.
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h3 class="card-title">Products Without Batch Tracking</h3>
    </div>
    <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th>Product</th>
                    <th>SKU</th>
                    <th>Category</th>
                    <th>Current Stock</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                // Get products without batch tracking
                $stmt = db()->prepare("
                    SELECT p.*, c.name as category_name,
                           COALESCE(SUM(s.quantity), 0) as total_stock
                    FROM products p
                    LEFT JOIN categories c ON p.category_id = c.id
                    LEFT JOIN stock s ON p.id = s.product_id
                    WHERE p.tenant_id = ? AND p.batch_tracking = 0
                    GROUP BY p.id
                    ORDER BY p.name
                ");
                $stmt->execute([Auth::tenantId()]);
                $nonBatchProducts = $stmt->fetchAll();
                ?>
                <?php foreach ($nonBatchProducts as $product): ?>
                <tr>
                    <td>
                        <div class="font-medium"><?= e($product['name']) ?></div>
                    </td>
                    <td>
                        <span class="text-sm text-muted"><?= e($product['sku']) ?></span>
                    </td>
                    <td>
                        <span class="badge badge-secondary"><?= e($product['category_name'] ?? 'Uncategorized') ?></span>
                    </td>
                    <td>
                        <span class="font-medium <?= $product['total_stock'] <= ($product['alert_qty'] ?? 5) ? 'text-warning' : '' ?>">
                            <?= number_format($product['total_stock'], 2) ?>
                        </span>
                    </td>
                    <td>
                        <form method="POST" action="<?= APP_URL ?>/settings/update-batch-tracking" style="display:inline;">
                            <?= Security::csrfField() ?>
                            <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                            <input type="hidden" name="enable_batch_tracking" value="1">
                            <button type="submit" class="btn btn-primary btn-sm" onclick="return confirm('Enable batch tracking for this product?')">
                                Enable Tracking
                            </button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($nonBatchProducts)): ?>
                <tr>
                    <td colspan="5" class="text-center text-muted py-8">
                        All products have batch tracking enabled.
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="card mt-6">
    <div class="card-header">
        <h3 class="card-title">Batch Tracking Information</h3>
    </div>
    <div class="p-4">
        <div class="grid-2 gap-6">
            <div>
                <h4 class="font-medium mb-2">What is Batch Tracking?</h4>
                <p class="text-sm text-muted mb-4">
                    Batch tracking allows you to monitor products by their batch numbers, 
                    manufacturing dates, and expiry dates. This is essential for:
                </p>
                <ul class="text-sm text-muted space-y-1">
                    <li>Food and pharmaceutical products</li>
                    <li>Products with limited shelf life</li>
                    <li>Quality control and recall management</li>
                    <li>FIFO (First In, First Out) inventory management</li>
                </ul>
            </div>
            <div>
                <h4 class="font-medium mb-2">Best Practices</h4>
                <ul class="text-sm text-muted space-y-1">
                    <li>Always record batch numbers during purchases</li>
                    <li>Monitor expiry dates regularly</li>
                    <li>Use FIFO method for stock rotation</li>
                    <li>Set up alerts for products nearing expiry</li>
                    <li>Remove expired products immediately</li>
                </ul>
            </div>
        </div>
    </div>
</div>
