<?php /* stock/adjust.php */ ?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h5 class="fw-semibold mb-0">
    <i class="bi bi-sliders me-2 text-warning"></i>Stock Adjustment
  </h5>
  <a href="<?= APP_URL ?>/stock" class="btn btn-sm btn-outline-secondary">
    <i class="bi bi-arrow-left me-1"></i>Back to Stock
  </a>
</div>

<div class="row g-3 align-items-start">

  <!-- Adjustment Form -->
  <div class="col-md-5">
    <div class="card">
      <div class="card-header bg-transparent fw-semibold small">
        <i class="bi bi-pencil-square me-1"></i>Adjust Stock
      </div>
      <div class="card-body">
        <form method="POST" action="<?= APP_URL ?>/stock/adjust" id="adj-form">
          <?= Auth::csrfField() ?>

          <!-- Product select -->
          <div class="mb-3">
            <label class="form-label small fw-semibold">Product *</label>
            <select name="product_id" id="product-sel" class="form-select" required
                    onchange="onProductChange(this)">
              <option value="">— Select Product —</option>
              <?php foreach ($products as $p): ?>
              <option value="<?= $p['id'] ?>"
                      data-stock="<?= (float)$p['current_stock'] ?>"
                      data-reorder="<?= (float)$p['reorder_level'] ?>"
                      data-unit="<?= e($p['unit'] ?? '') ?>"
                      <?= $preProduct == $p['id'] ? 'selected' : '' ?>>
                <?= e($p['product_name']) ?>
                (<?= e($p['product_code']) ?>)
                — Stock: <?= number_format((float)$p['current_stock'], 2) ?>
                <?= e($p['unit'] ?? '') ?>
              </option>
              <?php endforeach; ?>
            </select>
          </div>

          <!-- Current stock info panel -->
          <div id="stock-info" class="mb-3 p-3 rounded"
               style="background:#f0f7ff;border:1px solid #c0d8f8;display:none">
            <div class="row g-2 text-center">
              <div class="col-4">
                <div class="text-muted small">Current</div>
                <div class="fw-bold fs-5 text-primary" id="info-current">—</div>
              </div>
              <div class="col-4">
                <div class="text-muted small">Reorder</div>
                <div class="fw-bold" id="info-reorder">—</div>
              </div>
              <div class="col-4">
                <div class="text-muted small">After Adj.</div>
                <div class="fw-bold fs-5" id="info-after" style="color:#198754">—</div>
              </div>
            </div>
          </div>

          <!-- Adjustment type -->
          <div class="mb-3">
            <label class="form-label small fw-semibold">Adjustment Type *</label>
            <div class="d-flex gap-2">
              <label class="flex-grow-1">
                <input type="radio" name="type" value="adjustment_add"
                       class="btn-check" id="type-add" checked onchange="recalcPreview()">
                <span class="btn btn-outline-success w-100">
                  <i class="bi bi-plus-circle me-1"></i>Add Stock
                </span>
              </label>
              <label class="flex-grow-1">
                <input type="radio" name="type" value="adjustment_sub"
                       class="btn-check" id="type-sub" onchange="recalcPreview()">
                <span class="btn btn-outline-danger w-100">
                  <i class="bi bi-dash-circle me-1"></i>Remove
                </span>
              </label>
              <label class="flex-grow-1">
                <input type="radio" name="type" value="adjustment_set"
                       class="btn-check" id="type-set" onchange="recalcPreview()">
                <span class="btn btn-outline-primary w-100">
                  <i class="bi bi-pencil me-1"></i>Set Exact
                </span>
              </label>
            </div>
            <small class="text-muted mt-1 d-block" id="type-hint">
              Enter the quantity to add to current stock.
            </small>
          </div>

          <!-- Quantity -->
          <div class="mb-3">
            <label class="form-label small fw-semibold" id="qty-label">Quantity *</label>
            <div class="input-group">
              <input type="number" name="quantity" id="qty-input"
                     class="form-control form-control-lg fw-bold"
                     step="0.01" min="0" required value=""
                     placeholder="0"
                     oninput="recalcPreview()">
              <span class="input-group-text" id="unit-badge">units</span>
            </div>
          </div>

          <!-- Note -->
          <div class="mb-3">
            <label class="form-label small fw-semibold">Reason / Note</label>
            <textarea name="note" class="form-control" rows="2"
                      placeholder="e.g. Damaged goods, Physical count correction…"></textarea>
          </div>

          <button type="submit" class="btn btn-warning w-100 fw-semibold btn-lg"
                  id="submit-btn" onclick="return confirmAdj(event)">
            <i class="bi bi-check-circle me-1"></i>Apply Adjustment
          </button>

        </form>
      </div>
    </div>
  </div>

  <!-- Recent Adjustments -->
  <div class="col-md-7">
    <div class="card">
      <div class="card-header bg-transparent fw-semibold small">
        <i class="bi bi-clock-history me-1"></i>Recent Adjustments
        <span class="badge bg-secondary ms-1"><?= count($recentAdjustments) ?></span>
      </div>
      <div class="card-body p-0">
        <?php if (!empty($recentAdjustments)): ?>
        <div class="table-responsive">
          <table class="table table-sm mb-0">
            <thead class="table-light">
              <tr>
                <th>Product</th>
                <th>Type</th>
                <th class="text-end">Qty In</th>
                <th class="text-end">Qty Out</th>
                <th class="text-end">After</th>
                <th>Note</th>
                <th>By / When</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($recentAdjustments as $adj):
                $typeMap = [
                  'adjustment_add' => ['bg-success', '+ Add'],
                  'adjustment_sub' => ['bg-danger',  '− Remove'],
                  'adjustment_set' => ['bg-primary',  '= Set'],
                ];
                [$badgeCls, $typeLabel] = $typeMap[$adj['movement_type']] ?? ['bg-secondary', $adj['movement_type']];
              ?>
              <tr>
                <td>
                  <div class="small fw-semibold"><?= e($adj['product_name']) ?></div>
                  <small class="text-muted font-monospace"><?= e($adj['product_code']) ?></small>
                </td>
                <td>
                  <span class="badge <?= $badgeCls ?>" style="font-size:.7rem">
                    <?= $typeLabel ?>
                  </span>
                </td>
                <td class="text-end text-success fw-semibold small">
                  <?= $adj['quantity_in'] > 0 ? '+'.number_format($adj['quantity_in'],2) : '—' ?>
                </td>
                <td class="text-end text-danger small">
                  <?= $adj['quantity_out'] > 0 ? '−'.number_format($adj['quantity_out'],2) : '—' ?>
                </td>
                <td class="text-end fw-semibold small">
                  <?= number_format((float)$adj['stock_after'], 2) ?>
                </td>
                <td class="text-muted small"><?= e(mb_strimwidth($adj['note'] ?? '', 0, 25, '…')) ?></td>
                <td>
                  <small class="text-muted"><?= e($adj['done_by'] ?? '—') ?></small>
                  <div style="font-size:.65rem" class="text-muted">
                    <?= fDate($adj['created_at'], 'd M H:i') ?>
                  </div>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <?php else: ?>
        <div class="text-center text-muted py-5">
          <i class="bi bi-sliders fs-2 d-block mb-2 opacity-25"></i>
          No stock adjustments yet.
        </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

