<?php /* products/form.php */
$isEdit = isset($product);
$sym    = e(setting('currency_symbol','Rs.'));
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h5 class="fw-semibold mb-0">
    <i class="bi bi-box-seam me-2 text-primary"></i>
    <?= $isEdit ? 'Edit Product' : 'Add New Product' ?>
  </h5>
  <a href="<?= APP_URL ?>/products" class="btn btn-sm btn-outline-secondary">
    <i class="bi bi-arrow-left me-1"></i>Back
  </a>
</div>

<form method="POST"
      action="<?= APP_URL ?>/products/<?= $isEdit ? 'edit/'.$product['id'] : 'create' ?>"
      enctype="multipart/form-data" id="product-form">
  <?= Auth::csrfField() ?>

  <div class="row g-3">

    <!-- ── LEFT COL ────────────────────────────────────── -->
    <div class="col-lg-8">

      <!-- Basic Information -->
      <div class="card mb-3">
        <div class="card-header bg-transparent fw-semibold small">
          <i class="bi bi-info-circle me-1"></i>Basic Information
        </div>
        <div class="card-body">
          <div class="row g-3">

            <div class="col-12">
              <label class="form-label small fw-semibold">Product Name *</label>
              <input type="text" name="product_name" class="form-control" required
                     placeholder="e.g. Panadol Extra 500mg Tablet"
                     value="<?= e($product['product_name'] ?? '') ?>">
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Product Code *</label>
              <div class="input-group">
                <input type="text" name="product_code" class="form-control" required
                       id="product-code"
                       placeholder="e.g. PRD-001"
                       value="<?= e($product['product_code'] ?? '') ?>">
                <?php if (!$isEdit): ?>
                <button class="btn btn-outline-secondary" type="button"
                        onclick="genCode()" title="Generate code">
                  <i class="bi bi-arrow-repeat"></i>
                </button>
                <?php endif; ?>
              </div>
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Barcode</label>
              <div class="input-group">
                <span class="input-group-text"><i class="bi bi-upc-scan"></i></span>
                <input type="text" name="barcode" id="barcodeInput" class="form-control"
                       placeholder="Scan or type barcode (optional)"
                       value="<?= e($product['barcode'] ?? '') ?>">
                <button type="button" class="btn btn-outline-secondary"
                        onclick="genBarcode()" title="Generate a unique barcode">
                  <i class="bi bi-arrow-repeat"></i>
                </button>
              </div>
              <div class="form-text">
                <i class="bi bi-upc me-1"></i>
                Scan, type manually, or click ↻ to generate one. Leave empty if not needed.
              </div>
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Generic / Alt. Name</label>
              <input type="text" name="generic_name" class="form-control"
                     placeholder="Alternative name"
                     value="<?= e($product['generic_name'] ?? '') ?>">
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Category</label>
              <select name="category_id" class="form-select">
                <option value="">— Select Category —</option>
                <?php foreach ($categories as $c): ?>
                <option value="<?= $c['id'] ?>"
                  <?= ($product['category_id'] ?? '') == $c['id'] ? 'selected' : '' ?>>
                  <?= e($c['category_name']) ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Brand</label>
              <select name="brand_id" class="form-select">
                <option value="">— Select Brand —</option>
                <?php foreach ($brands as $b): ?>
                <option value="<?= $b['id'] ?>"
                  <?= ($product['brand_id'] ?? '') == $b['id'] ? 'selected' : '' ?>>
                  <?= e($b['brand_name']) ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Unit</label>
              <select name="unit_id" class="form-select">
                <option value="">— Select Unit —</option>
                <?php foreach ($units as $u): ?>
                <option value="<?= $u['id'] ?>"
                  <?= ($product['unit_id'] ?? '') == $u['id'] ? 'selected' : '' ?>>
                  <?= e($u['unit_name']) ?> (<?= e($u['short_name']) ?>)
                </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-12">
              <label class="form-label small fw-semibold">Description</label>
              <textarea name="description" class="form-control" rows="2"
                        placeholder="Optional product description…"><?= e($product['description'] ?? '') ?></textarea>
            </div>

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

      <!-- Pricing -->
      <div class="card mb-3">
        <div class="card-header bg-transparent fw-semibold small">
          <i class="bi bi-tag me-1"></i>Pricing
        </div>
        <div class="card-body">
          <div class="row g-3">

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Cost Price *</label>
              <div class="input-group">
                <span class="input-group-text"><?= $sym ?></span>
                <input type="number" name="cost_price" id="cost-price"
                       class="form-control" step="0.01" min="0" required
                       value="<?= $product['cost_price'] ?? 0 ?>"
                       oninput="calcMargin()">
              </div>
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Selling Price *</label>
              <div class="input-group">
                <span class="input-group-text"><?= $sym ?></span>
                <input type="number" name="selling_price" id="selling-price"
                       class="form-control" step="0.01" min="0" required
                       value="<?= $product['selling_price'] ?? 0 ?>"
                       oninput="calcMargin()">
              </div>
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Wholesale Price</label>
              <div class="input-group">
                <span class="input-group-text"><?= $sym ?></span>
                <input type="number" name="wholesale_price"
                       class="form-control" step="0.01" min="0"
                       value="<?= $product['wholesale_price'] ?? 0 ?>">
              </div>
            </div>

            <!-- Live Margin Preview -->
            <div class="col-12">
              <div class="p-2 rounded d-flex gap-4 align-items-center flex-wrap"
                   style="background:#f0f7ff;border:1px solid #c0d8f8;font-size:.8rem">
                <div>
                  <span class="text-muted">Profit:</span>
                  <span class="fw-bold ms-1" id="margin-profit">—</span>
                </div>
                <div>
                  <span class="text-muted">Gross Margin</span>
                  <span style="font-size:.68rem;color:#94a3b8">(profit/sale)</span>
                  <span class="fw-bold ms-1" id="margin-pct">—</span>
                </div>
                <div>
                  <span class="text-muted">Markup</span>
                  <span style="font-size:.68rem;color:#94a3b8">(profit/cost)</span>
                  <span class="fw-bold ms-1" id="markup-pct">—</span>
                </div>
              </div>
            </div>

            <div class="col-md-3">
              <label class="form-label small fw-semibold">Tax %</label>
              <div class="input-group">
                <input type="number" name="tax_percent" class="form-control"
                       step="0.01" min="0" max="100"
                       value="<?= $product['tax_percent'] ?? 0 ?>">
                <span class="input-group-text">%</span>
              </div>
            </div>

            <div class="col-md-3">
              <label class="form-label small fw-semibold">Discount %</label>
              <div class="input-group">
                <input type="number" name="discount_percent" class="form-control"
                       step="0.01" min="0" max="100"
                       value="<?= $product['discount_percent'] ?? 0 ?>">
                <span class="input-group-text">%</span>
              </div>
            </div>

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

      <!-- Stock -->
      <div class="card mb-3">
        <div class="card-header bg-transparent fw-semibold small">
          <i class="bi bi-layers me-1"></i>Stock
        </div>
        <div class="card-body">
          <div class="row g-3">

            <div class="col-md-4">
              <label class="form-label small fw-semibold">
                <?= $isEdit ? 'Current Stock' : 'Opening Stock' ?>
              </label>
              <input type="number" name="current_stock" class="form-control"
                     step="0.01" min="0"
                     value="<?= $product['current_stock'] ?? 0 ?>"
                     <?= $isEdit ? 'readonly' : '' ?>>
              <?php if ($isEdit): ?>
              <small class="text-muted">
                Use <a href="<?= APP_URL ?>/stock/adjust">Stock Adjustment</a> to change.
              </small>
              <?php endif; ?>
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Reorder Level</label>
              <input type="number" name="reorder_level" class="form-control"
                     step="0.01" min="0"
                     placeholder="Alert when stock falls below"
                     value="<?= $product['reorder_level'] ?? 0 ?>">
              <small class="text-muted">Low-stock alert threshold</small>
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-semibold">Max Stock Level</label>
              <input type="number" name="max_stock_level" class="form-control"
                     step="0.01" min="0"
                     placeholder="Optional upper limit"
                     value="<?= $product['max_stock_level'] ?? 0 ?>">
            </div>

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

    </div><!-- /left col -->

    <!-- ── RIGHT COL ───────────────────────────────────── -->
    <div class="col-lg-4">

      <!-- Product Image -->
      <div class="card mb-3">
        <div class="card-header bg-transparent fw-semibold small">
          <i class="bi bi-image me-1"></i>Product Image
        </div>
        <div class="card-body text-center">
          <div id="img-preview" class="mb-2"
               style="height:160px;display:flex;align-items:center;justify-content:center;
                      background:#f8f9fa;border:2px dashed #dee2e6;border-radius:8px;
                      overflow:hidden;cursor:pointer"
               onclick="document.getElementById('img-input').click()">
            <?php if (!empty($product['product_image'])): ?>
            <img src="<?= UPLOAD_URL ?>/<?= e($product['product_image']) ?>"
                 id="img-tag" style="max-height:156px;max-width:100%;object-fit:contain">
            <?php else: ?>
            <div id="img-placeholder">
              <i class="bi bi-cloud-upload fs-2 text-muted d-block mb-1"></i>
              <small class="text-muted">Click to upload image</small>
            </div>
            <?php endif; ?>
          </div>
          <input type="file" name="product_image" id="img-input"
                 class="d-none" accept="image/*"
                 onchange="previewImage(this)">
          <button type="button" class="btn btn-outline-secondary btn-sm w-100"
                  onclick="document.getElementById('img-input').click()">
            <i class="bi bi-upload me-1"></i>
            <?= !empty($product['product_image']) ? 'Change Image' : 'Upload Image' ?>
          </button>
          <small class="text-muted d-block mt-1">JPG / PNG / WebP — Max 2MB</small>
        </div>
      </div>

      <!-- Options -->
      <div class="card mb-3">
        <div class="card-header bg-transparent fw-semibold small">
          <i class="bi bi-sliders me-1"></i>Options
        </div>
        <div class="card-body">

          <label class="form-label small fw-semibold">Status</label>
          <select name="status" class="form-select form-select-sm mb-3">
            <option value="active"
              <?= ($product['status'] ?? 'active') === 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive"
              <?= ($product['status'] ?? '') === 'inactive' ? 'selected' : '' ?>>Inactive</option>
          </select>

          <div class="form-check mb-2">
            <input type="checkbox" name="has_expiry" class="form-check-input"
                   id="has_expiry" value="1"
                   onchange="toggleExpiry(this.checked)"
                   <?= !empty($product['has_expiry']) ? 'checked' : '' ?>>
            <label class="form-check-label small" for="has_expiry">
              <i class="bi bi-calendar-x me-1 text-danger"></i>This product has an Expiry Date
            </label>
          </div>

          <div id="expiry-wrap" class="mb-3"
               style="display:<?= !empty($product['has_expiry']) ? 'block' : 'none' ?>">
            <label class="form-label small fw-semibold">
              Expiry Date <span class="text-danger">*</span>
            </label>
            <input type="date" name="expiry_date" id="expiry_date"
                   class="form-control form-control-sm"
                   value="<?= e($product['expiry_date'] ?? '') ?>"
                   min="<?= date('Y-m-d') ?>">
            <?php
            $exp = $product['expiry_date'] ?? '';
            if ($exp):
              $daysLeft = (int) ceil((strtotime($exp) - time()) / 86400);
              $expClr = $daysLeft < 0 ? '#dc2626' : ($daysLeft <= 30 ? '#d97706' : '#16a34a');
              $expMsg = $daysLeft < 0
                ? ' Expired ' . abs($daysLeft) . ' days ago'
                : ($daysLeft === 0 ? ' Expires today!' : " {$daysLeft} days remaining");
            ?>
            <div class="form-text fw-semibold" style="color:<?=$expClr?>">
              <?=$expMsg?>
            </div>
            <?php endif;?>
          </div>

          <div class="form-check mb-2">
            <input type="checkbox" name="is_batch" class="form-check-input"
                   id="is_batch" value="1"
                   <?= !empty($product['is_batch']) ? 'checked' : '' ?>>
            <label class="form-check-label small" for="is_batch">
              <i class="bi bi-calendar-range me-1 text-muted"></i>Track Batches / Expiry
            </label>
          </div>

          <div class="form-check">
            <input type="checkbox" name="is_serial" class="form-check-input"
                   id="is_serial" value="1"
                   <?= !empty($product['is_serial']) ? 'checked' : '' ?>>
            <label class="form-check-label small" for="is_serial">
              <i class="bi bi-hash me-1 text-muted"></i>Track Serial Numbers
            </label>
          </div>

        </div>
      </div>

      <!-- Save Button -->
      <button type="submit" class="btn btn-primary w-100 btn-lg fw-semibold">
        <i class="bi bi-check-circle me-2"></i>
        <?= $isEdit ? 'Update Product' : 'Save Product' ?>
      </button>
      <a href="<?= APP_URL ?>/products" class="btn btn-outline-secondary w-100 mt-2">
        Cancel
      </a>

    </div><!-- /right col -->
  </div>
