<?php $this->start('body'); ?>
<?php $w = $this->data['w']; $items = $this->data['items']; $history = $this->data['history']; ?>
<?php
  $bg  = ['draft'=>'secondary','submitted'=>'warning','approved'=>'primary','sourcing'=>'info','ready'=>'success','wo_created'=>'primary','completed'=>'success','rejected'=>'danger','cancelled'=>'dark'][$w['status']] ?? 'secondary';
  $urg = ['low'=>['light','text-muted'],'normal'=>['light','text-muted'],'high'=>['warning','text-dark'],'breakdown'=>['danger','text-white']][$w['urgency']] ?? ['light','text-muted'];
  $canEditHeader = !in_array($w['status'], ['wo_created','completed','rejected','cancelled'], true);
  $canEditItems  = in_array($w['status'], ['draft','submitted','approved','sourcing'], true);
?>

<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-hand-paper me-2 text-muted"></i><?= htmlspecialchars($w['wr_no']); ?>
      <span class="badge bg-<?= $bg; ?> ms-2" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars(str_replace('_',' ', $w['status'])); ?></span>
      <span class="badge bg-<?= $urg[0]; ?> <?= $urg[1]; ?><?= $urg[0]==='light'?' border':''; ?> ms-1" style="font-size:.65em;vertical-align:middle;text-transform:capitalize;"><?= htmlspecialchars($w['urgency']); ?></span>
    </h5>
    <div class="text-muted small">
      <a href="<?= PROOT; ?>Trucks/view/<?= (int)$w['truck_id']; ?>"><?= htmlspecialchars($w['truck_reg']); ?></a>
      <?php if ($w['driver_name']): ?> · reported by <a href="<?= PROOT; ?>Drivers/view/<?= (int)$w['driver_id']; ?>"><?= htmlspecialchars($w['driver_name']); ?></a><?php endif; ?>
      <?php if ($w['reported_at']): ?> · <?= humanDateTime($w['reported_at']); ?><?php endif; ?>
    </div>
  </div>
  <div class="d-flex gap-2">
    <a href="<?= PROOT; ?>WorkRequests" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    <?php if ($canEditHeader): ?><a href="<?= PROOT; ?>WorkRequests/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'] === 'rejected' && $w['reject_reason']): ?>
  <div class="alert alert-danger py-2 small"><i class="fas fa-times-circle me-1"></i><strong>Rejected:</strong> <?= htmlspecialchars($w['reject_reason']); ?></div>
<?php endif; ?>
<?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; ?>
<?php if ($w['wo_no']): ?>
  <div class="alert alert-primary py-2 small"><i class="fas fa-wrench me-1"></i>Linked Work Order: <a href="<?= PROOT; ?>WorkOrders/view/<?= (int)$w['wo_id']; ?>" class="fw-semibold"><?= htmlspecialchars($w['wo_no']); ?></a></div>
<?php endif; ?>

