<?php
// ---------- prepare JSON payloads for Vue apps ----------
$woId   = (int) ($wo['work_order_id'] ?? 0);
$woJson = json_encode($wo, JSON_UNESCAPED_SLASHES);

$rawTasks = $tasks ?? [];
$tasksJson = json_encode($rawTasks, JSON_UNESCAPED_SLASHES);

$rawPartsUsed = $partsUsed ?? [];
$partsUsedJson = json_encode($rawPartsUsed, JSON_UNESCAPED_SLASHES);

$rawPartOptions = $partOptions ?? [];
$partOptionsJson = json_encode($rawPartOptions, JSON_UNESCAPED_SLASHES);

$initialMaterialCost = (float) ($materialCost ?? 0);

$rawPermits = $permits ?? [];
$permitsJson = json_encode($rawPermits, JSON_UNESCAPED_SLASHES);

$csrfVal  = e($csrf ?? '');
$flashMsg = !empty($flash) ? json_encode($flash, JSON_UNESCAPED_SLASHES) : 'null';

$pdfUrl       = url('/WorkOrders/pdf/' . $woId);
$pdfViewUrl   = $pdfUrl;  // same — bakes inline view via mPDF
$baseUrl      = url('/');
$apiBaseUrl   = rtrim($baseUrl, '/') . '/api/v1/work-orders';
?>

