@extends('layouts.app')
@section('title', ($ro->number ?: ('RO #' . $ro->id)))

@section('content')
@php $base = url('vrc/repair-orders/' . $ro->id); @endphp
<section class="content-header">
    <h1>{{ $ro->number ?: ('RO #' . $ro->id) }}
        <span class="label label-info" id="vrc-ro-status">{{ __('vrc::lang.ro_status_' . $ro->status) }}</span>
        @if($ro->is_rework)<span class="label label-warning" title="@lang('vrc::lang.is_rework')"><i class="fa fa-refresh"></i> @lang('vrc::lang.rework')</span>@endif
        <a href="{{ route('vrc.repair-orders.job-card', $ro->id) }}" target="_blank" class="btn btn-default btn-sm pull-right"><i class="fa fa-print"></i> @lang('vrc::lang.job_card')</a>
    </h1>
</section>

@if($ro->is_rework)
<div class="callout callout-warning" style="margin:10px 15px;">
    <h4><i class="fa fa-refresh"></i> @lang('vrc::lang.rework')</h4>
    <p>
        @if($ro->reworkOf)
            @lang('vrc::lang.original_repair_order'):
            <a href="{{ route('vrc.repair-orders.show', $ro->reworkOf->id) }}">{{ $ro->reworkOf->number ?: '#'.$ro->reworkOf->id }}</a>.
        @endif
        @if($ro->rework_reason) <em>{{ $ro->rework_reason }}</em>@endif
    </p>
    @can('vrc.quality.manage')
        @if($ro->rework_ncr_id)
            <span class="label label-default">@lang('vrc::lang.rework_already_escalated')</span>
        @else
            <form method="POST" action="{{ route('vrc.repair-orders.escalate-rework', $ro->id) }}" style="display:inline;">@csrf
                <button class="btn btn-xs btn-warning"><i class="fa fa-exclamation-triangle"></i> @lang('vrc::lang.escalate_to_ncr')</button>
            </form>
        @endif
    @endcan
</div>
@endif