</form>

<script>
const SYM = '<?= $sym ?>';

// ── Margin calculator ──────────────────────────────────────
function calcMargin() {
  const cost  = parseFloat(document.getElementById('cost-price').value)   || 0;
  const sell  = parseFloat(document.getElementById('selling-price').value) || 0;
  const profit = sell - cost;

  // Markup on Cost  = profit / cost × 100    (e.g. cost 100 → sell 200 = 100%)
  const markup = cost > 0 ? ((profit / cost)  * 100).toFixed(1) : 0;
  // Margin on Sale  = profit / selling × 100  (e.g. 100/200 = 50%)
  const margin = sell > 0 ? ((profit / sell)  * 100).toFixed(1) : 0;

  const profitEl = document.getElementById('margin-profit');
  const mPctEl   = document.getElementById('margin-pct');
  const mkPctEl  = document.getElementById('markup-pct');

  profitEl.textContent = SYM + ' ' + profit.toFixed(2);
  mPctEl.textContent   = margin + '%';   // Gross Margin (sale-based)
  mkPctEl.textContent  = markup + '%';   // Markup (cost-based)

  const color = markup >= 30 ? '#198754' : markup >= 15 ? '#fd7e14' : '#dc3545';
  [profitEl, mPctEl, mkPctEl].forEach(el => el.style.color = color);
}