<!-- ── Action bar per status ────────────────────────────── -->
<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'] === 'draft'): ?>
      <button type="button" class="btn btn-sm btn-primary" onclick="act('submit','Submit for approval?','Sends this request to Ops Manager. Add items first if you know what is needed.','Submit','btn-primary','blue')"><i class="fas fa-paper-plane me-1"></i>Submit for approval</button>
    <?php endif; ?>
    <?php if ($w['status'] === 'submitted'): ?>
      <button type="button" class="btn btn-sm btn-success" onclick="doApprove()"><i class="fas fa-check me-1"></i>Approve (Ops Manager)</button>
      <button type="button" class="btn btn-sm btn-outline-danger" onclick="doReject()"><i class="fas fa-times me-1"></i>Reject</button>
    <?php endif; ?>
    <?php if ($w['status'] === 'approved'): ?>
      <button type="button" class="btn btn-sm btn-info text-white" onclick="act('startSourcing','Start sourcing?','Procurement takes ownership. Update items with vendors and actual costs as parts come in.','Start sourcing','btn-info','blue')"><i class="fas fa-truck me-1"></i>Start sourcing</button>
    <?php endif; ?>
    <?php if (in_array($w['status'], ['approved','sourcing'], true)): ?>
      <button type="button" class="btn btn-sm btn-success" onclick="doMarkReady()"><i class="fas fa-check-double me-1"></i>Parts ready</button>
    <?php endif; ?>
    <?php if ($w['status'] === 'ready'): ?>
      <button type="button" class="btn btn-sm btn-primary" onclick="act('convertToWo','Convert to Work Order?','Creates a new WO with the truck + items from this request. Fleet Manager can then start work.','Convert to WO','btn-primary','blue')"><i class="fas fa-wrench me-1"></i>Convert to Work Order</button>
    <?php endif; ?>
    <?php if (in_array($w['status'], ['draft','submitted','approved','sourcing','ready'], true)): ?>
      <button type="button" class="btn btn-sm btn-outline-secondary" onclick="doCancel()"><i class="fas fa-ban me-1"></i>Cancel</button>
    <?php endif; ?>

    <span class="ms-auto text-muted small">
      <?php if ((float)$w['estimated_cost'] > 0): ?>Est: <strong><?= htmlspecialchars($w['currency']); ?> <?= number_format((float)$w['estimated_cost'], 2, '.', ','); ?></strong><?php endif; ?>
      <?php if ((float)$w['approved_amount'] > 0): ?> · Approved: <strong><?= htmlspecialchars($w['currency']); ?> <?= number_format((float)$w['approved_amount'], 2, '.', ','); ?></strong><?php endif; ?>
    </span>
  </div>
</div>

