@extends('layouts.app')

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

    .c3-tooltip-container {
        background-color: #ffffff;
        border-radius: 0.25em;
        min-width: 180px !important;
        width: auto !important;
        max-width: 300px;
        min-width: 10%;
        padding: 20px;
        box-shadow: 0 0 1px rgba(0, 0, 0, .125),
            0 1px 3px rgba(0, 0, 0, .2);
        pointer-events: auto !important;
    }

    .c3-text {
        transform: translateX(-25px) !important;
        fill: #000 !important;
    }

    .c3 .c3-grid line {
        stroke-opacity: 0.3;
        stroke-width: 1px;
    }

    .c3-xgrid,
    .c3-ygrid {
        stroke-dasharray: 0 0;
    }
</style>

@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('charts.index') }}">Charts</a></li>
                        <li class="breadcrumb-item">{{ $chart->name }}</li>
                    </ol>
                </div>
            </div>
            <div class="row mb-2 mt-2">
                <div class="col-sm-8">
                    <h2 style="font-weight: bold">{{ ucwords($chart->getResourceConfiguration('title')) }}</h2>
                    <h6>{{ $chart->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="buttons text-right mb-4">
                <a id="print-chart" href="#" class="btn btn-light py-3 px-4 btn-xl shadow-sm mx-4">
                    <i class="fa-solid fa-print"></i> Print
                </a>
                <a href="#" class="btn btn-light py-3 px-3 shadow-sm" id="export-chart">
                    <i class="fa-solid fa-file-export"></i> Export
                </a>

                <form id="chartExportForm" action="{{ route('charts.details.export',$chart->id) }}" method="POST"
                    style="display: none;">
                    @csrf
                    <input type="hidden" id="chartImageData" name="chartImageData">
                </form>

                <form id="chartPrintForm" action="{{ route('charts.details.print',$chart->id) }}" method="POST"
                    style="display: none;">
                    @csrf
                    <input type="hidden" id="chartPrintImageData" name="chartPrintImageData">
                </form>


            </div>
            <div>
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr style="background-color: #d6d8da">
                            <th>{{ ucwords($chart->getResourceConfiguration('x_axis_column')) }}</th>
                            <th>{{ !empty($chart->getResourceConfiguration('label')) ?
                                ucwords($chart->getResourceConfiguration('label')) :
                                ucwords($chart->getResourceConfiguration('y_axis_column'))}}</th>
                            @if($chart->getResourceConfiguration('drill_down'))
                            <th></th>
                            @endif
                        </tr>
                    </thead>
                    <tbody>
                        @foreach(array_combine($chart->data['x_axis'],$chart->data['y_axis']) as $x_axis =>$y_axis)
                        <tr class="smaller-font">
                            <td>
                                @if($chart->getResourceConfiguration('date_time_scale') == "months")
                                {{Illuminate\Support\Carbon::parse($x_axis)->format('Y-m') }}
                                @elseif($chart->getResourceConfiguration('date_time_scale') == "years")
                                {{Illuminate\Support\Carbon::parse($x_axis)->format('Y') }}
                                @else
                                {{ $x_axis }}
                                @endif
                            </td>
                            <td>{{ $y_axis }}</td>

                            @if($chart->getResourceConfiguration('drill_down'))
                            <th><a href="{{route('charts.drill',[$chart->id]) . '?xValue=' . $x_axis}}"
                                    class="text-primary" style="color:black;
                                text-decoration: underline;
                                font-weight:normal
                                ">Details</a> </th>
                            @endif
                        </tr>
                        @endforeach
                    </tbody>
                </table>

            </div>

            <div class="card card-primary card-outline">
                <div class="card-header">
                    <h3 class="card-title" style="color:black;font-weight:bold">
                        @if($chart->getResourceConfiguration('chart_link'))
                        <a href="{{ route('charts.details',$chart->id) }}" style="color:black">{{
                            $chart->getResourceConfiguration('title') }}</a>
                        @else
                        {{ $chart->getResourceConfiguration('title') }}
                        @endif
                    </h3>
                </div>
                <div class="card-body">
                    <div id="{{ Str::of($chart->name)->kebab() }}"></div>
                    <canvas id="chartCanvas" style="display: none;"></canvas>

                </div>

            </div>

        </div>

</div>


@endsection


@section('scripts')
<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>
    {!! $chart->script !!}
d3.selectAll(".c3")
    .selectAll("text")
    .style("font-family", "poppins, arial");


</script>
@php
$chartID = Str::of($chart->name)->kebab();
$chartName = Str::of($chart->name)->camel();
@endphp
<script src="{{ get_asset('dist/js/html2canvas.min.js') }}"></script>

<script>
    function exportChartImage(element,form) {

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

    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();

        $.ajax({
            type: 'POST',
            url: $("#" + form).attr('action'),
            data: $("#" + form).serialize(),
            xhrFields:{
                responseType: 'blob'
            },
            beforeSend:function(){
                $("#global-loader").fadeIn();
                $("#global-loader .loader-text").html('Please wait, this may take a few minutes.');

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

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

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


    });

    }

    function printChartImage(element,form) {

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

        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;

            $("#global-loader .loader-text").html('Please wait, this may take a few minutes.');

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



        });

        }

    $(document).on('click','#export-chart',function(e){
        e.preventDefault();
        exportChartImage('chartImageData','chartExportForm');

    });

    $(document).on('click','#print-chart',function(e){
        e.preventDefault();
        printChartImage('chartPrintImageData','chartPrintForm');
    });

</script>

@endsection