<?php $title=__('stock.usage_history', 'Usage History'); ob_start(); ?>

<?php if(isset($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
    <?=htmlspecialchars($_SESSION['success']); unset($_SESSION['success']);?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0">
        <i class="fas fa-history"></i> <?= __('stock.usage_history_aggregated', 'Applied Usage History (Aggregated)') ?>
    </h1>
    <div>
        <a href="/samanta_crm/stock/ingredients" class="btn btn-secondary">
            <i class="fas fa-arrow-left me-1"></i><?= __('stock.back_to_stock', 'Back to Stock') ?>
        </a>
    </div>
</div>

<div class="card">
    <div class="card-header py-2">
        <span class="small fw-bold"><i class="fas fa-table me-1"></i><?= __('stock.usage_dates', 'Usage Dates') ?></span>
    </div>
    <div class="card-body pt-0">
        <table class="table table-sm table-hover align-middle data-table mb-0">
	<thead><tr><th><?= __('common.date', 'Date') ?></th><th class="text-end"><?= __('stock.items', 'Items') ?></th><th><?= __("common.actions", "Actions") ?></th></tr></thead>
	<tbody>
	<?php foreach($rows as $r): $rolled = isset($r['rolled_items']) ? ((int)$r['rolled_items']) : 0; $allRolled = ($rolled>0 && $rolled==(int)$r['items']); ?>
		<tr class="<?= $allRolled ? 'table-secondary':''; ?>">
			<td><a href="/samanta_crm/stock/usage-history?date=<?=htmlspecialchars($r['apply_date']);?>"><?=htmlspecialchars($r['apply_date']);?></a></td>
			<td class="text-end"><?= (int)$r['items']; ?></td>
			<td>
				<a href="/samanta_crm/stock/usage-history?date=<?=htmlspecialchars($r['apply_date']);?>" class="btn btn-sm btn-primary">View</a>
				<form method="post" action="/samanta_crm/stock/rollback-daily" style="display:inline" onsubmit="return confirm('Rollback usage for <?=htmlspecialchars($r['apply_date']);?>? This will restore stock.');">
					<input type="hidden" name="rollback_date" value="<?=htmlspecialchars($r['apply_date']);?>">
					<button class="btn btn-sm btn-warning">Rollback</button>
				</form>
			</td>
		</tr>
	<?php endforeach; ?>
        </tbody>
        </table>
    </div>
    <div class="card-footer py-2 d-flex justify-content-between align-items-center">
        <span></span>
        <div class="small text-muted">
            <?= __('common.total', 'Total') ?>: <?= count($rows) ?> <?= __('stock.dates', 'dates') ?>
        </div>
    </div>
</div>

<?php $content=ob_get_clean(); include '../app/Views/layout.php'; ?>