<div class="row g-3">
  <!-- ── Left: fault 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">Fault Details</h6>
        <dl class="row mb-0 small">
          <dt class="col-4 text-muted fw-normal">Urgency</dt><dd class="col-8" style="text-transform:capitalize;"><?= htmlspecialchars($w['urgency']); ?></dd>
          <?php if ($w['fault_location']): ?><dt class="col-4 text-muted fw-normal">Location</dt><dd class="col-8"><?= htmlspecialchars($w['fault_location']); ?></dd><?php endif; ?>
          <?php if ($w['truck_odometer']): ?><dt class="col-4 text-muted fw-normal">Odometer</dt><dd class="col-8"><?= number_format((int)$w['truck_odometer']); ?> km</dd><?php endif; ?>
          <?php if ($w['approved_amount']): ?><dt class="col-4 text-muted fw-normal">Approved amount</dt><dd class="col-8"><?= htmlspecialchars($w['currency']); ?> <?= number_format((float)$w['approved_amount'], 2, '.', ','); ?></dd><?php endif; ?>
          <?php if ($w['approval_notes']): ?><dt class="col-4 text-muted fw-normal">Approval notes</dt><dd class="col-8"><?= htmlspecialchars($w['approval_notes']); ?></dd><?php endif; ?>
          <?php if ($w['sourced_vendor_name']): ?><dt class="col-4 text-muted fw-normal">Sourced vendor</dt><dd class="col-8"><?= htmlspecialchars($w['sourced_vendor_name']); ?></dd><?php endif; ?>
          <?php if ($w['sourcing_notes']): ?><dt class="col-4 text-muted fw-normal">Sourcing notes</dt><dd class="col-8"><?= htmlspecialchars($w['sourcing_notes']); ?></dd><?php endif; ?>
        </dl>

        <?php if ($w['symptom']): ?>
          <hr class="my-2">
          <div class="text-uppercase text-muted small">Symptom</div>
          <div class="small"><?= nl2br(htmlspecialchars($w['symptom'])); ?></div>
        <?php endif; ?>
        <?php if ($w['notes']): ?>
          <hr class="my-2">
          <div class="text-uppercase text-muted small">Notes</div>
          <div class="small"><?= nl2br(htmlspecialchars($w['notes'])); ?></div>
        <?php endif; ?>
      </div>
    </div>

    <div class="card border-0 shadow-sm">
      <div class="card-body">
        <h6 class="text-uppercase text-muted small mb-3"><i class="fas fa-history me-1"></i>History</h6>
        <?php if (empty($history)): ?>
          <p class="text-muted small mb-0 fst-italic">No transitions yet.</p>
        <?php else: ?>
          <ul class="list-unstyled mb-0 small">
            <?php foreach ($history as $h): ?>
              <li class="mb-2 ps-3" style="border-left: 2px solid var(--pacific-navy);">
                <div class="fw-semibold" style="text-transform:capitalize;"><?= htmlspecialchars(str_replace('_',' ', $h['to_status'])); ?><?php if ($h['from_status']): ?><span class="text-muted"> ← <?= htmlspecialchars(str_replace('_',' ', $h['from_status'])); ?></span><?php endif; ?></div>
                <div class="text-muted small"><?= humanDateTime($h['action_at']); ?><?php if ($h['actor_name']): ?> · <?= htmlspecialchars($h['actor_name']); ?><?php endif; ?></div>
                <?php if ($h['note']): ?><div class="small"><?= htmlspecialchars($h['note']); ?></div><?php endif; ?>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- ── Right: items + add form ── -->
  <div class="col-lg-7">
    <div class="card border-0 shadow-sm">
      <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-list me-1"></i>Parts &amp; Services Needed <span class="text-muted">· <?= count($items); ?></span></h6>
          <?php if ($canEditItems): ?>
            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="collapse" data-bs-target="#addItemPanel"><i class="fas fa-plus me-1"></i>Add item</button>
          <?php endif; ?>
        </div>

        <?php if ($canEditItems): ?>
          <div id="addItemPanel" class="collapse mb-3">
            <form method="POST" action="<?= PROOT; ?>WorkRequests/addItem/<?= (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">Description <span class="text-danger">*</span></label>
                  <input type="text" name="description" class="form-control form-control-sm" required placeholder="e.g. Heavy-duty battery 12V 200Ah"></div>
                <div class="col-md-2"><label class="form-label small mb-1">Type</label>
                  <select name="item_type" class="form-select form-select-sm">
                    <?php foreach (['part'=>'Part','labour'=>'Labour','external_service'=>'External service'] as $k=>$v): ?>
                      <option value="<?= $k; ?>"><?= $v; ?></option>
                    <?php endforeach; ?>
                  </select></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=>$v): ?>
                      <option value="<?= $k; ?>"><?= $v; ?></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-1"><label class="form-label small mb-1">UoM</label>
                  <select name="uom" class="form-select form-select-sm">
                    <?php foreach (['unit','hours','set','pair','box','litre'] as $u): ?>
                      <option value="<?= $u; ?>"><?= $u; ?></option>
                    <?php endforeach; ?>
                  </select></div>
                <div class="col-md-2"><label class="form-label small mb-1">Est. unit cost</label>
                  <input type="text" name="unit_cost_est" class="form-control form-control-sm js-money"></div>
                <div class="col-md-8"><label class="form-label small mb-1">Notes</label>
                  <input type="text" name="notes" class="form-control form-control-sm"></div>
                <div class="col-md-4 d-flex align-items-end justify-content-end gap-2">
                  <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#addItemPanel">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>#</th><th>Item</th><th>Type · Category</th><th class="money">Qty</th><th class="money">Unit est.</th><th class="money">Total est.</th><th>Sourcing</th><th></th></tr>
            </thead>
            <tbody>
              <?php foreach ($items as $it): ?>
                <?php $srcBg = ['not_started'=>'light','in_stock'=>'success','sourced'=>'info','delivered'=>'success'][$it['sourcing_status']] ?? 'light'; ?>
                <tr>
                  <td class="small text-muted"><?= (int)$it['seq_no']; ?></td>
                  <td class="small"><strong><?= htmlspecialchars($it['description']); ?></strong><?php if ($it['notes']): ?><div class="text-muted"><?= htmlspecialchars($it['notes']); ?></div><?php endif; ?></td>
                  <td class="small"><?= htmlspecialchars(ucfirst($it['item_type'])); ?><div class="text-muted"><?= htmlspecialchars(ucwords(str_replace('_',' ',$it['category']))); ?></div></td>
                  <td class="money small"><?= number_format((float)$it['qty'], (float)$it['qty']==(int)$it['qty']?0:2); ?> <span class="text-muted"><?= htmlspecialchars($it['uom']); ?></span></td>
                  <td class="money small"><?= number_format((float)$it['unit_cost_est'], 0, '.', ','); ?></td>
                  <td class="money"><?= number_format((float)$it['total_est'], 0, '.', ','); ?></td>
                  <td class="small"><span class="badge bg-<?= $srcBg; ?><?= $srcBg==='light'?' text-muted border':''; ?>" style="text-transform:capitalize;"><?= htmlspecialchars(str_replace('_',' ',$it['sourcing_status'])); ?></span><?php if ($it['vendor_name']): ?><div class="text-muted"><?= htmlspecialchars($it['vendor_name']); ?></div><?php endif; ?></td>
                  <td class="text-end">
                    <?php if ($canEditItems): ?>
                      <button type="button" class="btn btn-sm btn-outline-danger js-del-item" data-id="<?= (int)$it['c0d']; ?>" data-name="<?= htmlspecialchars($it['description']); ?>"><i class="fas fa-trash"></i></button>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if (empty($items)): ?>
                <tr><td colspan="8" class="text-center text-muted py-3 small fst-italic">No items listed — add parts, labour or external services above.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="text-end mt-3">
  <button type="button" class="btn btn-sm btn-outline-danger" onclick="doDelete()"><i class="fas fa-trash me-1"></i>Delete record</button>
