<?php $this->start('body'); ?>
<?php $w = $this->data['w']; $parts = $this->data['parts']; ?>
<?php $bg = ['open'=>'warning','in_progress'=>'info','completed'=>'primary','closed'=>'success','cancelled'=>'dark'][$w['status']] ?? 'secondary';
      $pbg = ['low'=>'light','normal'=>'light','high'=>'warning','urgent'=>'danger'][$w['priority']] ?? 'light'; ?>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-semibold"><i class="fas fa-wrench me-2 text-muted"></i><?= htmlspecialchars($w['wo_no']); ?>
      <span class="badge bg-<?= $bg; ?> ms-2" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars(str_replace('_',' ',$w['status'])); ?></span>
      <?php if ($w['priority'] !== 'normal'): ?>
        <span class="badge bg-<?= $pbg; ?> <?= $w['priority']==='urgent'?'text-white':'text-dark'; ?> ms-1" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars($w['priority']); ?></span>
      <?php endif; ?>
    </h5>
    <div class="text-muted small">
      <?= htmlspecialchars(ucfirst($w['kind'])); ?> ·
      <a href="<?= PROOT; ?>Trucks/view/<?= (int)$w['truck_id']; ?>"><?= htmlspecialchars($w['truck_reg']); ?></a>
      <?php if ($w['vendor_name']): ?> · <a href="<?= PROOT; ?>Vendors/view/<?= (int)$w['vendor_id']; ?>"><?= htmlspecialchars($w['vendor_name']); ?></a><?php else: ?> · <em class="text-muted">internal workshop</em><?php endif; ?>
      · opened <?= humanDate($w['opened_on']); ?>
    </div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= PROOT; ?>WorkOrders" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    <?php if (!in_array($w['status'], ['closed','cancelled'], true)): ?>
      <a href="<?= PROOT; ?>WorkOrders/edit/<?= (int)$w['c0d']; ?>" class="btn btn-sm btn-primary"><i class="fas fa-pen me-1"></i>Edit</a>
    <?php endif; ?>
  </div>
</div>

<?= flashHtml(); ?>

<?php if ($w['status'] === 'cancelled' && $w['cancel_reason']): ?>
  <div class="alert alert-warning py-2 small"><i class="fas fa-ban me-1"></i><strong>Cancelled:</strong> <?= htmlspecialchars($w['cancel_reason']); ?></div>
<?php endif; ?>

<!-- ── Lifecycle actions ── -->
<div class="card border-0 shadow-sm mb-3">
  <div class="card-body py-2 d-flex flex-wrap gap-2 align-items-center">
    <span class="text-uppercase text-muted small me-2"><i class="fas fa-play-circle me-1"></i>Actions</span>
    <?php if ($w['status'] === 'open'):        ?><button type="button" class="btn btn-sm btn-info text-white" onclick="act('start')"><i class="fas fa-play me-1"></i>Start work</button><?php endif; ?>
    <?php if ($w['status'] === 'in_progress'): ?><button type="button" class="btn btn-sm btn-primary"        onclick="act('complete')"><i class="fas fa-check me-1"></i>Mark complete</button><?php endif; ?>
    <?php if (in_array($w['status'], ['completed','in_progress'], true)): ?>
      <button type="button" class="btn btn-sm btn-success" onclick="doClose()" title="Posts JE Dr Maintenance / Cr AP"><i class="fas fa-check-double me-1"></i>Close &amp; post JE</button>
    <?php endif; ?>
    <?php if (in_array($w['status'], ['open','in_progress','completed'], true)): ?>
      <button type="button" class="btn btn-sm btn-outline-danger" onclick="doCancel()"><i class="fas fa-ban me-1"></i>Cancel</button>
    <?php endif; ?>
    <span class="ms-auto text-muted small">
      Total: <strong><?= htmlspecialchars($w['currency']); ?> <?= number_format((float)$w['total_cost'], 2, '.', ','); ?></strong>
    </span>
  </div>
</div>

