@extends('layouts.dashboard.app')

@section('style')
    <link rel="stylesheet" href="{{ asset('css/viewer.css') }}">

    <style>
        * {
            box-sizing: border-box;
        }

        #the-canvas {
            border: 1px solid black;
            direction: ltr;
        }

        * {
            box-sizing: border-box;
        }

        li {
            text-decoration: none;
        }

        /* Position the image container (needed to position the left and right arrows) */
        .container {
            position: relative;
        }

        /* Hide the images by default */
        .mySlides {
            display: none;
        }

        /* Add a pointer when hovering over the thumbnail images */
        .cursor {
            cursor: pointer;
        }

        /* Next & previous buttons */
        .prev,
        .next {
            cursor: pointer;
            position: absolute;
            top: 40%;
            width: auto;
            padding: 16px;
            margin-top: -50px;
            color: white;
            font-weight: bold;
            font-size: 20px;
            border-radius: 0 3px 3px 0;
            user-select: none;
            -webkit-user-select: none;
        }

        /* Position the "next button" to the right */
        .next {
            right: 0;
            border-radius: 3px 0 0 3px;
        }

        /* On hover, add a black background color with a little bit see-through */
        .prev:hover,
        .next:hover {
            background-color: rgba(0, 0, 0, 0.8);
        }

        /* Number text (1/3 etc) */
        .numbertext {
            color: #f2f2f2;
            font-size: 12px;
            padding: 8px 12px;
            position: absolute;
            top: 0;
        }

        /* Container for image text */
        .caption-container {
            text-align: center;
            background-color: #222;
            padding: 2px 16px;
            color: white;
        }

        .row:after {
            content: "";
            display: table;
            clear: both;
        }

        /* Six columns side by side */
        .column {
            float: left;
            width: 16.66%;
        }

        /* Add a transparency effect for thumnbail images */
        .demo {
            opacity: 0.6;
        }

        .active,
        .demo:hover {
            opacity: 1;
        }

        .container {
            position: relative;
            width: 33%;
        }

        .image {
            opacity: 1;
            display: block;
            width: 100%;
            height: auto;
            transition: .5s ease;
            backface-visibility: hidden;
        }

        .middle {
            transition: .5s ease;
            opacity: 0;
            position: absolute;
            top: 28%;
            left: 82%;
            transform: translate(-50%, -50%);
            -ms-transform: translate(-50%, -50%);
            text-align: center;
        }

        .container:hover .image {
            opacity: 0.8;
        }

        .container:hover .middle {
            opacity: 1;
        }

        .text {
            color: rgb(0, 0, 0);
            font-size: 16px;
        }
    </style>
