<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>
<?php $isEdit=isset($est)&&!empty($est['id']); $e=$est??[]; ?>
<div class="page-header">
  <div><h1><i class="bi bi-calculator me-2"></i><?= $isEdit?'Edit '.esc($e['est_number']):'New Estimation' ?></h1></div>
</div>
<?php $formUrl=$isEdit?base_url('estimations/update/'.$e['id']):base_url('estimations/store'); ?>
<?= form_open($formUrl) ?>
<div class="row g-3">
  <div class="col-lg-8">
    <!-- Header Info -->
    <div class="fm-form-section">
      <h6><i class="bi bi-info-circle"></i>Estimation Details</h6>
      <div class="row g-2">
        <div class="col-md-8">
          <label class="form-label">Title <span class="text-danger">*</span></label>
          <input type="text" name="title" class="form-control" value="<?= esc($e['title']??old('title')) ?>" required>
        </div>
        <div class="col-md-4">
          <label class="form-label">Facility <span class="text-danger">*</span></label>
          <select name="facility_id" class="form-select" required>
            <option value="">— Select —</option>
            <?php foreach($facilities as $f): ?>
            <option value="<?= $f['id'] ?>" <?= ($e['facility_id']??'')==$f['id']?'selected':'' ?>><?= esc($f['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-12">
          <label class="form-label">Linked Work Order</label>
          <select name="wo_id" class="form-select">
            <option value="">— None —</option>
            <?php foreach($workOrders as $wo): ?>
            <option value="<?= $wo['id'] ?>" <?= ($e['wo_id']??'')==$wo['id']?'selected':'' ?>><?= esc($wo['wo_number']) ?> — <?= esc(substr($wo['title'],0,50)) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-12">
          <label class="form-label">Description / Scope of Work</label>
          <textarea name="description" class="form-control" rows="3"><?= esc($e['description']??'') ?></textarea>
        </div>
      </div>
    </div>

    <!-- Line Items -->
    <div class="fm-form-section">
      <h6><i class="bi bi-list-ol"></i>Line Items</h6>
      <table class="table table-sm" id="lineItems">
        <thead><tr><th>Type</th><th>Description</th><th style="width:80px">Qty</th><th style="width:110px">Unit Cost</th><th style="width:110px">Total</th><th style="width:40px"></th></tr></thead>
        <tbody id="lineBody">
          <?php $existingItems=$items??[['type'=>'material','description'=>'','quantity'=>1,'unit_cost'=>0]]; ?>
          <?php foreach($existingItems as $i=>$item): ?>
          <tr class="line-row">
            <td>
              <select name="item_type[]" class="form-select form-select-sm">
                <?php foreach(['material'=>'Material','labor'=>'Labor','other'=>'Other'] as $v=>$l): ?>
                <option value="<?= $v ?>" <?= ($item['type']??'material')===$v?'selected':'' ?>><?= $l ?></option>
                <?php endforeach; ?>
              </select>
            </td>
            <td><input type="text" name="item_desc[]" class="form-control form-control-sm" value="<?= esc($item['description']??'') ?>" placeholder="Description"></td>
            <td><input type="number" name="item_qty[]" class="form-control form-control-sm qty-input" value="<?= $item['quantity']??1 ?>" min="0" step="0.1" onchange="calcRow(this)"></td>
            <td><input type="number" name="item_cost[]" class="form-control form-control-sm cost-input" value="<?= $item['unit_cost']??0 ?>" min="0" step="0.01" onchange="calcRow(this)"></td>
            <td><input type="number" name="item_total[]" class="form-control form-control-sm row-total" value="<?= ($item['quantity']??1)*($item['unit_cost']??0) ?>" readonly style="background:#f9f9f9"></td>
            <td><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)"><i class="bi bi-trash"></i></button></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
        <tfoot><tr>
          <td colspan="3"></td>
          <td class="text-end small fw-semibold">Subtotal</td>
          <td><input type="number" id="subtotalDisplay" class="form-control form-control-sm" readonly style="background:#f0f4f8;font-weight:700"></td>
          <td></td>
        </tr></tfoot>
      </table>
      <button type="button" class="btn btn-fm-outline btn-sm" onclick="addRow()"><i class="bi bi-plus me-1"></i>Add Line Item</button>
    </div>

    <div class="fm-form-section">
      <h6><i class="bi bi-card-text"></i>Notes</h6>
      <textarea name="notes" class="form-control" rows="2" placeholder="Terms, conditions, validity..."><?= esc($e['notes']??'') ?></textarea>
    </div>
  </div>

  <!-- Summary Sidebar -->
  <div class="col-lg-4">
    <div class="fm-form-section position-sticky" style="top:80px">
      <h6><i class="bi bi-receipt"></i>Cost Summary</h6>
      <div class="mb-3">
        <label class="form-label small">Labor Cost (<?= $currency ?>)</label>
        <input type="number" name="labor_cost" id="laborCostInput" class="form-control" step="0.01" min="0" value="<?= $e['labor_cost']??0 ?>" oninput="updateSummary()">
      </div>
      <div class="mb-3">
        <label class="form-label small">Material Cost (<?= $currency ?>)</label>
        <input type="number" name="material_cost" id="materialCostInput" class="form-control" step="0.01" min="0" value="<?= $e['material_cost']??0 ?>" oninput="updateSummary()">
      </div>
      <div class="mb-3">
        <label class="form-label small">Other Cost (<?= $currency ?>)</label>
        <input type="number" name="other_cost" id="otherCostInput" class="form-control" step="0.01" min="0" value="<?= $e['other_cost']??0 ?>" oninput="updateSummary()">
      </div>
      <hr>
      <?php if($vatEnabled): ?>
      <div class="d-flex justify-content-between small mb-2">
        <span>VAT (<?= $vatRate ?>%)</span>
        <strong id="vatDisplay">0.00</strong>
      </div>
      <?php endif; ?>
      <div class="d-flex justify-content-between fw-bold mb-3" style="font-size:1.1rem">
        <span>TOTAL</span>
        <span id="totalDisplay" style="color:var(--fm-primary)">0.00</span>
      </div>
      <button type="submit" class="btn btn-fm-primary w-100"><i class="bi bi-check-lg me-2"></i><?= $isEdit?'Update':'Save Estimation' ?></button>
      <a href="<?= base_url('estimations') ?>" class="btn btn-fm-outline w-100 mt-2">Cancel</a>
    </div>
  </div>
</div>
<?= form_close() ?>

<?= $this->section('scripts') ?>
<script>
const VAT_ENABLED = <?= $vatEnabled?'true':'false' ?>;
const VAT_RATE    = <?= $vatRate ?>;
const CURRENCY    = '<?= $currency ?>';

function calcRow(inp){
  const row=inp.closest('.line-row');
  const qty=parseFloat(row.querySelector('.qty-input').value)||0;
  const cost=parseFloat(row.querySelector('.cost-input').value)||0;
  row.querySelector('.row-total').value=(qty*cost).toFixed(2);
}
function removeRow(btn){ if(document.querySelectorAll('.line-row').length>1) btn.closest('tr').remove(); updateSummary(); }
function addRow(){
  const tbody=document.getElementById('lineBody');
  const tr=document.createElement('tr');tr.className='line-row';
  tr.innerHTML=`<td><select name="item_type[]" class="form-select form-select-sm"><option value="material">Material</option><option value="labor">Labor</option><option value="other">Other</option></select></td><td><input type="text" name="item_desc[]" class="form-control form-control-sm" placeholder="Description"></td><td><input type="number" name="item_qty[]" class="form-control form-control-sm qty-input" value="1" min="0" step="0.1" onchange="calcRow(this)"></td><td><input type="number" name="item_cost[]" class="form-control form-control-sm cost-input" value="0" min="0" step="0.01" onchange="calcRow(this)"></td><td><input type="number" name="item_total[]" class="form-control form-control-sm row-total" value="0" readonly style="background:#f9f9f9"></td><td><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)"><i class="bi bi-trash"></i></button></td>`;
  tbody.appendChild(tr);
}
function updateSummary(){
  const labor=parseFloat(document.getElementById('laborCostInput').value)||0;
  const material=parseFloat(document.getElementById('materialCostInput').value)||0;
  const other=parseFloat(document.getElementById('otherCostInput').value)||0;
  const subtotal=labor+material+other;
  const vat=VAT_ENABLED?Math.round(subtotal*VAT_RATE/100*100)/100:0;
  const total=subtotal+vat;
  if(document.getElementById('vatDisplay')) document.getElementById('vatDisplay').textContent=vat.toFixed(2);
  document.getElementById('totalDisplay').textContent=total.toFixed(2);
  if(document.getElementById('subtotalDisplay')) document.getElementById('subtotalDisplay').value=subtotal.toFixed(2);
}
document.addEventListener('DOMContentLoaded',updateSummary);
</script>
<?= $this->endSection() ?>
<?= $this->endSection() ?>