<div class="row g-3">
  <!-- ── Details ── -->
  <div class="col-lg-5">
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Details</h6>
        <dl class="row mb-0 small">
          <dt class="col-5 text-muted fw-normal">Truck</dt>       <dd class="col-7"><?= htmlspecialchars($w['truck_reg']); ?><?php if ($w['make']): ?> · <?= htmlspecialchars(trim($w['make'] . ' ' . $w['model'])); ?><?php endif; ?></dd>
          <dt class="col-5 text-muted fw-normal">Vendor</dt>      <dd class="col-7"><?= htmlspecialchars($w['vendor_name'] ?: 'Internal workshop'); ?></dd>
          <dt class="col-5 text-muted fw-normal">Kind</dt>        <dd class="col-7" style="text-transform:capitalize;"><?= htmlspecialchars($w['kind']); ?></dd>
          <?php if ($w['opened_km']): ?><dt class="col-5 text-muted fw-normal">Odometer at open</dt><dd class="col-7"><?= number_format((int)$w['opened_km']); ?> km</dd><?php endif; ?>
          <?php if ($w['started_at']): ?><dt class="col-5 text-muted fw-normal">Started</dt><dd class="col-7"><?= humanDateTime($w['started_at']); ?></dd><?php endif; ?>
          <?php if ($w['completed_at']): ?><dt class="col-5 text-muted fw-normal">Completed</dt><dd class="col-7"><?= humanDateTime($w['completed_at']); ?></dd><?php endif; ?>
          <?php if ($w['closed_at']): ?><dt class="col-5 text-muted fw-normal">Closed</dt><dd class="col-7"><?= humanDateTime($w['closed_at']); ?></dd><?php endif; ?>
          <?php if ($w['downtime_hrs']): ?><dt class="col-5 text-muted fw-normal">Downtime</dt><dd class="col-7"><?= number_format((float)$w['downtime_hrs'], 1); ?> hrs</dd><?php endif; ?>
          <?php if ($w['je_no']): ?>
            <hr class="my-2">
            <dt class="col-5 text-muted fw-normal">Journal</dt><dd class="col-7"><a href="<?= PROOT; ?>Journals/view/<?= (int)$w['je_id']; ?>" class="font-monospace"><?= htmlspecialchars($w['je_no']); ?></a></dd>
          <?php endif; ?>
        </dl>
      </div>
    </div>

    <div class="card border-0 shadow-sm">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Diagnosis &amp; Work</h6>
        <?php if ($w['fault_description']): ?>
          <div class="mb-2"><span class="text-uppercase text-muted small">Fault:</span><div class="small"><?= nl2br(htmlspecialchars($w['fault_description'])); ?></div></div>
        <?php endif; ?>
        <?php if ($w['work_performed']): ?>
          <div><span class="text-uppercase text-muted small">Work performed:</span><div class="small"><?= nl2br(htmlspecialchars($w['work_performed'])); ?></div></div>
        <?php endif; ?>
        <?php if (!$w['fault_description'] && !$w['work_performed']): ?>
          <p class="text-muted small mb-0 fst-italic">Nothing recorded yet.</p>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- ── Parts + costs ── -->
  <div class="col-lg-7">
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <div class="d-flex align-items-center justify-content-between mb-3">
          <h6 class="text-uppercase text-muted small mb-0"><i class="fas fa-tools me-1"></i>Parts <span class="text-muted">· <?= count($parts); ?></span></h6>
          <?php if (!in_array($w['status'], ['closed','cancelled'], true)): ?>
            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="collapse" data-bs-target="#addPartPanel"><i class="fas fa-plus me-1"></i>Add part</button>
          <?php endif; ?>
        </div>

        <?php if (!in_array($w['status'], ['closed','cancelled'], true)): ?>
          <div id="addPartPanel" class="collapse mb-3">
            <form method="POST" action="<?= PROOT; ?>WorkOrders/addPart/<?= (int)$w['c0d']; ?>" class="border rounded p-3 bg-light">
              <?= csrf_field(); ?>
              <div class="row g-2">
                <div class="col-md-4"><label class="form-label small mb-1">Part name <span class="text-danger">*</span></label>
                  <input type="text" name="part_name" class="form-control form-control-sm" required></div>
                <div class="col-md-3"><label class="form-label small mb-1">Part #</label>
                  <input type="text" name="part_no" class="form-control form-control-sm"></div>
                <div class="col-md-2"><label class="form-label small mb-1">Category</label>
                  <select name="category" class="form-select form-select-sm">
                    <?php foreach (['spare_parts'=>'Spare parts','tyres'=>'Tyres','batteries'=>'Batteries','lubricants'=>'Lubricants','consumables'=>'Consumables'] as $k=>$vv): ?>
                      <option value="<?= $k; ?>"><?= $vv; ?></option>
                    <?php endforeach; ?>
                  </select></div>
                <div class="col-md-1"><label class="form-label small mb-1">Qty</label>
                  <input type="text" name="qty" class="form-control form-control-sm js-num" value="1"></div>
                <div class="col-md-2"><label class="form-label small mb-1">Unit cost</label>
                  <input type="text" name="unit_cost" class="form-control form-control-sm js-money"></div>
                <div class="col-12 d-flex gap-2 justify-content-end pt-2">
                  <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#addPartPanel">Cancel</button>
                  <button class="btn btn-sm btn-primary"><i class="fas fa-plus me-1"></i>Add</button>
                </div>
              </div>
            </form>
          </div>
        <?php endif; ?>

        <div class="table-responsive">
          <table class="table table-sm align-middle mb-0">
            <thead class="table-light">
              <tr><th>Part</th><th>Category</th><th class="money">Qty</th><th class="money">Unit</th><th class="money">Total</th><th></th></tr>
            </thead>
            <tbody>
              <?php foreach ($parts as $p): ?>
                <tr>
                  <td class="small"><?= htmlspecialchars($p['part_name']); ?><?php if ($p['part_no']): ?><div class="text-muted font-monospace small"><?= htmlspecialchars($p['part_no']); ?></div><?php endif; ?></td>
                  <td class="small"><span class="badge bg-light text-dark border"><?= htmlspecialchars(ucwords(str_replace('_',' ',$p['category']))); ?></span></td>
                  <td class="money small"><?= number_format((float)$p['qty'], 2); ?></td>
                  <td class="money small"><?= number_format((float)$p['unit_cost'], 0, '.', ','); ?></td>
                  <td class="money"><?= number_format((float)$p['total_cost'], 0, '.', ','); ?></td>
                  <td class="text-end">
                    <?php if (!in_array($w['status'], ['closed','cancelled'], true)): ?>
                      <button type="button" class="btn btn-sm btn-outline-danger" onclick="delPart(<?= (int)$p['c0d']; ?>, '<?= htmlspecialchars(addslashes($p['part_name'])); ?>')"><i class="fas fa-trash"></i></button>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if (empty($parts)): ?>
                <tr><td colspan="6" class="text-center text-muted py-3 small fst-italic">No parts recorded yet.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- ── Costs ── -->
    <div class="card border-0 shadow-sm">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3">Cost Summary (<?= htmlspecialchars($w['currency']); ?>)</h6>
        <dl class="row mb-0 small">
          <dt class="col-6 text-muted fw-normal">Parts</dt>   <dd class="col-6 money"><?= number_format((float)$w['parts_cost'], 2, '.', ','); ?></dd>
          <dt class="col-6 text-muted fw-normal">Labour<?php if ($w['labour_hours']): ?> <span class="text-muted small">(<?= number_format((float)$w['labour_hours'], 2); ?> hrs × <?= number_format((float)$w['labour_rate'], 0); ?>)</span><?php endif; ?></dt>
          <dd class="col-6 money"><?= number_format((float)$w['labour_cost'], 2, '.', ','); ?></dd>
          <dt class="col-6 text-muted fw-normal">External invoice</dt><dd class="col-6 money"><?= number_format((float)$w['external_cost'], 2, '.', ','); ?></dd>
          <hr class="my-2">
          <dt class="col-6 fw-semibold">Total</dt><dd class="col-6 money fw-semibold"><?= htmlspecialchars($w['currency']); ?> <?= number_format((float)$w['total_cost'], 2, '.', ','); ?></dd>
        </dl>
      </div>
    </div>
  </div>
