@extends('layouts.app')
@section('title', __('vrc::lang.inspection'))

@section('css')
<style>
    .vrc-dvi-item { border:1px solid #eee; border-radius:6px; padding:10px; margin-bottom:8px; }
    .vrc-dvi-btns label { margin-right:6px; padding:6px 12px; border-radius:6px; border:1px solid #ddd; cursor:pointer; }
    .vrc-dvi-btns input { display:none; }
    .vrc-dvi-btns input:checked + span { font-weight:700; }
    .ok span{color:#00a65a} .attention span{color:#f39c12} .critical span{color:#dd4b39} .na span{color:#999}
    #vrc-sig { border:1px solid #ccc; border-radius:6px; touch-action:none; background:#fff; }
</style>
@endsection

@section('content')
@php $base = url('vrc/inspections/'.$inspection->id); @endphp
<section class="content-header">
    <h1>@lang('vrc::lang.inspection') — {{ __('vrc::lang.dvi_'.$inspection->type) }}
        <a href="{{ route('vrc.repair-orders.show', $inspection->repair_order_id) }}" class="btn btn-default btn-sm pull-right">@lang('vrc::lang.back_to_ro')</a>
        <a href="{{ route('vrc.inspections.pdf', $inspection->id) }}" target="_blank" class="btn btn-default btn-sm pull-right" style="margin-right:6px;"><i class="fa fa-print"></i> PDF</a>
    </h1>
</section>

<section class="content" data-base="{{ $base }}">
    @component('components.widget', ['class' => 'box-primary'])
        <form id="vrc-dvi-form">
            @foreach ($inspection->results as $r)
                <div class="vrc-dvi-item">
                    <strong>{{ $r->label }}</strong>
                    <div class="vrc-dvi-btns" style="margin:6px 0;">
                        @foreach (['ok','attention','critical','na'] as $opt)
                            <label class="{{ $opt }}"><input type="radio" name="result[{{ $r->id }}][result]" value="{{ $opt }}" {{ $r->result==$opt?'checked':'' }}><span>{{ __('vrc::lang.dvi_'.$opt) }}</span></label>
                        @endforeach
                    </div>
                    <div class="row">
                        <div class="col-md-6"><input type="text" name="result[{{ $r->id }}][note]" class="form-control input-sm" placeholder="@lang('vrc::lang.note')" value="{{ $r->note }}"></div>
                        <div class="col-md-6">
                            <select name="result[{{ $r->id }}][recommended_service_id]" class="form-control input-sm">
                                <option value="">— @lang('vrc::lang.recommend_service') —</option>
                                @foreach ($services as $sid => $sname)<option value="{{ $sid }}" {{ $r->recommended_service_id==$sid?'selected':'' }}>{{ $sname }}</option>@endforeach
                            </select>
                        </div>
                    </div>
                </div>
            @endforeach

            <div class="form-group">
                <label>Body damage diagram</label>
                <div style="margin-bottom:6px;">
                    <select id="vrc-damage-type" class="form-control input-sm" style="width:auto; display:inline-block;">
                        <option value="scratch">Scratch</option><option value="dent">Dent</option>
                        <option value="crack">Crack</option><option value="rust">Rust</option><option value="other">Other</option>
                    </select>
                    <span class="text-muted" style="font-size:12px;">Click the diagram to add a mark; click a mark to remove it.</span>
                </div>
                <div id="vrc-body-wrap" style="position:relative; width:220px; margin:0 auto; user-select:none; cursor:crosshair;">
                    <svg viewBox="0 0 120 240" style="width:100%; height:auto; display:block;">
                        <rect x="20" y="10" width="80" height="220" rx="34" ry="38" fill="#f7f7f7" stroke="#999" stroke-width="2"/>
                        <rect x="34" y="34" width="52" height="40" rx="8" fill="#e3eaf2" stroke="#aab"/>
                        <rect x="32" y="150" width="56" height="46" rx="8" fill="#e3eaf2" stroke="#aab"/>
                        <line x1="60" y1="80" x2="60" y2="148" stroke="#ccc"/>
                        <rect x="12" y="40" width="8" height="26" rx="3" fill="#ccc"/><rect x="100" y="40" width="8" height="26" rx="3" fill="#ccc"/>
                        <rect x="12" y="174" width="8" height="26" rx="3" fill="#ccc"/><rect x="100" y="174" width="8" height="26" rx="3" fill="#ccc"/>
                    </svg>
                    <div id="vrc-body-markers" style="position:absolute; top:0; left:0; right:0; bottom:0;"></div>
                </div>
                <input type="hidden" name="body_diagram" id="vrc-body-input" value="">
            </div>

            @if($inspection->type === 'final')
            <div class="form-group" style="border:1px solid #eee; border-radius:6px; padding:10px; background:#fafafa;">
                <label style="display:block;">@lang('vrc::lang.test_drive')</label>
                <label style="font-weight:400; margin-right:14px;">
                    <input type="checkbox" name="test_drive_done" value="1" {{ $inspection->test_drive_done ? 'checked' : '' }}>
                    @lang('vrc::lang.test_drive_done')
                </label>
                <label style="font-weight:400; margin-right:6px;">@lang('vrc::lang.result'):</label>
                <select name="test_drive_result" class="form-control input-sm" style="width:auto; display:inline-block; margin-right:14px;">
                    <option value="">—</option>
                    <option value="pass" {{ $inspection->test_drive_result==='pass'?'selected':'' }}>@lang('vrc::lang.test_drive_pass')</option>
                    <option value="fail" {{ $inspection->test_drive_result==='fail'?'selected':'' }}>@lang('vrc::lang.test_drive_fail')</option>
                </select>
                <label style="font-weight:400; margin-right:6px;">@lang('vrc::lang.odometer'):</label>
                <input type="number" name="test_drive_odometer" class="form-control input-sm" style="width:110px; display:inline-block;" value="{{ $inspection->test_drive_odometer }}">
                <input type="text" name="test_drive_notes" class="form-control input-sm" style="margin-top:6px;" placeholder="@lang('vrc::lang.note')" value="{{ $inspection->test_drive_notes }}">
            </div>
            @endif

            <div class="form-group"><label>@lang('vrc::lang.summary')</label><textarea name="summary" class="form-control" rows="2">{{ $inspection->summary }}</textarea></div>
            <label><input type="checkbox" name="complete" value="1" {{ $inspection->status=='completed'?'checked':'' }}> @lang('vrc::lang.mark_completed')</label>
            <hr>
            <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> @lang('messages.save')</button>
            <button type="button" class="btn btn-success" id="vrc-push"><i class="fa fa-arrow-right"></i> @lang('vrc::lang.push_to_estimate')</button>
        </form>

        <hr>
        <div class="row">
            <div class="col-md-6">
                <label>@lang('vrc::lang.photos')</label>
                <form id="vrc-photo-form" enctype="multipart/form-data">
                    <input type="file" name="photos[]" multiple class="form-control">
                    <button type="submit" class="btn btn-default btn-sm" style="margin-top:6px;"><i class="fa fa-upload"></i> @lang('messages.upload')</button>
                </form>
            </div>
            <div class="col-md-6">
                <label>@lang('vrc::lang.customer_signature')</label><br>
                <canvas id="vrc-sig" width="300" height="120"></canvas><br>
                <button type="button" class="btn btn-default btn-xs" id="vrc-sig-clear">@lang('messages.clear')</button>
                <button type="button" class="btn btn-primary btn-xs" id="vrc-sig-save">@lang('vrc::lang.save_signature')</button>
            </div>
        </div>
    @endcomponent
</section>
@endsection

@section('javascript')
<script>
$(function () {
    var base = $('section.content[data-base]').data('base');
    var token = $('meta[name=csrf-token]').attr('content');

    $('#vrc-dvi-form').on('submit', function (e) {
        e.preventDefault();
        $.post(base + '/results', $(this).serialize() + '&_token=' + token, function (r) {
            r.success ? toastr.success(r.msg) : toastr.error(r.msg);
        }).fail(function(){ toastr.error('Error'); });
    });

    $('#vrc-push').on('click', function () {
        $.post(base + '/push-to-estimate', { _token: token }, function (r) {
            r.success ? toastr.success(r.msg) : toastr.error(r.msg);
        }).fail(function(){ toastr.error('Error'); });
    });

    $('#vrc-photo-form').on('submit', function (e) {
        e.preventDefault();
        var fd = new FormData(this); fd.append('_token', token);
        $.ajax({ url: base + '/photos', method: 'POST', data: fd, processData: false, contentType: false })
            .done(function (r) { r.success ? toastr.success(r.msg) : toastr.error(r.msg); })
            .fail(function(){ toastr.error('Error'); });
    });

    // Body-damage diagram markers
    var markers = @json($inspection->body_diagram ?? []);
    var colors = { scratch:'#f39c12', dent:'#dd4b39', crack:'#605ca8', rust:'#8d6e63', other:'#3c8dbc' };
    function renderMarkers() {
        var $m = $('#vrc-body-markers').empty();
        markers.forEach(function (mk, i) {
            $('<div>').css({ position:'absolute', left:mk.x+'%', top:mk.y+'%', transform:'translate(-50%,-50%)',
                width:'18px', height:'18px', borderRadius:'50%', background:(colors[mk.type]||'#dd4b39'),
                color:'#fff', fontSize:'11px', lineHeight:'18px', textAlign:'center', cursor:'pointer', border:'2px solid #fff' })
                .text(i + 1).attr('title', mk.type).data('idx', i).appendTo($m);
        });
        $('#vrc-body-input').val(JSON.stringify(markers));
    }
    $('#vrc-body-wrap').on('click', function (e) {
        if ($(e.target).closest('#vrc-body-markers > div').length) return;
        var rect = this.getBoundingClientRect();
        markers.push({
            x: +(((e.clientX - rect.left) / rect.width) * 100).toFixed(1),
            y: +(((e.clientY - rect.top) / rect.height) * 100).toFixed(1),
            type: $('#vrc-damage-type').val()
        });
        renderMarkers();
    });
    $('#vrc-body-markers').on('click', 'div', function (e) {
        e.stopPropagation(); markers.splice($(this).data('idx'), 1); renderMarkers();
    });
    renderMarkers();

    // Simple signature pad
    var c = document.getElementById('vrc-sig'), ctx = c.getContext('2d'), drawing = false, has = false;
    function pos(e){ var rect=c.getBoundingClientRect(), t=e.touches?e.touches[0]:e; return {x:t.clientX-rect.left, y:t.clientY-rect.top}; }
    function start(e){ drawing=true; has=true; var p=pos(e); ctx.beginPath(); ctx.moveTo(p.x,p.y); e.preventDefault(); }
    function move(e){ if(!drawing)return; var p=pos(e); ctx.lineTo(p.x,p.y); ctx.stroke(); e.preventDefault(); }
    function end(){ drawing=false; }
    c.addEventListener('mousedown',start); c.addEventListener('mousemove',move); window.addEventListener('mouseup',end);
    c.addEventListener('touchstart',start); c.addEventListener('touchmove',move); c.addEventListener('touchend',end);
    $('#vrc-sig-clear').on('click', function(){ ctx.clearRect(0,0,c.width,c.height); has=false; });
    $('#vrc-sig-save').on('click', function(){
        if(!has){ toastr.warning('—'); return; }
        $.post(base + '/sign', { signature: c.toDataURL('image/png'), who: 'customer', _token: token }, function (r) {
            r.success ? toastr.success(r.msg) : toastr.error(r.msg);
        }).fail(function(){ toastr.error('Error'); });
    });
});
</script>
@endsection
