@extends('layouts.app')

@section('styles')
<style>
    .content-wrapper>* {
        font-family: 'poppins', 'arial';
    }
</style>
<link rel="stylesheet" href="{{ get_asset('dist/css/c3.min.css') }}" />
<link rel="stylesheet" href="{{ get_asset('dist/css/metrics.css') }}" />

@endsection

@section('content')

<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <div class="container-fluid px-4">
            <div class="row mt-2">
                <div class="col-sm-6">
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="{{ route('home') }}">Home</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('metrics.index') }}">Metrics</a></li>
                        <li class="breadcrumb-item">{{ $metric->name }}</li>
                    </ol>
                </div>
            </div>
            <div class="row mb-2 mt-2">
                <div class="col-sm-8">
                    <h2 style="font-weight: bold">{{ ucwords($metric->getResourceConfiguration('title')) }}
                    </h2>
                    <h6>{{ $metric->created_at->format('d M Y h:i A') }}</h6>
                </div>
                <div class="col-sm-4 text-right">
                    <div class="p-2 branding-logo">
                        @include('partials._logo')
                    </div>
                </div>
            </div>
            <hr style="border-top: 1px solid rgba(0, 0, 0, .5);">
        </div>
        <div class="container-fluid mt-4 px-4">
            <div class="row">
                <div class="col-6">
                    {{-- @dd($metric) --}}
                    {!! $metric->drillTooltip !!}
                </div>
                <div class="col-6">
                    <div class="buttons text-right mb-4">
                        <a href="{{ route('metrics.drill.print',[$metric->id]) }}" id="print-metric"
                            class="btn btn-light py-3 px-4 btn-xl shadow-sm mx-4" style="display: inline-block">
                            <i class="fa-solid fa-print"></i> Print
                        </a>
                        <a href="{{ route('metrics.drill.export',[$metric->id]) }}" id="export-metric"
                            class="btn btn-light py-3 px-3 shadow-sm" style="display: inline-block">
                            <i class="fa-solid fa-file-export"></i> Export
                        </a>

                        <form id="metricExportForm" action="{{ route('metrics.drill.export',$metric->id) }}"
                            method="POST" style="display: none;">
                            @csrf
                            <input type="hidden" name="page" value="{{ $data->currentPage() }}">

                            <input type="hidden" id="metricImageData" name="metricImageData">
                        </form>

                        <form id="metricPrintForm" action="{{ route('metrics.drill.print',$metric->id) }}" method="POST"
                            style="display: none;">
                            @csrf
                            <input type="hidden" name="page" value="{{ $data->currentPage() }}">
                            <input type="hidden" id="metricPrintImageData" name="metricPrintImageData">
                        </form>

                    </div>
                </div>

            </div>
            <div class="clearfix"></div>

            <div class="table table-bordered table-striped" style="overflow-x: auto;word-break:keep-all;">
                <table id="reports" style="width: 100%">
                    <thead>
                        <tr style="background-color: #d6d8da">
                            @foreach($keys as $key)
                            <th>{{ ucwords($key) }}</th>
                            @endforeach
                        </tr>
                    </thead>
                    <tbody>
                        @if($data->total() > 0)
                        @foreach($data as $row)
                        <tr class="smaller-font">
                            @foreach($row as $item)

                            <td>{{ $item }}</td>
                            @endforeach
                        </tr>
                        @endforeach
                        @else
                        <tr style="background-color:transparent">
                            <td style="text-align: center" colspan="{{ count($keys) }}">
                                <h6>Sorry, There is no data</h6>
                            </td>
                        </tr>
                        @endif
                    </tbody>
                </table>
            </div>
            <div class="float-right">
                {{ $data->links() }}
            </div>
            <div class="clearfix"></div>
            @if($metric->getResourceConfiguration('compare_with') !='no_comparison')
            <div class="card card-primary card-outline">
                <div class="card-header">
                    <h3 class="card-title" style="color:black;font-weight:bold">
                        {{ $metric->getResourceConfiguration('title') }}
                    </h3>
                </div>
                <div class="card-body">
                    @php
                    $metricID = Str::of($metric->name)->kebab();
                    @endphp
                    <div id="{{ $metricID }}"></div>
                    <canvas id="chartCanvas" style="display: none;"></canvas>

                </div>

            </div>
            @endif

        </div>