</div>

<!-- Hidden forms -->
<form id="actForm" method="POST" action="" class="d-none">
  <?= csrf_field(); ?>
  <input type="hidden" name="cancel_reason"  id="fReason">
  <input type="hidden" name="work_performed" id="fWorkPerformed">
  <input type="hidden" name="close_date"     id="fCloseDate">
</form>
<form id="delPartForm" method="POST" action="" class="d-none"><?= csrf_field(); ?></form>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
const WO_ID = <?= (int)$w['c0d']; ?>;
const PROOT = '<?= PROOT; ?>';

function submitAct(verb, extra) {
    const f = document.getElementById('actForm');
    f.action = PROOT + 'WorkOrders/' + verb + '/' + WO_ID;
    if (extra) for (const [k,v] of Object.entries(extra)) { const el = document.getElementById(k); if (el) el.value = v; }
    f.submit();
}

function act(verb) {
    const cfg = {
        start:    { title:'Start work?',    msg:'Truck will be marked as <strong>in maintenance</strong>.', btn:'Start',        cls:'btn-info',    colour:'blue' },
        complete: { title:'Mark complete?', msg:'Work is done. Close-out and JE post comes next.',           btn:'Mark complete',cls:'btn-primary', colour:'blue' }
    }[verb];
    $.confirm({ title:cfg.title, content:cfg.msg, type:cfg.colour,
        buttons: { go: { text:cfg.btn, btnClass:cfg.cls, action: () => submitAct(verb) }, back: function(){} }
    });
}