@endsection
@section('content')

    <div class="row">
        <div class="col-lg-12">

            <div class="card">
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="d-flex ">
                            <div class="col-md-6">
                                <a style="float: left" href="{{ route('Dossier.show', $dossier->id) }}"
                                    class="btn btn-dark">Dossier</a>

                            </div>
                            <div class="col-md-6">
                                <a style="float: right" href="{{ route('Rapport.show', $rapport->id) }}"
                                    class="btn btn-primary">Rapport</a>

                            </div>
                        </div>
                    </div>

                </div>
                <div class="card-body">
                    <h4 class="header-title mb-3">Dossier {{ $dossier->ref }}</h4>
                    <input type="hidden" value="{{ $dossier->id }}" id="id">

                    <div class="table-responsive">
                        <table class="table mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Reference</th>
                                    <th>Matricule</th>
                                    <th>Compagnie</th>
                                    <th>Garantie</th>
                                    <th>Date Sinistre</th>
                                    <th>Type de Dossier</th>
                                    <th>Mode</th>
                                    <th>Vehicule</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>{{ $dossier->ref ?? null }}</td>
                                    <td>{{ $dossier->matricule ?? null }}</td>
                                    <td>{{ $dossier->company->company ?? null }}</td>
                                    <td>{{ $dossier->guarantee->guarantee ?? null }}</td>
                                    <td>{{ $dossier->date_sinistre ?? null }}</td>
                                    <td> <span
                                            class="badge badge-info-lighten">{{ $dossier->typeexpertise->type ?? null }}</span>
                                    </td>
                                    <td> <span
                                            class="badge badge-success-lighten">{{ $dossier->mode->mode ?? null }}</span>
                                    </td>
                                    <td>{{ $dossier->vehiculemodel->name ?? null }}/{{ $dossier->vehiculemodel->brand->brand ?? null }}
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <!-- end table-responsive -->
                </div>
            </div>
        </div> <!-- end col -->


    </div>

    <div class="row">
        <div class="col-6 mt-4">
            <input type="hidden" value="{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) }}"
                id="url">
            <div style="display: flex; justify-content: space-between;">
                <a class="btn btn-outline-primary mb-3"
                    href="{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) }}"
                    target="_blank">Télécharger Rapport</a>
                @if ($rapport->rapport_status_id != 2 && $rapport->rapport_status_id != 3)
                    <form action="{{ route('Rapport.regenerate', $rapport->id) }}" method="post">
                        @csrf
                        <button type="submit" class="btn btn-info">Regénérer Rapport</button>
                    </form>
                @endif
            </div>


            @if ($rapport->rapport_status_id == 4)
                @can('signer', App\Models\Rapport::class)
                    <form action="{{ route('rapport.status') }}" class="mb-1" method="POST">
                        @csrf
                        <input type="hidden" value="{{ $rapport->id }}" name="rapport_id">
                        <ul class="nav nav-tabs nav-stacked ">


                            <div class="col-4">
                                <button type="submit" class="ml-5 btn btn-danger" style="" name="action" value="0">
                                    Refuser </button>
                            </div>
                            <div class="col-4">
                                <button style="float: right" type="submit" class=" btn btn-success" name="action"
                                    value="1"> Signer </button>

                                <select class="form-select mt-1" name="position" id="">
                                    <option value="1">A Gauche</option>
                                    <option value="2">A Droite</option>
                                </select>

                            </div>
                        </ul>
                        <div class="col-md-6 mb-3">
                            <label for="date" class="form-label">Observation :</label>
                            <textarea class="form-control mb-2  @error('observation') is-invalid @enderror" name="observation" id=""
                                cols="10" rows="3"></textarea>
                            @error('observation')
                                <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                    </form>
                @endcan
            @elseif ($rapport->rapport_status_id == 2)
                @if (Auth::user()->role_id == 4 || Auth::user()->role_id == 1)
                    <form action="{{ route('rapport.status') }}" class="mb-1" method="POST">
                        @csrf
                        <input type="hidden" value="{{ $rapport->id }}" name="rapport_id">

                        <button type="submit" class="ml-5 btn btn-info mb-2" style="" name="action" value="2">
                            Envoyer
                        </button>

                    </form>
                @endif
            @else
                <div class="col-4">
                    <a class="btn btn-primary" target="_blank"
                        href="{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) }}">Display</a>
                </div>
                <h3>Rapport : <span class=" badge bg-{{ $rapport->status->color }}">{{ $rapport->status->status }}</span>
                </h3>
            @endif

            <div class="mt-1 mb-1 div">
                <button class="btn btn-sm btn-outline-info" id="prev">Précédent</button>
                &nbsp; &nbsp;
                <span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
                &nbsp; &nbsp;

                <button class="btn btn-sm btn-outline-info" id="next">Suivant</button>
            </div>
            <canvas id="the-canvas"></canvas>



        </div>
        <div class="col-6 mt-4">
            <div class="">
                <ul class="nav nav-tabs nav-stacked ">
                    @foreach ($typedocuments as $type)
                        <li class="nav-item ">
                            <button type="button" data-filter="{{ $type->type }}" class="link nav-link"
                                style=" cursor: pointer;" value="{{ $type->id }}">{{ $type->type }} </button>
                        </li>
                    @endforeach

                </ul>
                <div class="card-body m-1" id="galley" style="height: 300px; overflow-y:auto">
                    <input type="hidden" id="id" name="dossier_id" value="{{ $dossier->id }}">
                    @if ($dossier->document)
                        <ul style=" list-style-type: none;" id="row" class="row">
                            @foreach ($dossier->document as $doc)
                                @if ($doc->type_document_id != 10)
                                    <li class="box container col-3 media {{ $doc->typedocument->type }} ">
                                        <img data-original="{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) }}"
                                            src="{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) }}"
                                            alt="img" class="img-fluid m-1" srcset="">
                                        <div class="middle">
                                            <a data-bs-toggle="modal" data-bs-target="#exampleModal" href=""
                                                class="text icon dripicons-document-edit"></a>
                                        </div>
                                        <span class="badge bg-primary m-1"
                                            style="display: block;">{{ $doc->typedocument->type ?? null }}</span>
                                    </li>
                                @endif
                            @endforeach


                        </ul>
                    @endif
                </div>


            </div>
        </div>
    </div>
    <div class="row mt-2">
        <div class="col-lg-6">
            <div class="card">
                <div class="card-body">

                    <h4 class="header-title mb-3" style="color: black">Observation</h4>
                    @if ($observations)
                        <div class="accordion" id="">
                            @foreach ($observations as $key => $observation)
                                <div class="accordion-item">
                                    <h2 class="accordion-header" id="headingOne" style="margin-top: unset;">
                                        <button class="accordion-button collapsed" type="button"
                                            data-bs-toggle="collapse" data-bs-target="#collapse-{{ $key }}"
                                            aria-expanded="false" aria-controls="">
                                            {{ $observation->user->name }}
                                        </button>
                                    </h2>
                                    <div id="collapse-{{ $key }}" class="accordion-collapse collapse "
                                        aria-labelledby="headingOne" data-bs-parent="#accordionExample">
                                        <div class="accordion-body">
                                            <strong class="text-dark">{{ $observation->observation }}.</strong>
                                            <span>{{ $observation->created_at }}</span>
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @endif
                    <form method="POST" action="{{ route('Observation.store') }}">
                        @csrf
                        <div class="col-md-12 mt-1 ml-3">
                            <input type="hidden" name="for_rapport" value="1">
                            <input type="hidden" name="dossier_id" value="{{ $dossier->id }}">
                            <input type="hidden" name="rapport_id" value="{{ $rapport->id }}">
                            <textarea name="observation" class="form-control mb-2" id="observation" cols="30" rows="10"></textarea>

                            <button class="mt-2 btn btn-info">Créer</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    </div>