</div>


@endsection


@section('scripts')
@if($metric->getResourceConfiguration('compare_with') !='no_comparison')

<script src="{{ get_asset('dist/js/moment.min.js')}}"></script>
<script src="{{ get_asset('dist/js/d3.v5.min.js')}}"></script>
<script src="{{ get_asset('dist/js/c3.min.js')}}"></script>
<script src="{{ get_asset('dist/js/charts.js')}}"></script>
<script>
    {!! $metric->script !!}
</script>
<script src="{{ get_asset('dist/js/html2canvas.min.js') }}"></script>

<script>
    function exportMetricImage(element,form) {

    var metric = document.getElementById("{{ $metricID }}");

    html2canvas(metric, {
        backgroundColor: null,
        scale: 1.5,
        logging: false
    }).then(function(canvas) {
        // Convert the canvas to a data URL (PNG format)
        var metricImage = canvas.toDataURL('image/png');

        // Set the metric image data in a hidden input field within the form
        document.getElementById(element).value = metricImage;

        $.ajax({
            type: 'POST',
            url: $("#" + form).attr('action'),
            data: $("#" + form).serialize(),
            xhrFields:{
                responseType: 'blob'
            },
            beforeSend:function(){
                $("#global-loader").fadeIn();
            },
            success: function(response) {
                var blob = new Blob([response]);
                var link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = "{{ ucwords($metric->getResourceConfiguration('title')) . '-page ' . $data->currentPage() }}.pdf";
                link.click();

                $("#global-loader").fadeOut("slow");
            },
            error: function(xhr, status, error) {
                console.error(error);
            }
        });


    });

    }

    function printMetricImage(element,form) {

        var chart = document.getElementById("{{ $metricID }}");

        html2canvas(chart, {
            backgroundColor: null,
            scale: 1.5,
            logging: false
        }).then(function(canvas) {
            // Convert the canvas to a data URL (PNG format)
            var chartImage = canvas.toDataURL('image/png');

            // Set the chart image data in a hidden input field within the form
            document.getElementById(element).value = chartImage;

            // Submit the form
            document.getElementById(form).submit();



        });

    }


    $(document).on('click','#export-metric',function(e){
        e.preventDefault();
        $("#global-loader .loader-text").html('Please wait, this may take a few minutes.');

        exportMetricImage('metricImageData','metricExportForm');

    });

    $(document).on('click','#print-metric',function(e){
        e.preventDefault();
        $("#global-loader .loader-text").html('Please wait, this may take a few minutes.');

        printMetricImage('metricPrintImageData','metricPrintForm');
    });

</script>
@else
<script>
    function printMetricPage(form)
    {

        document.getElementById(form).submit();
    }

    function exportMetricPage(form)
    {
        $.ajax({
            type: 'POST',
            url: $("#" + form).attr('action'),
            data: $("#" + form).serialize(),
            xhrFields:{
                responseType: 'blob'
            },
            beforeSend:function(){
                $("#global-loader").fadeIn();

            },
            success: function(response) {
                var blob = new Blob([response]);
                var link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = "{{ ucwords($metric->getResourceConfiguration('title'))  . '-page ' . $data->currentPage()}}.pdf";
                link.click();

                $("#global-loader").fadeOut("slow");
                $("#global-loader .loader-text").html('');

            },
            error: function(xhr, status, error) {
                console.error(error);
            }
        });

    }

    $(document).on('click','#export-metric',function(e){
        e.preventDefault();
        $("#global-loader .loader-text").html('Please wait, this may take a few minutes.');

        exportMetricPage('metricExportForm');

    });

    $(document).on('click','#print-metric',function(e){
        e.preventDefault();
        $("#global-loader .loader-text").html('Please wait, this may take a few minutes.');

        printMetricPage('metricPrintForm');
    });
</script>
@endif
@endsection