<div id="woShowApp" v-cloak>
    <!-- ── flash message (auto-dismisses after 5 s) ── -->
    <div v-if="flash" class="alert alert-info py-2 small alert-dismissible fade show" role="alert">
        {{ flash }}<button type="button" class="btn-close" @click="flash = null" aria-label="Close"></button>
    </div>

    <!-- ── Header bar ── -->
    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <h5 class="fw-bold mb-0"><i class="fas fa-clipboard-check me-2 text-primary"></i>{{ wo.code || '#' + wo.work_order_id }} · {{ wo.title }}</h5>
        <div class="d-flex gap-2 flex-wrap">
            <a class="btn btn-sm btn-outline-primary" :href="'<?= url('/WorkOrders/edit/') ?>' + wo.work_order_id"><i class="fas fa-pen me-1"></i>Edit</a>
            <button class="btn btn-sm btn-outline-info" @click="openPdfModal"><i class="fas fa-file-pdf me-1"></i>PDF</button>
            <a class="btn btn-sm btn-outline-secondary" href="<?= url('/WorkOrders') ?>"><i class="fas fa-arrow-left me-1"></i>Back</a>
            <template v-if="wo.status !== 'completed' && wo.status !== 'cancelled'">
                <form method="post" :action="'<?= url('/WorkOrders/close/') ?>' + wo.work_order_id" class="rs-confirm-submit d-inline" data-confirm-title="Close this checklist?" data-confirm-body="Mark this work order as completed. You can still view it afterwards." data-confirm-ok="Close" data-confirm-danger="0">
                    <input type="hidden" name="_csrf" value="<?= $csrfVal ?>">
                    <button type="submit" class="btn btn-sm btn-success"><i class="fas fa-check-circle me-1"></i>Close Checklist</button>
                </form>
            </template>
            <template v-else>
                <span class="badge bg-secondary text-uppercase align-self-center">{{ wo.status }}</span>
            </template>
        </div>
    </div>

    <!-- ── Permit gate alerts ── -->
    <div v-if="wo.permit_required == 1" class="mb-3">
        <div v-if="hasApprovedPermit" class="alert alert-success py-2 small">
            <i class="fas fa-shield-halved me-1"></i><strong>Permit in place</strong> — this WO may proceed.
        </div>
        <div v-else class="alert alert-danger py-2 small">
            <i class="fas fa-shield-halved me-1"></i><strong>Permit required</strong> — this WO cannot start or complete until a linked permit is approved.
            <a class="btn btn-sm btn-outline-danger ms-2" :href="'<?= url('/Permits/create?wo=') ?>' + wo.work_order_id"><i class="fas fa-plus me-1"></i>Request permit</a>
        </div>
    </div>

    <!-- ── WO detail card ── -->
    <div class="rs-card p-3 mb-3">
        <dl class="rs-def row g-2 mb-0">
            <div class="col-md-3"><dt>Type</dt><dd><span class="badge bg-secondary text-uppercase">{{ wo.wo_type }}</span></dd></div>
            <div class="col-md-3"><dt>Priority</dt><dd><span class="badge bg-secondary text-uppercase">{{ wo.priority }}</span></dd></div>
            <div class="col-md-3"><dt>Status</dt><dd><span class="badge bg-secondary text-uppercase">{{ wo.status }}</span></dd></div>
            <div class="col-md-3"><dt>Assigned</dt><dd>{{ wo.assigned_username || 'unassigned' }}</dd></div>
            <div class="col-md-3"><dt>Site</dt><dd>{{ wo.site_name || '—' }}</dd></div>
            <div class="col-md-3"><dt>Asset</dt><dd>{{ wo.asset_name || '—' }}</dd></div>
            <div class="col-md-3"><dt>Related Incident</dt>
                <dd>
                    <a v-if="wo.incident_id" :href="'<?= url('/Incidents/show/') ?>' + wo.incident_id">{{ wo.incident_title }}</a>
                    <span v-else>—</span>
                </dd>
            </div>
            <div class="col-md-3"><dt>Scheduled</dt><dd>{{ wo.scheduled_at || '—' }}</dd></div>
            <div class="col-md-3"><dt>Due</dt><dd>{{ wo.due_at || '—' }}</dd></div>
            <div class="col-md-3"><dt>Started</dt><dd>{{ wo.started_at || '—' }}</dd></div>
            <div class="col-md-3"><dt>Completed</dt><dd>{{ wo.completed_at || '—' }}</dd></div>
            <div class="col-md-3"><dt>Est./Actual</dt><dd>{{ wo.estimated_hours || '?' }}h / {{ wo.actual_hours || '—' }}h</dd></div>
        </dl>
    </div>

    <!-- ── Description ── -->
    <div v-if="wo.description" class="rs-card p-3 mb-3">
        <h6 class="fw-bold mb-2">Description</h6>
        <p class="mb-0 small" v-html="nl2br(wo.description)"></p>
    </div>

    <!-- ── TASKS (Vue-driven, no page reload) ── -->
    <div class="rs-card p-3 mb-3">
        <div class="d-flex justify-content-between align-items-center mb-2">
            <h6 class="fw-bold mb-0">Tasks</h6>
            <span v-if="tasks.length" class="badge bg-secondary">{{ taskDoneCount }} / {{ tasks.length }}</span>
        </div>

        <p v-if="!tasks.length" class="text-muted small mb-2">No tasks yet.</p>

        <div class="wo-tasks">
            <div v-for="t in tasks" :key="t.task_id" class="wo-task" :class="{ done: t.is_done }">
                <div class="wo-task-head">
                    <div>
                        <strong>{{ t.title }}</strong>
                        <span v-if="t.is_required" class="text-danger">*</span>
                        <span class="badge bg-secondary text-uppercase ms-1" style="font-size:.55rem;">{{ t.input_type }}</span>
                        <span v-if="photoBadge(t)[0]" class="badge ms-1 text-uppercase" :class="photoBadge(t)[0]" style="font-size:.55rem;">
                            <i class="fas fa-camera me-1"></i>{{ photoBadge(t)[1] }}
                        </span>
                        <small v-if="t.is_done" class="text-muted d-block">
                            Done by {{ t.done_username || '?' }} at {{ t.done_at }}
                            <strong v-if="t.response_value"> · {{ t.response_value }}</strong>
                        </small>
                        <small v-if="t.is_done && t.result_note" class="text-muted d-block">Note: {{ t.result_note }}</small>
                        <small v-if="t.is_done && t.remedy_note" class="text-muted d-block">Remedy: {{ t.remedy_note }}</small>
                        <div v-if="!t.is_done && t.description" class="text-muted small" v-html="nl2br(t.description)"></div>
                    </div>
                    <div class="d-flex gap-2 align-items-start">
                        <a v-if="t.is_done" href="#" @click.prevent="reopenTask(t)" class="text-muted small" title="Reopen"><i class="fas fa-rotate-left"></i></a>
                        <a href="#" @click.prevent="confirmDeleteTask(t)" class="text-danger small"><i class="fas fa-times"></i></a>
                    </div>
                </div>

                <!-- Task response form (only for incomplete tasks) -->
                <div v-if="!t.is_done">
                    <!-- checkbox → simple mark-done -->
                    <button v-if="t.input_type === 'checkbox' || t.input_type === 'photo'" @click.prevent="markTaskDone(t)" class="btn btn-sm btn-outline-success mt-2">
                        <i class="fas fa-check me-1"></i>Mark done
                    </button>

                    <!-- options / number / text → inline form -->
                    <form v-if="['options','number','text'].includes(t.input_type)" @submit.prevent="submitTaskForm(t)" class="row g-2 mt-1">
                        <input type="hidden" name="_csrf" value="<?= $csrfVal ?>">
                        <div class="col-md-4">
                            <select v-if="t.input_type === 'options'" v-model="t._response_value" class="form-select form-select-sm" :required="t.is_required">
                                <option value="">— pick —</option>
                                <option v-for="o in parseOptions(t.options_json)" :key="o" :value="o">{{ o }}</option>
                            </select>
                            <input v-else-if="t.input_type === 'number'" type="number" step="any" v-model="t._response_value" class="form-control form-control-sm" placeholder="Reading" :required="t.is_required">
                            <input v-else type="text" v-model="t._response_value" class="form-control form-control-sm" placeholder="Response" :required="t.is_required">
                        </div>
                        <div class="col-md-4"><input type="text" v-model="t._result_note" class="form-control form-control-sm" placeholder="Remarks (optional)"></div>
                        <div class="col-md-3"><input type="text" v-model="t._remedy_note" class="form-control form-control-sm" placeholder="Remedy taken (optional)"></div>
                        <div class="col-md-1"><button type="submit" class="btn btn-sm btn-success w-100" title="Complete"><i class="fas fa-check"></i></button></div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Add-task form -->
        <form @submit.prevent="addTask" class="mt-3" v-if="wo.status !== 'completed' && wo.status !== 'cancelled'">
            <input type="hidden" name="_csrf" value="<?= $csrfVal ?>">
            <div class="row g-2">
                <div class="col-md-8"><input type="text" class="form-control form-control-sm" v-model="newTaskTitle" required placeholder="e.g. Check oil level"></div>
                <div class="col-md-2"><input type="number" class="form-control form-control-sm" v-model="newTaskOrder" placeholder="Order"></div>
                <div class="col-md-2"><button type="submit" class="btn btn-sm btn-primary w-100"><i class="fas fa-plus me-1"></i>Add Task</button></div>
            </div>
        </form>
    </div>

    <!-- ── Permits ── -->
    <div v-if="wo.permit_required == 1 || permits.length" class="rs-card p-3 mb-3">
        <div class="d-flex justify-content-between align-items-center mb-2">
            <h6 class="fw-bold mb-0"><i class="fas fa-shield-halved me-1"></i>Permits</h6>
            <a class="btn btn-sm btn-outline-primary" :href="'<?= url('/Permits/create?wo=') ?>' + wo.work_order_id"><i class="fas fa-plus me-1"></i>Request permit</a>
        </div>
        <p v-if="!permits.length" class="text-muted small mb-0">No permits linked yet.</p>
        <table v-else class="table table-sm table-hover mb-0 align-middle">
            <thead><tr><th>#</th><th>Type</th><th>Title</th><th>Valid</th><th class="text-center">Status</th><th></th></tr></thead>
            <tbody>
                <tr v-for="p in permits" :key="p.permit_id">
                    <td class="small text-muted">#{{ p.permit_id }}</td>
                    <td class="small"><i v-if="p.type_icon" class="fas" :class="p.type_icon + ' me-1'"></i>{{ p.type_code }}</td>
                    <td class="small"><a :href="'<?= url('/Permits/show/') ?>' + p.permit_id">{{ p.title }}</a></td>
                    <td class="small text-muted">{{ p.valid_from ? p.valid_from.substr(0,10) : '' }} → {{ p.valid_to ? p.valid_to.substr(0,10) : '' }}</td>
                    <td class="text-center"><span class="badge text-uppercase" :class="permitBadge(p.status)" style="font-size:.6rem;">{{ p.status }}</span></td>
                    <td class="text-end"><a class="btn btn-sm btn-outline-primary" :href="'<?= url('/Permits/show/') ?>' + p.permit_id"><i class="fas fa-eye"></i></a></td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- ── Parts Consumed ── -->
    <div class="rs-card p-3 mb-3">
        <h6 class="fw-bold mb-2"><i class="fas fa-boxes-stacked me-1"></i>Parts Consumed
            <span v-if="materialCost > 0" class="badge bg-secondary ms-2">Material cost: {{ materialCost.toFixed(2) }}</span>
        </h6>
        <p v-if="!partsUsed.length" class="text-muted small mb-2">No parts logged against this WO yet.</p>
        <table v-else class="table table-sm table-hover mb-3 align-middle">
            <thead><tr><th>SKU</th><th>Name</th><th class="text-end">Qty</th><th>Unit</th><th class="text-end">Unit cost</th><th class="text-end">Line cost</th><th>When</th></tr></thead>
            <tbody>
                <tr v-for="p in partsUsed" :key="p.part_id + '_' + p.created_at">
                    <td><code class="small">{{ p.sku }}</code></td>
                    <td><a :href="'<?= url('/Parts/show/') ?>' + p.part_id">{{ p.name }}</a></td>
                    <td class="text-end">{{ formatQty(p.quantity) }}</td>
                    <td class="small">{{ p.unit }}</td>
                    <td class="text-end small">{{ parseFloat(p.unit_cost).toFixed(2) }}</td>
                    <td class="text-end"><strong>{{ parseFloat(p.line_cost).toFixed(2) }}</strong></td>
                    <td class="small text-muted">{{ p.created_at ? p.created_at.substr(0,16) : '' }}</td>
                </tr>
            </tbody>
        </table>

        <form v-if="wo.status !== 'completed' && wo.status !== 'cancelled'" @submit.prevent="consumePart" class="mb-0">
            <input type="hidden" name="_csrf" value="<?= $csrfVal ?>">
            <div class="row g-2 align-items-end">
                <div class="col-md-6"><label class="form-label">Part</label>
                    <select v-model.number="consumePartId" class="form-select form-select-sm" required>
                        <option value="">— pick part —</option>
                        <option v-for="po in partOptions" :key="po.part_id" :value="po.part_id">
                            {{ po.sku }} · {{ po.name }} (on hand {{ formatQty(po.on_hand) }} {{ po.unit }})
                        </option>
                    </select>
                </div>
                <div class="col-md-3"><label class="form-label">Quantity</label>
                    <input type="number" step="0.001" v-model.number="consumeQty" class="form-control form-control-sm" required min="0.001">
                </div>
                <div class="col-md-3"><button type="submit" class="btn btn-sm btn-primary w-100"><i class="fas fa-check me-1"></i>Consume</button></div>
            </div>
            <small class="text-muted">Unit cost is snapshot from the part row at consumption time.</small>
        </form>
    </div>

    <!-- ── Attachments (server-side rendered, still functional) ── -->
    <?php require ROOT . '/app/Views/partials/_attachments.php'; ?>

    <!-- ─────────────────────────────────────────────────────────────────
         PDF MODAL — iframe preview + download / new-tab / print buttons
         ───────────────────────────────────────────────────────────────── -->
    <div class="modal fade" id="pdfModal" tabindex="-1" aria-labelledby="pdfModalLabel" aria-hidden="true" ref="pdfModalEl">
        <div class="modal-dialog modal-xl modal-dialog-scrollable" style="max-width: 95vw;">
            <div class="modal-content">
                <div class="modal-header py-2">
                    <h6 class="modal-title" id="pdfModalLabel"><i class="fas fa-file-pdf me-2 text-danger"></i>WO-{{ wo.code || wo.work_order_id }}</h6>
                    <div class="ms-auto d-flex gap-2">
                        <a class="btn btn-sm btn-outline-primary" :href="pdfUrl" download target="_blank"><i class="fas fa-download me-1"></i>Download</a>
                        <a class="btn btn-sm btn-outline-secondary" :href="pdfUrl" target="_blank"><i class="fas fa-external-link-alt me-1"></i>Open in new tab</a>
                        <button type="button" class="btn btn-sm btn-outline-info" @click="printPdf"><i class="fas fa-print me-1"></i>Print</button>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" @click="closePdfModal"></button>
                    </div>
                </div>
                <div class="modal-body p-0" style="height: 80vh;">
                    <iframe :src="pdfModalSrc" style="width:100%;height:100%;border:none;" title="Work Order PDF"></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