@endsection
@section('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.worker.min.js"></script>
    <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <script src="{{ asset('js/viewer.js') }}"></script>
    <script>
        var $mediaElements = $('.media');

        $('.link').click(function(e) {
            e.preventDefault();
            // get the category from the attribute
            var filterVal = $(this).data('filter');
            console.log(filterVal);
            var type_id = this.value;
            if (filterVal === 'AA') {
                $mediaElements.show();
            } else {
                // hide all then filter the ones to show
                $mediaElements.hide().filter('.' + filterVal).show();
            }
        });
        // $(document).ready(function() {
        //     $('.link').on('click', function() {

        //         var type_id = this.value;
        //         var dossier_id = jQuery('#id').val();
        //         $(".box").remove();
        //         var divs = document.getElementsByClassName('type_id')
        //         // $.ajax({
        //         //     url: '/Document/' + dossier_id + '/Type/' + type_id,
        //         //     type: 'get',
        //         //     context: this,

        //         //     success: function(response) {

        //         //         $.each(response, function(key, value) {
        //         //             console.log(value);
        //         //             $("#row").append(
        //         //                 '<li class=\"box col-3 container\"> <img  data-original="' +
        //         //                 value + '"  src="' +
        //         //                 value +
        //         //                 '"  class=\"img-fluid m-1\" > <div class=\"middle\">      <a href="" class=\"text icon dripicons-document-edit\"></a> </div> <span class=\"badge bg-primary m-1\" style=\"display: block;\">Avant</span></li>'
        //         //             );
        //         //         });
        //         //     },
        //         // });
        //     });
        // });
    </script>


    <script>
        window.addEventListener('load', function() {
            console.log('DOM fully loaded and parsed');
            var galley = document.getElementById('galley');
            var maxOffsetPercentage = 0.9;
            var viewer = new Viewer(galley, {
                url: 'data-original',
                backdrop: 'static',
                move: function(event) {
                    var viewerData = viewer.viewerData;
                    var imageData = viewer.imageData;
                    var maxOffsetHorizontal = viewerData.width * maxOffsetPercentage;
                    var maxOffsetVertical = viewerData.height * maxOffsetPercentage;
                    var detail = event.detail;
                    var left = detail.x;
                    var top = detail.y;
                    var right = viewerData.width - (left + imageData.width);
                    var bottom = viewerData.height - (top + imageData.height);
                    if (
                        // Move left
                        (detail.x < detail.oldX && right > 0 && right > maxOffsetHorizontal)
                        // Move right
                        ||
                        (detail.x > detail.oldX && left > 0 && left > maxOffsetHorizontal)
                        // Move up
                        ||
                        (detail.y < detail.oldY && bottom > 0 && bottom > maxOffsetVertical)
                        // Move down
                        ||
                        (detail.y > detail.oldY && top > 0 && top > maxOffsetVertical)
                    ) {
                        event.preventDefault();
                    }
                },
                zoomed: function(event) {
                    var detail = event.detail;
                    // Zoom out
                    if (detail.ratio < detail.oldRatio) {
                        var viewerData = viewer.viewerData;
                        var imageData = viewer.imageData;
                        var maxOffsetHorizontal = viewerData.width * maxOffsetPercentage;
                        var maxOffsetVertical = viewerData.height * maxOffsetPercentage;
                        var left = imageData.x;
                        var top = imageData.y;
                        var right = viewerData.width - (left + imageData.width);
                        var bottom = viewerData.height - (top + imageData.height);
                        var x = 0;
                        var y = 0;
                        if (right > 0 && right > maxOffsetHorizontal) {
                            x = maxOffsetHorizontal - right;
                        }
                        if (left > 0 && left > maxOffsetHorizontal) {
                            x = maxOffsetHorizontal - left;
                        }

                        if (bottom > 0 && bottom > maxOffsetVertical) {
                            y = bottom - maxOffsetVertical;
                        }

                        if (top > 0 && top > maxOffsetVertical) {
                            y = top - maxOffsetVertical;
                        }

                        // Move the image into view if it is invisible
                        if (x !== 0 || y !== 0) {
                            viewer.move(x, y);
                        }
                    }
                },
            });
        });
        var links = document.getElementsByClassName('link');
        for (var i = 0; i < links.length; i++) {

            links[i].addEventListener('click', function() {
                console.log('clcl');
                var galley = document.getElementById('galley');
                var maxOffsetPercentage = 0.9;
                var viewer = new Viewer(galley, {
                    url: 'data-original',
                    backdrop: 'static',
                    move: function(event) {
                        var viewerData = viewer.viewerData;
                        var imageData = viewer.imageData;
                        var maxOffsetHorizontal = viewerData.width * maxOffsetPercentage;
                        var maxOffsetVertical = viewerData.height * maxOffsetPercentage;
                        var detail = event.detail;
                        var left = detail.x;
                        var top = detail.y;
                        var right = viewerData.width - (left + imageData.width);
                        var bottom = viewerData.height - (top + imageData.height);
                        if (
                            // Move left
                            (detail.x < detail.oldX && right > 0 && right > maxOffsetHorizontal)
                            // Move right
                            ||
                            (detail.x > detail.oldX && left > 0 && left > maxOffsetHorizontal)
                            // Move up
                            ||
                            (detail.y < detail.oldY && bottom > 0 && bottom > maxOffsetVertical)
                            // Move down
                            ||
                            (detail.y > detail.oldY && top > 0 && top > maxOffsetVertical)
                        ) {
                            event.preventDefault();
                        }
                    },
                    zoomed: function(event) {
                        var detail = event.detail;
                        // Zoom out
                        if (detail.ratio < detail.oldRatio) {
                            var viewerData = viewer.viewerData;
                            var imageData = viewer.imageData;
                            var maxOffsetHorizontal = viewerData.width * maxOffsetPercentage;
                            var maxOffsetVertical = viewerData.height * maxOffsetPercentage;
                            var left = imageData.x;
                            var top = imageData.y;
                            var right = viewerData.width - (left + imageData.width);
                            var bottom = viewerData.height - (top + imageData.height);
                            var x = 0;
                            var y = 0;
                            if (right > 0 && right > maxOffsetHorizontal) {
                                x = maxOffsetHorizontal - right;
                            }
                            if (left > 0 && left > maxOffsetHorizontal) {
                                x = maxOffsetHorizontal - left;
                            }

                            if (bottom > 0 && bottom > maxOffsetVertical) {
                                y = bottom - maxOffsetVertical;
                            }

                            if (top > 0 && top > maxOffsetVertical) {
                                y = top - maxOffsetVertical;
                            }

                            // Move the image into view if it is invisible
                            if (x !== 0 || y !== 0) {
                                viewer.move(x, y);
                            }
                        }
                    },
                });
            });
        }
    </script>
    <script>
        // If absolute URL from the remote server is provided, configure the CORS
        // header on that server.

        var url = document.getElementById('url').value;
        // Loaded via <script> tag, create shortcut to access PDF.js exports.
        var pdfjsLib = window['pdfjs-dist/build/pdf'];
        // The workerSrc property shall be specified.
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.worker.min.js';

        var pdfDoc = null,
            pageNum = 1,
            pageRendering = false,
            pageNumPending = null,
            scale = 0.8,
            canvas = document.getElementById('the-canvas'),
            ctx = canvas.getContext('2d');

        /**
         * Get page info from document, resize canvas accordingly, and render page.
         * @param num Page number.
         */
        function renderPage(num) {
            pageRendering = true;
            // Using promise to fetch the page
            pdfDoc.getPage(num).then(function(page) {
                var viewport = page.getViewport({
                    scale: scale
                });
                canvas.height = viewport.height;
                canvas.width = viewport.width;

                // Render PDF page into canvas context
                var renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                };
                var renderTask = page.render(renderContext);

                // Wait for rendering to finish
                renderTask.promise.then(function() {
                    pageRendering = false;
                    if (pageNumPending !== null) {
                        // New page rendering is pending
                        renderPage(pageNumPending);
                        pageNumPending = null;
                    }
                });
            });

            // Update page counters
            document.getElementById('page_num').textContent = num;
        }

        /**
         * If another page rendering in progress, waits until the rendering is
         * finised. Otherwise, executes rendering immediately.
         */
        function queueRenderPage(num) {
            if (pageRendering) {
                pageNumPending = num;
            } else {
                renderPage(num);
            }
        }

        /**
         * Displays previous page.
         */
        function onPrevPage() {
            if (pageNum <= 1) {
                return;
            }
            pageNum--;
            queueRenderPage(pageNum);
        }
        document.getElementById('prev').addEventListener('click', onPrevPage);

        /**
         * Displays next page.
         */
        function onNextPage() {
            if (pageNum >= pdfDoc.numPages) {
                return;
            }
            pageNum++;
            queueRenderPage(pageNum);
        }
        document.getElementById('next').addEventListener('click', onNextPage);

        /**
         * Asynchronously downloads PDF.
         */
        pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
            pdfDoc = pdfDoc_;
            document.getElementById('page_count').textContent = pdfDoc.numPages;

            // Initial/first page rendering
            renderPage(pageNum);
        });

        var $mediaElements = $('.media');
        var canvas = document.getElementById("the-canvas");

        var ctx = canvas.getContext('2d');

        ctx.fillStyle = "rgb(0,255,255)";
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        ctx.beginPath();
        ctx.fillStyle = "rgb(200,0,0)";
        ctx.arc(canvas.width / 2, canvas.height / 2, 50, 0, Math.PI * 2);
        ctx.fill();
    </script>
@endsection