// ── Image preview ──────────────────────────────────────────
function previewImage(input) {
  if (!input.files || !input.files[0]) return;
  const reader = new FileReader();
  reader.onload = e => {
    const preview = document.getElementById('img-preview');
    const ph      = document.getElementById('img-placeholder');
    let   img     = document.getElementById('img-tag');
    if (!img) {
      img = document.createElement('img');
      img.id = 'img-tag';
      img.style.cssText = 'max-height:156px;max-width:100%;object-fit:contain';
      preview.innerHTML = '';
      preview.appendChild(img);
    }
    if (ph) ph.style.display = 'none';
    img.src = e.target.result;
    preview.style.border = '2px dashed #0d6efd';
  };
  reader.readAsDataURL(input.files[0]);
}

// ── Auto-generate product code ─────────────────────────────
function toggleExpiry(checked) {
  const wrap = document.getElementById('expiry-wrap');
  const input = document.getElementById('expiry_date');
  wrap.style.display = checked ? 'block' : 'none';
  input.required = checked;
  if (!checked) input.value = '';
}

function genCode() {
  const rand = Math.random().toString(36).substring(2,6).toUpperCase();
  document.getElementById('product-code').value = 'PRD-' + rand;
}

async function genBarcode() {
  const btn = document.activeElement;
  const input = document.getElementById('barcodeInput');
  const original = input.value;
  input.value = 'Generating…';
  try {
    const res  = await fetch('<?=APP_URL?>/products/generate-barcode');
    const data = await res.json();
    input.value = data.barcode || original;
  } catch (e) {
    input.value = original;
    alert('Could not generate barcode — please try again.');
  }
}

// Run margin calc on page load for edit mode
calcMargin();
</script>