<?php $this->start('scripts'); ?>
<script>
(function () {
    // Parse inline JSON payloads
    var woData       = <?= $woJson ?>;
    var tasksData    = <?= $tasksJson ?>;
    var partsData    = <?= $partsUsedJson ?>;
    var partOptsData = <?= $partOptionsJson ?>;
    var initialMc    = <?= (float) $initialMaterialCost ?>;
    var permitsData  = <?= $permitsJson ?>;
    var initialFlash = <?= $flashMsg ?>;
    var woId         = <?= $woId ?>;
    var apiBase      = '<?= e($apiBaseUrl) ?>';
    var csrfToken    = '<?= $csrfVal ?>';
    var hasAppPermit = <?= !empty($hasApprovedPermit) ? 'true' : 'false' ?>;

    // Ensure each task has reactive props
    tasksData.forEach(function (t) {
        t._response_value = t._response_value || t.response_value || '';
        t._result_note    = '';
        t._remedy_note    = '';
        t.is_done         = !!t.is_done;
        t.is_required     = !!t.is_required;
    });

    var app = Vue.createApp({
        data: function () {
            return {
                wo: woData,
                tasks: tasksData,
                partsUsed: partsData,
                partOptions: partOptsData,
                materialCost: initialMc,
                permits: permitsData,
                hasApprovedPermit: hasAppPermit,
                flash: initialFlash,
                // add-task form
                newTaskTitle: '',
                newTaskOrder: 0,
                // consume-part form
                consumePartId: '',
                consumeQty: 0.001,
                // PDF modal
                pdfModalSrc: '',
            };
        },
        computed: {
            taskDoneCount: function () {
                return this.tasks.filter(function (t) { return t.is_done; }).length;
            },
            pdfUrl: function () {
                return '<?= e($pdfUrl) ?>';
            },
        },
        methods: {
            // ── helpers ──
            nl2br: function (str) {
                if (!str) return '';
                return String(str).replace(/\n/g, '<br>');
            },
            parseOptions: function (json) {
                if (!json) return [];
                try { return JSON.parse(json); } catch (e) { return []; }
            },
            formatQty: function (v) {
                var n = parseFloat(v);
                if (isNaN(n)) return v;
                var s = n.toFixed(3);
                return s.replace(/\.?0+$/, '') || '0';
            },
            photoBadge: function (t) {
                var map = {
                    required: ['bg-danger', 'Photo required'],
                    optional: ['bg-info', 'Photo optional'],
                    n_a: [null, null],
                };
                return map[t.photo_requirement] || [null, null];
            },
            permitBadge: function (status) {
                var map = { requested:'bg-primary', approved:'bg-info text-dark', active:'bg-success', rejected:'bg-danger', closed:'bg-secondary', expired:'bg-dark', draft:'bg-secondary' };
                return map[status] || 'bg-secondary';
            },
            showFlash: function (msg) {
                var self = this;
                self.flash = msg;
                setTimeout(function () { self.flash = null; }, 5000);
            },

            // ── TASK ACTIONS (no page reload) ──
            markTaskDone: function (t) {
                var self = this;
                var taskId = t.task_id;
                var body = new URLSearchParams();
                body.append('_csrf', csrfToken);
                fetch(apiBase + '/complete-task/' + taskId, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': csrfToken },
                    body: body.toString(),
                }).then(function (r) { return r.json(); })
                  .then(function (data) {
                    if (data.error) { self.showFlash(data.error); return; }
                    // refresh task state
                    self.refreshWoData();
                }).catch(function () { self.showFlash('Network error.'); });
            },
            submitTaskForm: function (t) {
                var self = this;
                var taskId = t.task_id;
                var body = new URLSearchParams();
                body.append('_csrf', csrfToken);
                body.append('response_value', t._response_value || '');
                body.append('note', t._result_note || '');
                body.append('remedy_note', t._remedy_note || '');
                fetch(apiBase + '/complete-task/' + taskId, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': csrfToken },
                    body: body.toString(),
                }).then(function (r) { return r.json(); })
                  .then(function (data) {
                    if (data.error) { self.showFlash(data.error); return; }
                    self.showFlash('Task completed.');
                    self.refreshWoData();
                }).catch(function () { self.showFlash('Network error.'); });
            },
            reopenTask: function (t) {
                var self = this;
                var taskId = t.task_id;
                fetch(apiBase + '/reopen-task/' + taskId, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': csrfToken },
                    body: '_csrf=' + encodeURIComponent(csrfToken),
                }).then(function (r) { return r.json(); })
                  .then(function (data) {
                    if (data.success) {
                        self.showFlash('Task reopened.');
                        self.refreshWoData();
                    }
                }).catch(function () { self.showFlash('Network error.'); });
            },
            confirmDeleteTask: function (t) {
                var self = this;
                rsConfirm({
                    title: 'Delete task?',
                    message: 'Remove "' + t.title + '" from this work order?',
                    okLabel: 'Delete',
                    danger: true,
                    onConfirm: function () {
                        // Fallback to server-side delete for simplicity (no API endpoint for delete-task exists)
                        self.showFlash('Task removed.');
                        window.location.href = '<?= url('/WorkOrders/deleteTask/') ?>' + t.task_id;
                    },
                });
            },
            addTask: function () {
                var self = this;
                if (!self.newTaskTitle.trim()) return;
                var body = new URLSearchParams();
                body.append('_csrf', csrfToken);
                body.append('title', self.newTaskTitle.trim());
                body.append('sort_order', self.newTaskOrder || 0);
                fetch('<?= url('/WorkOrders/addTask/') ?>' + woId, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: body.toString(),
                }).then(function (r) {
                    // The server-side addTask does a redirect; we do a fetch and then refresh
                    self.newTaskTitle = '';
                    self.newTaskOrder = 0;
                    self.showFlash('Task added.');
                    self.refreshWoData();
                }).catch(function () { self.showFlash('Network error.'); });
            },

            // ── CONSUME PART ──
            consumePart: function () {
                var self = this;
                if (!self.consumePartId || !self.consumeQty) return;
                var body = JSON.stringify({
                    part_id: self.consumePartId,
                    quantity: self.consumeQty,
                });
                fetch(apiBase + '/consume-part/' + woId, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
                    body: body,
                }).then(function (r) { return r.json(); })
                  .then(function (data) {
                    if (data.error) { self.showFlash(data.error); return; }
                    self.partsUsed = data.parts_used || [];
                    self.materialCost = parseFloat(data.material_cost) || 0;
                    self.consumePartId = '';
                    self.consumeQty = 0.001;
                    self.showFlash('Part consumption logged.');
                }).catch(function () { self.showFlash('Network error.'); });
            },

            // ── REFRESH WO DATA FROM SERVER ──
            refreshWoData: function () {
                var self = this;
                fetch(apiBase + '/' + woId)
                    .then(function (r) { return r.json(); })
                    .then(function (resp) {
                        if (!resp.data) return;
                        // merge tasks back
                        var newTasks = resp.data.tasks || [];
                        newTasks.forEach(function (t) {
                            t._response_value = t._response_value || t.response_value || '';
                            t._result_note    = '';
                            t._remedy_note    = '';
                            t.is_done         = !!t.is_done;
                            t.is_required     = !!t.is_required;
                        });
                        self.tasks = newTasks;
                        self.materialCost = parseFloat(resp.data.material_cost) || 0;
                        self.partsUsed = resp.data.parts_used || self.partsUsed;
                        // keep existing wo fields but sync status
                        self.wo.status = resp.data.status;
                        self.wo.completed_at = resp.data.completed_at;
                        self.wo.started_at = resp.data.started_at;
                    });
            },

            // ── PDF MODAL ──
            openPdfModal: function () {
                this.pdfModalSrc = this.pdfUrl;
                var modalEl = document.getElementById('pdfModal');
                if (modalEl) {
                    var bsModal = new bootstrap.Modal(modalEl);
                    bsModal.show();
                }
            },
            closePdfModal: function () {
                this.pdfModalSrc = '';
            },
            printPdf: function () {
                // Open the PDF URL in a hidden iframe and trigger print
                var printWin = window.open(this.pdfUrl, '_blank');
                if (printWin) {
                    printWin.onload = function () {
                        printWin.focus();
                        printWin.print();
                    };
                }
            },
        },
    });

    app.mount('#woShowApp');
})();
</script>
<?php $this->end(); ?>