</div>

<!-- Hidden forms -->
<form id="actForm" method="POST" action="" class="d-none">
  <?= csrf_field(); ?>
  <input type="hidden" name="cancel_reason"     id="fCancelReason">
  <input type="hidden" name="reject_reason"     id="fRejectReason">
  <input type="hidden" name="approved_amount"   id="fApprovedAmount">
  <input type="hidden" name="approval_notes"    id="fApprovalNotes">
  <input type="hidden" name="sourced_vendor_id" id="fSourcedVendor">
  <input type="hidden" name="sourcing_notes"    id="fSourcingNotes">
</form>
<form id="delItemForm" method="POST" action="" class="d-none"><?= csrf_field(); ?></form>
<form id="delForm" method="POST" action="<?= PROOT; ?>WorkRequests/delete/<?= (int)$w['c0d']; ?>" class="d-none"><?= csrf_field(); ?></form>

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

document.querySelectorAll('.js-num').forEach(el => new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 3 }));
document.querySelectorAll('.js-money').forEach(el => new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 2 }));

function submitAct(verb, extra) {
    const f = document.getElementById('actForm');
    f.action = PROOT + 'WorkRequests/' + verb + '/' + WR_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, title, msg, btn, cls, colour) {
    $.confirm({ title, content: msg, type: colour, buttons: { go: { text: btn, btnClass: cls, action: () => submitAct(verb) }, back: function(){} } });
}