<section class="content" data-ro="{{ $ro->id }}" data-base="{{ $base }}">
    <div class="row">
        <div class="col-md-8">
            {{-- Transition bar --}}
            @can('vrc.repair_order.manage')
            <div class="box box-solid"><div class="box-body">
                <strong>@lang('vrc::lang.move_to'):</strong>
                @forelse ($allowed as $to)
                    <button class="btn btn-sm btn-default vrc-ro-transition" data-to="{{ $to }}">{{ __('vrc::lang.ro_status_' . $to) }}</button>
                @empty
                    <span class="text-muted">@lang('vrc::lang.no_further_transitions')</span>
                @endforelse
                @can('vrc.inspection.manage')
                    <a href="{{ route('vrc.inspections.create', $ro->id) }}" class="btn btn-sm btn-info pull-right"><i class="fa fa-clipboard-check"></i> @lang('vrc::lang.new_inspection')</a>
                @endcan
                @can('vrc.repair_order.manage')
                    <button class="btn btn-sm btn-success pull-right" id="vrc-redeem-plan" style="margin-right:6px;"><i class="fa fa-star"></i> @lang('vrc::lang.redeem_plan')</button>
                @endcan
                @can('vrc.estimate.manage')
                    <form method="POST" action="{{ route('vrc.estimates.from-ro', $ro->id) }}" class="pull-right" style="margin-right:6px;">@csrf
                        <button class="btn btn-sm btn-warning"><i class="fa fa-file-text-o"></i> @lang('vrc::lang.create_estimate')</button>
                    </form>
                @endcan
                @can('vrc.insurance.manage')
                    <button class="btn btn-sm btn-default pull-right vrc-modal-btn" style="margin-right:6px;" data-href="{{ route('vrc.insurance-claims.form', $ro->id) }}"><i class="fa fa-shield"></i> @lang('vrc::lang.insurance_claim')</button>
                @endcan
            </div></div>
            @endcan

            <ul class="nav nav-tabs">
                <li class="active"><a href="#tab-services" data-toggle="tab">@lang('vrc::lang.services')</a></li>
                <li><a href="#tab-parts" data-toggle="tab">@lang('vrc::lang.parts')</a></li>
                <li><a href="#tab-timeline" data-toggle="tab">@lang('vrc::lang.timeline')</a></li>
            </ul>
            <div class="tab-content box box-primary" style="padding:12px;">
                {{-- SERVICES --}}
                <div class="tab-pane active" id="tab-services">
                    @can('vrc.repair_order.manage')
                    <div class="well well-sm" style="background:#f9f9f9;">
                        <label><i class="fa fa-magic"></i> @lang('vrc::lang.ai_assistant')</label>
                        <div class="input-group">
                            <input type="text" id="vrc-ai-symptom" class="form-control input-sm" placeholder="@lang('vrc::lang.ai_symptom_placeholder')">
                            <span class="input-group-btn"><button class="btn btn-sm btn-info" id="vrc-ai-go"><i class="fa fa-magic"></i> @lang('vrc::lang.ai_suggest')</button></span>
                        </div>
                        <div id="vrc-ai-out" style="white-space:pre-wrap; margin-top:8px; display:none;" class="text-muted small"></div>
                    </div>
                    @endcan
                    <form class="form-inline vrc-add-service" style="margin-bottom:10px;">
                        <select name="service_id" class="form-control input-sm vrc-service-pick">
                            <option value="">— @lang('vrc::lang.ad_hoc') —</option>
                            @foreach ($services as $svc)
                                <option value="{{ $svc->id }}" data-price="{{ $svc->default_price }}" data-hours="{{ $svc->default_labor_hours }}" data-tax="{{ $svc->tax_rate_id }}">{{ $svc->name }}</option>
                            @endforeach
                        </select>
                        <input type="text" name="description" class="form-control input-sm vrc-svc-desc" placeholder="@lang('vrc::lang.description')" required>
                        <input type="number" name="qty" class="form-control input-sm" style="width:70px;" value="1" step="0.5" min="0" title="@lang('vrc::lang.qty')">
                        <input type="number" name="unit_price" class="form-control input-sm vrc-svc-price" style="width:100px;" value="0" step="0.01" min="0" title="@lang('vrc::lang.price')">
                        <select name="tax_rate_id" class="form-control input-sm vrc-svc-tax">{!! collect($taxRates)->map(fn($n,$i)=>"<option value='$i'>$n</option>")->implode('') !!}</select>
                        <button class="btn btn-sm btn-primary"><i class="fa fa-plus"></i> @lang('messages.add')</button>
                        <button type="button" class="btn btn-sm btn-default" id="vrc-apply-pkg"><i class="fa fa-cubes"></i> @lang('vrc::lang.apply_package')</button>
                    </form>
                    @endcan
                    <table class="table table-condensed table-bordered">
                        <thead><tr><th>@lang('vrc::lang.service')</th><th>@lang('vrc::lang.qty')</th><th>@lang('vrc::lang.price')</th><th>@lang('vrc::lang.line_total')</th><th>@lang('vrc::lang.technician')</th><th>@lang('vrc::lang.status')</th><th></th></tr></thead>
                        <tbody>
                        @foreach ($ro->services as $s)
                            <tr>
                                <td>{{ $s->description }}</td>
                                <td>{{ $s->qty }}</td>
                                <td>{{ $s->unit_price }}</td>
                                <td>{{ $s->line_total }}</td>
                                <td>
                                    <select class="form-control input-sm vrc-assign" data-line="{{ $s->id }}">
                                        <option value="">—</option>
                                        @foreach ($technicians as $tid => $tname)
                                            <option value="{{ $tid }}" {{ $s->assigned_technician_id == $tid ? 'selected' : '' }}>{{ $tname }}</option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>
                                    <select class="form-control input-sm vrc-svc-status" data-line="{{ $s->id }}">
                                        @foreach (['pending','in_progress','done','skipped'] as $st)
                                            <option value="{{ $st }}" {{ $s->status == $st ? 'selected' : '' }}>{{ __('vrc::lang.svc_' . $st) }}</option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>@can('vrc.repair_order.manage')<button class="btn btn-xs btn-danger vrc-del-service" data-line="{{ $s->id }}"><i class="fa fa-trash"></i></button>@endcan</td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                </div>
                {{-- PARTS --}}
                <div class="tab-pane" id="tab-parts">
                    @can('vrc.repair_order.manage')
                    <form class="form-inline vrc-add-part" style="margin-bottom:10px;">
                        <input type="text" class="form-control input-sm vrc-part-search" placeholder="@lang('vrc::lang.search_part')" autocomplete="off">
                        <input type="hidden" name="erp_product_id" class="vrc-part-product">
                        <input type="hidden" name="erp_variation_id" class="vrc-part-variation">
                        <input type="text" name="description" class="form-control input-sm vrc-part-desc" placeholder="@lang('vrc::lang.description')" required>
                        <input type="number" name="qty" class="form-control input-sm" style="width:70px;" value="1" step="0.5" min="0">
                        <input type="number" name="unit_price" class="form-control input-sm vrc-part-price" style="width:100px;" value="0" step="0.01" min="0">
                        <select name="tax_rate_id" class="form-control input-sm">{!! collect($taxRates)->map(fn($n,$i)=>"<option value='$i'>$n</option>")->implode('') !!}</select>
                        <select name="source" class="form-control input-sm">
                            <option value="stock">@lang('vrc::lang.src_stock')</option>
                            <option value="special_order">@lang('vrc::lang.src_special_order')</option>
                            <option value="customer_supplied">@lang('vrc::lang.src_customer_supplied')</option>
                        </select>
                        <button class="btn btn-sm btn-primary"><i class="fa fa-plus"></i> @lang('messages.add')</button>
                        <div class="vrc-part-results list-group" style="position:absolute;z-index:1000;width:300px;"></div>
                    </form>
                    <button class="btn btn-xs btn-default" id="vrc-suggest-parts" style="margin-bottom:8px;"><i class="fa fa-lightbulb-o"></i> @lang('vrc::lang.suggest_fitting_parts')</button>
                    <div id="vrc-suggested-parts"></div>
                    @endcan
                    <table class="table table-condensed table-bordered">
                        <thead><tr><th>@lang('vrc::lang.part')</th><th>@lang('vrc::lang.qty')</th><th>@lang('vrc::lang.price')</th><th>@lang('vrc::lang.line_total')</th><th>@lang('vrc::lang.source')</th><th></th></tr></thead>
                        <tbody>
                        @foreach ($ro->parts as $p)
                            <tr>
                                <td>{{ $p->description }}</td><td>{{ $p->qty }}</td><td>{{ $p->unit_price }}</td><td>{{ $p->line_total }}</td>
                                <td>{{ __('vrc::lang.src_' . $p->source) }}</td>
                                <td>@can('vrc.repair_order.manage')<button class="btn btn-xs btn-danger vrc-del-part" data-line="{{ $p->id }}"><i class="fa fa-trash"></i></button>@endcan</td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                </div>
                {{-- TIMELINE --}}
                <div class="tab-pane" id="tab-timeline">
                    <ul class="list-group">
                        @foreach ($ro->statusHistory as $h)
                            <li class="list-group-item">
                                <strong>{{ $h->from_status ? __('vrc::lang.ro_status_' . $h->from_status) : '—' }} → {{ __('vrc::lang.ro_status_' . $h->to_status) }}</strong>
                                <span class="pull-right text-muted">{{ optional($h->created_at)->format('Y-m-d H:i') }}</span>
                                @if($h->reason)<div class="text-muted">{{ $h->reason }}</div>@endif
                            </li>
                        @endforeach
                    </ul>
                </div>
            </div>
        </div>

        {{-- Sidebar: vehicle/customer + totals --}}
        <div class="col-md-4">
            @component('components.widget', ['class' => 'box-primary', 'title' => __('vrc::lang.vehicle')])
                <p><strong>{{ optional($ro->vehicle)->label }}</strong></p>
                <p>{{ optional($customer)->name }}</p>
                <p class="text-muted">@lang('vrc::lang.odometer'): {{ $ro->odometer_in ?? '—' }}</p>
                @if($ro->tracking_token)
                    <small class="text-muted">@lang('vrc::lang.track_repair'):</small>
                    <input type="text" class="form-control input-sm" readonly value="{{ route('vrc.portal.track', $ro->tracking_token) }}">
                @endif
            @endcomponent
            @component('components.widget', ['class' => 'box-success', 'title' => __('vrc::lang.totals')])
                <table class="table table-condensed">
                    <tr><th>@lang('vrc::lang.subtotal')</th><td class="text-right" id="vrc-subtotal">{{ $ro->subtotal }}</td></tr>
                    <tr><th>@lang('vrc::lang.discount')</th><td class="text-right" id="vrc-discount">{{ $ro->discount_total }}</td></tr>
                    <tr><th>@lang('vrc::lang.tax')</th><td class="text-right" id="vrc-tax">{{ $ro->tax_total }}</td></tr>
                    <tr><th>@lang('vrc::lang.grand_total')</th><td class="text-right"><strong id="vrc-grand">{{ $ro->grand_total }}</strong></td></tr>
                </table>
            @endcomponent

            @component('components.widget', ['class' => 'box-default', 'title' => __('vrc::lang.invoice')])
                @if($invoiceStatus)
                    <table class="table table-condensed">
                        <tr><th>@lang('vrc::lang.invoice')</th><td>{{ $invoiceStatus['invoice_no'] ?? '—' }}</td></tr>
                        <tr><th>@lang('vrc::lang.paid')</th><td>{{ number_format($invoiceStatus['paid'], 2) }} / {{ number_format($invoiceStatus['total'], 2) }}</td></tr>
                        <tr><th>@lang('vrc::lang.payment_status')</th><td><span class="label label-{{ $invoiceStatus['status']=='paid'?'success':'warning' }}">{{ $invoiceStatus['status'] }}</span></td></tr>
                    </table>
                    @if($ro->erp_invoice_id)<a href="{{ url('sells/'.$ro->erp_invoice_id) }}" class="btn btn-default btn-sm btn-block">@lang('vrc::lang.open_erp_invoice')</a>@endif
                @else
                    @can('vrc.repair_order.manage')
                        <button class="btn btn-success btn-block" id="vrc-ro-invoice"><i class="fa fa-file-text"></i> @lang('vrc::lang.generate_invoice')</button>
                    @endcan
                @endif
            @endcomponent
        </div>
    </div>
    <div class="modal fade vrc_modal" tabindex="-1" role="dialog"></div>
