<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{ get_phrase('Download Certificate') }}</title>
    <link rel="shortcut icon" href="{{ asset(get_frontend_settings('favicon')) }}" />
    <script src="{{ asset('assets/frontend/default/js/jquery-3.7.1.min.js') }}"></script>
    <script src="{{ asset('assets/global/html2canvas/html2canvas.min.js') }}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
</head>

<body>
    <style>
        html, body{
            overflow-x: hidden;
        }
        body {
            position: relative;
        }

        .remove-item,
        .ui-resizable-handle {
            display: none !important;
        }

           .certificate-layout-module {
        left: unset !important;
        top: unset !important;
        margin-left: auto !important;
        margin-right: auto !important;
    }

    svg {
        width: 100%;
        height: 100%;
    }

    .download-wrapper {
        position: fixed;
        bottom: 20px;
        right: 20px;
        display: flex;
        gap: 15px;
        z-index: 100;
    }

    .download-btn {
        padding: 12px 24px;
        border-radius: 8px;
        color: #ffffff;
        background: linear-gradient(135deg, #3d9bff 0%, #0066cc 100%);
        border: none;
        font-weight: 600;
        font-size: 16px;
        text-decoration: none;
        box-shadow: 0 4px 12px rgba(61, 155, 255, 0.3);
        cursor: pointer;
        transition: all 0.3s ease;
        display: inline-block;
        white-space: nowrap;
        text-align: center;
        min-width: 160px;
    }

    .download-btn.secondary {
        background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
        box-shadow: 0 4px 12px rgba(108, 117, 125, 0.3);
    }

    .download-btn.secondary:hover {
        background: linear-gradient(135deg, #5a6268 0%, #3d4349 100%);
        box-shadow: 0 6px 16px rgba(108, 117, 125, 0.4);
    }

    .download-btn:hover {
        background: linear-gradient(135deg, #2d8bef 0%, #0055b3 100%);
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(61, 155, 255, 0.4);
    }

    .download-btn:active {
        transform: translateY(0);
        box-shadow: 0 2px 8px rgba(61, 155, 255, 0.3);
    }

    .download-btn:focus {
        outline: 2px solid rgba(61, 155, 255, 0.5);
        outline-offset: 2px;
    }

    /* Responsive untuk mobile */
    @media (max-width: 768px) {
        .download-btn {
            bottom: 16px;
            right: 16px;
            padding: 10px 20px;
            font-size: 14px;
        }
    }

        .absolute-view{
            background-color: #e6e6e6;
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            overflow-y: auto;
            z-index: 50;
            width: 100%;
        }

        .certificate_builder_view{
            width: 60%;
            height: auto;
            min-width: 350px;
            margin-left: auto;
            margin-right: auto;
            padding-top: 60px;
        }
    </style>


    {{-- Downloadable canvas --}}
    <div class="captureCertificate" id="captureCertificate">
        @php
            $bulan_indonesia = [
                1 => 'Januari',
                2 => 'Februari',
                3 => 'Maret',
                4 => 'April',
                5 => 'Mei',
                6 => 'Juni',
                7 => 'Juli',
                8 => 'Agustus',
                9 => 'September',
                10 => 'Oktober',
                11 => 'November',
                12 => 'Desember'
            ];
            
            // Jika date_formatter() mengembalikan tanggal string
            $completion_date = $certificate->created_at; // Ambil timestamp asli
            
            // Konversi ke format Indonesia
            $timestamp = strtotime($completion_date); // atau $completion_date jika sudah timestamp
            $hari = date('j', $timestamp); // tanggal tanpa nol
            $bulan_angka = (int)date('n', $timestamp); // bulan angka
            $tahun = date('Y', $timestamp);
            
            $course_completion_date = $hari . ' ' . $bulan_indonesia[$bulan_angka] . ' ' . $tahun;
            $course_duration = $certificate->course->total_duration();
            $student_name = $certificate->user->name;
            $course_title = $certificate->course->title;
            $number_of_lesson = $certificate->course->lessons->count();
            $qr_code = $qrcode;
            $certificate_id = $certificate->identifier;
            $certificate_download_date = date('d M Y');
            $course_level = ucfirst($certificate->course->level);
            $course_language = ucfirst($certificate->course->language);
            $instructor_name = '';

            foreach ($certificate->course->instructors() as $instructor) {
                $instructor_name .= '<p>' . $instructor->name . '</p>';
            }

            $certificate_builder_content = get_settings('certificate_builder_content');
            $certificate_builder_content = str_replace('{course_duration}', $course_duration, $certificate_builder_content);
            $certificate_builder_content = str_replace('{instructor_name}', $instructor_name, $certificate_builder_content);
            $certificate_builder_content = str_replace('{student_name}', $student_name, $certificate_builder_content);
            $certificate_builder_content = str_replace('{course_title}', $course_title, $certificate_builder_content);
            $certificate_builder_content = str_replace('{number_of_lesson}', $number_of_lesson, $certificate_builder_content);
            $certificate_builder_content = str_replace('{qr_code}', $qr_code, $certificate_builder_content);
            $certificate_builder_content = str_replace('{course_completion_date}', $course_completion_date, $certificate_builder_content);
            $certificate_builder_content = str_replace('{certificate_id}', $certificate_id, $certificate_builder_content);
            $certificate_builder_content = str_replace('{certificate_download_date}', $certificate_download_date, $certificate_builder_content);
            $certificate_builder_content = str_replace('{course_level}', $course_level, $certificate_builder_content);
            $certificate_builder_content = str_replace('{course_language}', $course_language, $certificate_builder_content);

            // Use regex to update the src attribute of the <img> tag with the class 'certificate-template'.
            $newSrc = get_image(get_settings('certificate_template'));
            $certificate_builder_content = preg_replace('/(<img[^>]*class=["\']certificate-template["\'][^>]*src=["\'])([^"\']*)(["\'])/i', '${1}' . $newSrc . '${3}', $certificate_builder_content);
        @endphp

        {!! $certificate_builder_content !!}
    </div>
    {{-- Downloadable canvas end--}}


    {{-- Preview certificate --}}
    <div class="absolute-view">
        <div class="certificate_builder_view" id="certificate_builder_view">
            {!! $certificate_builder_content !!}
        </div>
    </div>
    {{-- Preview certificate end--}}


    <div class="download-wrapper">
        <a class="download-btn" href="#"
        onclick="setTimeout(() => renderCanvasToImage(), 500); return false;">
            {{ get_phrase('Download Image') }}
        </a>

        <a class="download-btn secondary" href="#"
        onclick="renderCanvasToPDF(); return false;">
            {{ get_phrase('Download PDF') }}
        </a>
    </div>



    <script>
        "use strict";

        $(function() {
            var certificate_builder_view_width = $('.certificate_builder_view').width();
            var certificate_layout_module = $('.certificate_builder_view .certificate-layout-module').width();
            var zoomScaleValue = ((certificate_builder_view_width/certificate_layout_module)*100) - 8;
            $('.certificate_builder_view .certificate-layout-module').css('zoom', zoomScaleValue+'%');
        });
    
        function renderCanvasToImage() {
            
            var certificate_width = $('#captureCertificate > div').width();
            html2canvas(document.querySelector("#captureCertificate > div"), {
                allowTaint: true,
                useCORS: true,
                width: certificate_width,
                scale: 2
            }).then(canvas => {
                document.querySelector("#captureCertificate").appendChild(canvas);
                $("canvas").hide();

                setTimeout(function() {
                    var canvas = document.querySelector("canvas");
                    downloadCanvas(canvas, "certificate.png");
                }, 2000);
            });
        }


        function downloadCanvas(canvas, filename) {
            // Convert canvas to data URL
            var dataUrl = canvas.toDataURL("image/png");

            // Create a temporary link element
            var link = document.createElement("a");
            link.href = dataUrl;
            link.download = filename;

            // Append the link to the body
            document.body.appendChild(link);

            // Create a new MouseEvent and dispatch it
            var event = new MouseEvent('click', {
                view: window,
                bubbles: true,
                cancelable: true
            });
            link.dispatchEvent(event);

            // Remove the link from the body
            document.body.removeChild(link);
        }
        

    $(function() {
        var certificate_builder_view_width = $('.certificate_builder_view').width();
        var certificate_layout_module = $('.certificate_builder_view .certificate-layout-module').width();
        var zoomScaleValue = ((certificate_builder_view_width / certificate_layout_module) * 100) - 8;
        $('.certificate_builder_view .certificate-layout-module').css('zoom', zoomScaleValue + '%');
    });

    function renderCanvasToPDF() {
        const target = document.querySelector("#captureCertificate > div");

        html2canvas(target, {
            allowTaint: true,
            useCORS: true,
            scale: 2
        }).then(canvas => {

            const imgData = canvas.toDataURL("image/png");

            // A4 Landscape
            const pdf = new window.jspdf.jsPDF({
                orientation: 'landscape',
                unit: 'mm',
                format: 'a4'
            });

            const pageWidth = pdf.internal.pageSize.getWidth();
            const pageHeight = pdf.internal.pageSize.getHeight();

            // Hitung rasio agar tidak terpotong
            const imgWidth = pageWidth;
            const imgHeight = canvas.height * imgWidth / canvas.width;

            const positionY = (pageHeight - imgHeight) / 2;

            pdf.addImage(
                imgData,
                'PNG',
                0,
                positionY,
                imgWidth,
                imgHeight,
                undefined,
                'FAST'
            );

            pdf.save("certificate.pdf");
        });
    }

    </script>
</body>

</html>