</div><!-- /row -->

<script>
// Product data map
const productData = {
  <?php foreach ($products as $p): ?>
  <?= (int)$p['id'] ?>: {
    stock:   <?= (float)$p['current_stock'] ?>,
    reorder: <?= (float)$p['reorder_level'] ?>,
    unit:    '<?= e($p['unit'] ?? 'units') ?>'
  },
  <?php endforeach; ?>
};

function onProductChange(sel) {
  const pid = parseInt(sel.value);
  const d   = productData[pid];
  if (!d) {
    document.getElementById('stock-info').style.display = 'none';
    return;
  }
  document.getElementById('info-current').textContent = d.stock.toFixed(2) + ' ' + d.unit;
  document.getElementById('info-reorder').textContent = d.reorder > 0 ? d.reorder.toFixed(0) : '—';
  document.getElementById('unit-badge').textContent   = d.unit || 'units';
  document.getElementById('stock-info').style.display = 'block';
  recalcPreview();
}

function getType() {
  return document.querySelector('[name=type]:checked')?.value || 'adjustment_add';
}

function recalcPreview() {
  const pid  = parseInt(document.getElementById('product-sel').value);
  const d    = productData[pid];
  const qty  = parseFloat(document.getElementById('qty-input').value) || 0;
  const type = getType();

  // Update hint text and label
  const hints = {
    adjustment_add: 'Enter the quantity to add to current stock.',
    adjustment_sub: 'Enter the quantity to remove from current stock.',
    adjustment_set: 'Enter the exact new stock quantity (replaces current).',
  };
  const labels = {
    adjustment_add: 'Quantity to Add *',
    adjustment_sub: 'Quantity to Remove *',
    adjustment_set: 'New Exact Quantity *',
  };
  document.getElementById('type-hint').textContent  = hints[type] || '';
  document.getElementById('qty-label').textContent  = labels[type] || 'Quantity *';

  if (!d) return;

  let after;
  if (type === 'adjustment_set')  after = Math.max(0, qty);
  else if (type === 'adjustment_add') after = d.stock + qty;
  else after = Math.max(0, d.stock - qty);

  const afterEl = document.getElementById('info-after');
  afterEl.textContent = after.toFixed(2) + ' ' + d.unit;
  afterEl.style.color = after <= 0 ? '#dc3545'
                      : (after <= d.reorder && d.reorder > 0) ? '#fd7e14'
                      : '#198754';
}

function confirmAdj(e) {
  const pid  = document.getElementById('product-sel').value;
  const qty  = parseFloat(document.getElementById('qty-input').value) || 0;
  const type = getType();
  if (!pid) { alert('Please select a product.'); e.preventDefault(); return false; }
  if (qty <= 0 && type !== 'adjustment_set') {
    alert('Quantity must be greater than zero.');
    e.preventDefault(); return false;
  }
  return true;
}

// Pre-select if product param provided
<?php if ($preProduct): ?>
const preEl = document.getElementById('product-sel');
if (preEl) { preEl.value = '<?= (int)$preProduct ?>'; onProductChange(preEl); }
<?php endif; ?>

// Init
onProductChange(document.getElementById('product-sel'));
</script>