function doClose() {
    $.confirm({
        title: 'Close work order?',
        content: `
            <div class="mb-2 small text-muted">This posts one JE: <strong>Dr Maintenance accounts</strong> (split by parts category, plus labour and external) / <strong>Cr 2010 Accounts Payable</strong>. The truck is released back to active.</div>
            <label class="form-label small mb-1">Work performed (optional — updates the record)</label>
            <textarea id="wpNote" class="form-control form-control-sm mb-2" rows="2" placeholder="Anything to record about what was done"></textarea>
            <label class="form-label small mb-1">Close date</label>
            <input type="date" id="cdInput" class="form-control form-control-sm" value="<?= date('Y-m-d'); ?>">
        `,
        type: 'green',
        buttons: {
            closeIt: { text: '<i class="fas fa-check-double me-1"></i>Close & post JE', btnClass: 'btn-success', action: function() {
                submitAct('close', { fWorkPerformed: document.getElementById('wpNote').value, fCloseDate: document.getElementById('cdInput').value });
            }},
            back: function(){}
        }
    });
}

function doCancel() {
    $.confirm({
        title: 'Cancel work order?',
        content: '<label class="form-label small">Reason <span class="text-danger">*</span></label><textarea id="cReason" class="form-control form-control-sm" rows="3"></textarea>',
        type: 'red',
        buttons: {
            cancel: { text: 'Cancel WO', btnClass: 'btn-danger', action: function() {
                const r = document.getElementById('cReason').value.trim();
                if (!r) { $.alert('Please enter a reason.'); return false; }
                submitAct('cancel', { fReason: r });
            }},
            back: { text: 'Back' }
        }
    });
}

function delPart(id, name) {
    $.confirm({
        title: 'Remove part?',
        content: 'Remove <strong>' + name + '</strong> from this work order? Cost totals will update automatically.',
        type: 'red',
        buttons: {
            remove: { text: 'Remove', btnClass: 'btn-danger', action: function() {
                const f = document.getElementById('delPartForm');
                f.action = PROOT + 'WorkOrders/deletePart/' + id;
                f.submit();
            }},
            back: function(){}
        }
    });
}
</script>
<?php $this->end(); ?>