</section>
@endsection

@section('javascript')
@include('vrc::partials.crud_scripts')
<script>
$(function () {
    var $ctx = $('section.content[data-base]'), base = $ctx.data('base');
    var token = $('meta[name=csrf-token]').attr('content');
    function reload() { window.location.reload(); }
    function post(url, data, cb) {
        data._token = token;
        $.post(url, data).done(function (r) {
            if (r.success) { toastr.success(r.msg); (cb || reload)(r); }
            else { toastr.error(r.msg || 'Error'); }
        }).fail(function (xhr) {
            if (xhr.responseJSON && xhr.responseJSON.msg) toastr.error(xhr.responseJSON.msg);
            else toastr.error('Error');
        });
    }

    // Service picker prefill
    $('.vrc-service-pick').on('change', function () {
        var o = $(this).find('option:selected');
        if (o.val()) {
            $('.vrc-svc-desc').val(o.text());
            $('.vrc-svc-price').val(o.data('price'));
            if (o.data('tax')) $('.vrc-svc-tax').val(o.data('tax'));
        }
    });

    // Transitions
    $('.vrc-ro-transition').on('click', function () {
        var to = $(this).data('to');
        var reason = (to === 'cancelled' || to === 'estimate_declined') ? (window.prompt('{{ __('vrc::lang.reason') }}:') || '') : '';
        post(base + '/transition', { to: to, reason: reason });
    });

    // Add service line
    $('.vrc-add-service').on('submit', function (e) { e.preventDefault(); post(base + '/services', objOf($(this))); });
    $(document).on('click', '.vrc-del-service', function () {
        $.ajax({ url: base + '/services/' + $(this).data('line'), method: 'DELETE', data: { _token: token } })
            .done(function (r) { r.success ? (toastr.success(r.msg), reload()) : toastr.error(r.msg); });
    });
    $('.vrc-assign').on('change', function () { post(base + '/assign', { line_id: $(this).data('line'), technician_id: $(this).val() }, function(){}); });
    $('.vrc-svc-status').on('change', function () { post(base + '/services/' + $(this).data('line') + '/status', { status: $(this).val() }, function(){}); });

    // Apply package
    $('#vrc-apply-pkg').on('click', function () {
        var pid = window.prompt('{{ __('vrc::lang.package_id_prompt') }}'); if (!pid) return;
        post(base + '/apply-package', { package_id: pid });
    });

    // Parts: live search
    $('.vrc-part-search').on('keyup', function () {
        var q = $(this).val(); var $res = $('.vrc-part-results');
        if (q.length < 2) { $res.empty(); return; }
        $.get('{{ route('vrc.parts.lookup') }}', { q: q }, function (rows) {
            $res.empty();
            rows.forEach(function (v) {
                var stock = v.enable_stock == 1
                    ? ' <span class="label label-' + (v.qty_available > 0 ? 'success' : 'danger') + '">' + v.qty_available + '</span>'
                    : '';
                $('<a href="#" class="list-group-item">').html($('<span>').text(v.name + ' (' + (v.sub_sku||'') + ')').html() + stock).on('click', function (e) {
                    e.preventDefault();
                    $('.vrc-part-product').val(v.product_id); $('.vrc-part-variation').val(v.variation_id);
                    $('.vrc-part-desc').val(v.name); $('.vrc-part-price').val(v.default_sell_price); $res.empty(); $('.vrc-part-search').val(v.name);
                }).appendTo($res);
            });
        });
    });
    $('.vrc-add-part').on('submit', function (e) { e.preventDefault(); post(base + '/parts', objOf($(this))); });
    $(document).on('click', '.vrc-del-part', function () {
        $.ajax({ url: base + '/parts/' + $(this).data('line'), method: 'DELETE', data: { _token: token } })
            .done(function (r) { r.success ? (toastr.success(r.msg), reload()) : toastr.error(r.msg); });
    });

    // Generate ERP invoice
    $('#vrc-ro-invoice').on('click', function () {
        $(this).prop('disabled', true);
        post(base + '/invoice', {}, function (r) {
            if (r.redirect) { window.location = r.redirect; } else { reload(); }
        });
    });

    // AI estimate assistant
    $('#vrc-ai-go').on('click', function () {
        var symptom = $('#vrc-ai-symptom').val();
        if (!symptom) return;
        var $btn = $(this).prop('disabled', true), $out = $('#vrc-ai-out').show().text('…');
        $.post(base + '/ai-assist', { symptom: symptom, _token: token }, function (r) {
            $out.text(r.ok ? r.text : (r.error || 'Error'));
        }).fail(function(){ $out.text('Error'); }).always(function(){ $btn.prop('disabled', false); });
    });

    // Suggested fitting parts (ProductCompat)
    $('#vrc-suggest-parts').on('click', function () {
        var $out = $('#vrc-suggested-parts').html('<p class="text-muted">…</p>');
        $.get(base + '/suggested-parts', function (r) {
            if (!r.parts || !r.parts.length) { $out.html('<p class="text-muted">@lang('vrc::lang.no_suggested_parts')</p>'); return; }
            var html = '<table class="table table-condensed"><thead><tr><th>@lang('vrc::lang.part')</th><th>@lang('vrc::lang.qty')</th><th>@lang('vrc::lang.price')</th><th></th></tr></thead><tbody>';
            r.parts.forEach(function (p) {
                html += '<tr><td>' + $('<span>').text(p.name).html() + ' <small class="text-muted">' + (p.sub_sku||'') + '</small></td>'
                    + '<td><span class="label label-' + (p.qty_available>0?'success':'danger') + '">' + p.qty_available + '</span></td>'
                    + '<td>' + p.price + '</td>'
                    + '<td><button class="btn btn-xs btn-primary vrc-add-suggested" data-pid="' + p.product_id + '" data-vid="' + (p.variation_id||'') + '" data-name="' + $('<span>').text(p.name).html() + '" data-price="' + p.price + '"><i class="fa fa-plus"></i></button></td></tr>';
            });
            $out.html(html + '</tbody></table>');
        });
    });
    $(document).on('click', '.vrc-add-suggested', function () {
        var $b = $(this);
        post(base + '/parts', { erp_product_id: $b.data('pid'), erp_variation_id: $b.data('vid'), description: $b.data('name'), qty: 1, unit_price: $b.data('price'), source: 'stock' });
    });

    // Redeem a loyalty plan visit
    $('#vrc-redeem-plan').on('click', function () {
        if (!confirm('@lang('vrc::lang.redeem_plan_confirm')')) return;
        post(base + '/redeem-plan', {});
    });

    function objOf($form) { var o = {}; $form.serializeArray().forEach(function (f) { o[f.name] = f.value; }); return o; }
});
</script>
@endsection