function doApprove() {
    const estValue = <?= (float)$w['estimated_cost']; ?>;
    $.confirm({
        title: 'Approve request?',
        content: `
            <div class="mb-2 small text-muted">Approves the request and hands it off to Procurement to source parts.</div>
            <label class="form-label small mb-1">Approved amount (${CURRENCY})</label>
            <input type="text" id="apAmt" class="form-control form-control-sm mb-2" value="${estValue.toFixed(2)}">
            <label class="form-label small mb-1">Approval notes (optional)</label>
            <textarea id="apNotes" class="form-control form-control-sm" rows="2" placeholder="Cap, conditions, urgency justification..."></textarea>
        `,
        type: 'green',
        onContentReady: function() { const el = document.getElementById('apAmt'); if (el && typeof Cleave !== 'undefined') new Cleave(el, { numeral: true, numeralThousandsGroupStyle: 'thousand', numeralDecimalScale: 2 }); },
        buttons: {
            go: { text: 'Approve', btnClass: 'btn-success', action: function() {
                submitAct('approve', { fApprovedAmount: document.getElementById('apAmt').value.replace(/,/g,''), fApprovalNotes: document.getElementById('apNotes').value });
            }},
            back: function(){}
        }
    });
}

function doReject() {
    $.confirm({
        title: 'Reject request?',
        content: '<label class="form-label small">Reason <span class="text-danger">*</span></label><textarea id="rjReason" class="form-control form-control-sm" rows="3"></textarea>',
        type: 'red',
        buttons: {
            go: { text: 'Reject', btnClass: 'btn-danger', action: function() {
                const r = document.getElementById('rjReason').value.trim();
                if (!r) { $.alert('Please enter a reason.'); return false; }
                submitAct('reject', { fRejectReason: r });
            }},
            back: function(){}
        }
    });
}

function doMarkReady() {
    const vendorOpts = <?= json_encode(array_map(fn($v)=>['id'=>$v['c0d'],'name'=>$v['vendor_name']], $this->data['vendors'])); ?>;
    const opts = vendorOpts.map(v => `<option value="${v.id}">${v.name}</option>`).join('');
    $.confirm({
        title: 'Mark parts ready?',
        content: `
            <div class="mb-2 small text-muted">Parts are on hand and Fleet Manager can convert this to a Work Order.</div>
            <label class="form-label small mb-1">Sourced from vendor (primary)</label>
            <select id="srVendor" class="form-select form-select-sm mb-2"><option value="">— none / from stock —</option>${opts}</select>
            <label class="form-label small mb-1">Sourcing notes (optional)</label>
            <textarea id="srNotes" class="form-control form-control-sm" rows="2" placeholder="Delivery date, PO ref, etc"></textarea>
        `,
        type: 'green',
        buttons: {
            go: { text: 'Mark ready', btnClass: 'btn-success', action: function() {
                submitAct('markReady', { fSourcedVendor: document.getElementById('srVendor').value, fSourcingNotes: document.getElementById('srNotes').value });
            }},
            back: function(){}
        }
    });
}

function doCancel() {
    $.confirm({
        title: 'Cancel request?',
        content: '<label class="form-label small">Reason (optional)</label><textarea id="cnReason" class="form-control form-control-sm" rows="3"></textarea>',
        type: 'red',
        buttons: { go: { text: 'Cancel WR', btnClass: 'btn-outline-secondary', action: function() {
            submitAct('cancel', { fCancelReason: document.getElementById('cnReason').value });
        }}, back: function(){} }
    });
}

function doDelete() {
    $.confirm({
        title: 'Delete this record?',
        content: 'Soft-deletes the request. Any linked Work Order is unaffected.',
        type: 'red',
        buttons: { remove: { text: 'Delete', btnClass: 'btn-danger', action: () => document.getElementById('delForm').submit() }, back: function(){} }
    });
}

document.querySelectorAll('.js-del-item').forEach(btn => btn.addEventListener('click', function() {
    const id = btn.getAttribute('data-id'); const name = btn.getAttribute('data-name');
    $.confirm({ title: 'Remove item?', content: 'Remove <strong>' + name + '</strong>?', type: 'red',
        buttons: { remove: { text: 'Remove', btnClass: 'btn-danger', action: function() {
            const f = document.getElementById('delItemForm');
            f.action = PROOT + 'WorkRequests/deleteItem/' + id;
            f.submit();
        }}, back: function(){} }
    });
}));
</script>
<?php $this->end(); ?>
