@extends('layouts.app')

@section('content')
{{--*/ usort($tableGrid, "SiteHelpers::_sort") /*--}}
<div class="page-titles">
  <h2> {{ $pageTitle }} <small> {{ $pageNote }} </small></h2>
</div>
<div  class="card">
	<div class="card-body">
		<div class="toolbar-nav">
			<div class="row">
                <div class="col-md-12">
                    <form class="form-inline d-flex flex-wrap align-items-end gap-3">
                        @php
                            $tanggal_akhir = request('tanggal_akhir') ?? date('Y-m-d', strtotime('-1 day'));
                            $tanggal_awal = request('tanggal_awal') ?? date('Y-m-d', strtotime('-7 days'));
                        @endphp

                        <input type="date" class="form-control mb-2" id="tanggal_awal" name="tanggal_awal" value="{{ $tanggal_awal }}">
                        <input type="date" class="form-control mb-2" id="tanggal_akhir" name="tanggal_akhir" value="{{ $tanggal_akhir }}">

                        <select class="form-control mb-2" id="cluster" name="cluster">
                            <option value="">-- Pilih Cluster --</option>
                            <option value="SUMATERA 1" {{ request('cluster') == 'SUMATERA 1' ? 'selected' : '' }}>SUMATERA 1</option>
                            <option value="SUMATERA 2" {{ request('cluster') == 'SUMATERA 2' ? 'selected' : '' }}>SUMATERA 2</option>
                            <option value="JATENG" {{ request('cluster') == 'JATENG' ? 'selected' : '' }}>JATENG</option>
                            <option value="JATIM 1" {{ request('cluster') == 'JATIM 1' ? 'selected' : '' }}>JATIM 1</option>
                            <option value="JATIM 2" {{ request('cluster') == 'JATIM 2' ? 'selected' : '' }}>JATIM 2</option>
                            <option value="SULAWESI" {{ request('cluster') == 'SULAWESI' ? 'selected' : '' }}>SULAWESI</option>
                        </select>

                        <select class="form-control mb-2" id="kebun" name="kebun">

                        </select>

                        <select class="form-control mb-2" id="jenis_report" name="jenis_report">
                            <option value="">-- Pilih Jenis Report --</option>
                            <option value="ha" {{ request('jenis_report') == 'ha' ? 'selected' : '' }}>HA</option>
                            <option value="ton" {{ request('jenis_report') == 'ton' ? 'selected' : 'selected' }}>TON</option>
                            <option value="protas" {{ request('jenis_report') == 'protas' ? 'selected' : '' }}>PROTAS</option>
                        </select>

                        <button type="submit" class="btn btn-primary mb-2">Filter</button>
                        <button type="button" class="btn btn-success mb-2" id="download-excel">Download Excel</button>
                        <button type="button" class="btn btn-danger mb-2" id="download-pdf">Download PDF</button>

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

	


		 <div class="table-responsive" style="min-height:300px;">
	    
		<input type="hidden" name="md" value="" />
		</div>

		    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
		                        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
                        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
        <script>
        $(document).ready(function() {
                        $("#kebun").jCombo("{!! url('dataprodisconsole/comboselect?filter=master_kebun:kode_kebun:nama_kebun') !!}",
			{  initial_text : 'Pilih Kebun' });


            // Highlight row in column 3 if it contains text 'TOTAL'


            $('#download-pdf').on('click', function(e) {
                e.preventDefault();
                var table = $('.table-responsive').find('table').get(0);
                if(table) {
                    // Right-align columns starting from column 5
                    $(table).find('tr').each(function() {
                        $(this).find('td,th').each(function(idx) {
                            if(idx >= 4) {
                                $(this).css('text-align', 'right');
                            }
                        });
                    });

                    html2canvas(table, {scrollY: -window.scrollY}).then(function(canvas) {
                        var imgData = canvas.toDataURL('image/png');
                        var pdf = new jspdf.jsPDF('l', 'pt', 'a4');
                        var pageWidth = pdf.internal.pageSize.getWidth();
                        var pageHeight = pdf.internal.pageSize.getHeight();

                        // Add title
                        pdf.setFontSize(16);
                        pdf.text('REALISASI PRODUKSI HARIAN KEBUN', pageWidth / 2, 30, { align: 'center' });
                        pdf.setFontSize(12);
                        pdf.text('BERDASARKAN PG PENGGILING', pageWidth / 2, 50, { align: 'center' });

                        var imgWidth = pageWidth - 40;
                        var imgHeight = canvas.height * imgWidth / canvas.width;
                        var y = 70; // Start below the title

                        // If the image is taller than one page, split across pages
                        var position = y;
                        var remainingHeight = imgHeight;
                        var pageImgHeight = pageHeight - y - 20;

                        var pageCanvas = document.createElement('canvas');
                        var pageCtx = pageCanvas.getContext('2d');
                        var sX = 0, sY = 0, sWidth = canvas.width, sHeight, dWidth = imgWidth, dHeight;

                        while (remainingHeight > 0) {
                            sHeight = Math.floor((pageImgHeight * canvas.width) / imgWidth);
                            if (sY + sHeight > canvas.height) {
                                sHeight = canvas.height - sY;
                            }
                            // Ensure sHeight is at least 1 to avoid corrupt PNG
                            if (sHeight < 1) sHeight = 1;
                            dHeight = (sHeight * imgWidth) / canvas.width;

                            pageCanvas.width = canvas.width;
                            pageCanvas.height = sHeight;
                            pageCtx.clearRect(0, 0, canvas.width, sHeight);
                            pageCtx.drawImage(canvas, sX, sY, sWidth, sHeight, 0, 0, sWidth, sHeight);

                            var pageImgData = pageCanvas.toDataURL('image/png');
                            pdf.addImage(pageImgData, 'PNG', 20, position, imgWidth, dHeight);

                            remainingHeight -= dHeight;
                            sY += sHeight;

                            if (remainingHeight > 0) {
                                pdf.addPage();
                                position = 20;
                            }
                        }

                        pdf.save('rekap_timbangan.pdf');
                    });
                
                } else {
                    alert('Tabel tidak ditemukan untuk diunduh.');
                }
            });
              $('#download-excel').on('click', function(e) {
                                e.preventDefault();
                                var tanggal_awal = $('#tanggal_awal').val();
                                var tanggal_akhir = $('#tanggal_akhir').val();
                                var cluster = $('#cluster').val();
                                var kebun = $('#kebun').val();
                                var jenis_report = $('#jenis_report').val();

                                $.ajax({
                                    url: '{{ url("rekaptimbhariankebunpg/getTable") }}',
                                    type: 'GET',
                                    data: {
                                        tanggal_awal: tanggal_awal,
                                        tanggal_akhir: tanggal_akhir,
                                        cluster: cluster,
                                        kebun: kebun,
                                        jenis_report: jenis_report,
                                        download: 1 // optional, if you want to handle differently on backend
                                    },
                                    headers: {
                                        'X-Requested-With': 'XMLHttpRequest'
                                    },
                                    success: function(html) {
                                        // Create a temporary DOM to extract the table
                                        var tempDiv = $('<div>').html(html);
                                        var table = tempDiv.find('table').get(0);
                                        if(table) {
                                            var wb = XLSX.utils.table_to_book(table, {sheet:"Sheet1"});
                                            XLSX.writeFile(wb, 'rekap_timbangan.xlsx');
                                        } else {
                                            alert('Tabel tidak ditemukan untuk diunduh.');
                                        }
                                    }
                                });
                            });
            function fetchTable() {
                var tanggal_awal = $('#tanggal_awal').val();
                var tanggal_akhir = $('#tanggal_akhir').val();
                var cluster = $('#cluster').val();
                var kebun = $('#kebun').val();
                var jenis_report = $('#jenis_report').val();

                // Show loading indicator
                $('.table-responsive').html('<div class="text-center py-5"><span class="spinner-border" role="status" aria-hidden="true"></span> Loading...</div>');

                $.ajax({
                    url: '{{ url("rekaptimbhariankebunpg/getTable") }}',
                    type: 'GET',
                    data: {
                        tanggal_awal: tanggal_awal,
                        tanggal_akhir: tanggal_akhir,
                        cluster: cluster,
                        kebun: kebun,
                        jenis_report: jenis_report
                    },
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    success: function(html) {
                        $('.table-responsive').html(html);


                                      var table = $('.table-responsive').find('table').get(0);
                                        // Right-align columns starting from column 5
                                        $(table).find('tr').each(function() {
                                            $(this).find('td,th').each(function(idx) {
                                                if(idx >= 4) {
                                                    $(this).css('text-align', 'right');
                                                }                                                
                                            });
                                            var cell = $(this).find('td:eq(2),th:eq(2)');
                                                if (cell.length && cell.text().toUpperCase().includes('TOTAL')) {
                                                    $(this).css('background-color', 'rgb(228 239 245)'); // light yellow
                                                }
                                        });

                    }
                });
            }

            $('.btn.btn-primary').on('click', function(e) {
                e.preventDefault();
                fetchTable();
            });

            // Optionally, fetch table on page load
            fetchTable();
        });
        </script>
		@include('footer')
	</div>  
</div>
@stop