<?php $__env->startSection('content'); ?>
    <div class="container-fluid py-4">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-4 editor-sidebar">
                <h4>1. Pilih Template</h4>

                <div id="templateSkeletonWrapper" class="d-flex flex-wrap gap-2">
                    
                    <div class="skeleton-box template-skeleton"></div>
                    <div class="skeleton-box template-skeleton"></div>
                    <div class="skeleton-box template-skeleton"></div>
                </div>

                <div id="templateButtonWrapper" class="d-flex flex-wrap gap-2 d-none">
                    <?php $__currentLoopData = $templates; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $template): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <button class="btn btn-light p-1"
                            onclick="selectTemplate(
                '<?php echo e(asset($template['image_preview_url'])); ?>',
                '<?php echo e(asset($template['image_full_url'])); ?>',
                '<?php echo e($template['id']); ?>',
                '<?php echo e($template['product']['price'] ?? 0); ?>',
                '<?php echo e($template['product']['weight'] ?? 0); ?>'
            )">
                            <img src="<?php echo e(asset($template['image_preview_url'])); ?>" alt="Template" class="img-thumbnail"
                                style="width: 100px; height: 100px; object-fit: cover;">
                        </button>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>




                <h4 class="mt-4">2. Masukkan Teks</h4>

                <!-- Heading -->
                <div class="mb-3">
                    <label for="headingText" class="form-label">Teks Heading</label>
                    <input type="text" class="form-control" id="headingText" placeholder="Masukkan teks heading"
                        oninput="updateHeadingStyle()">
                </div>
                <div class="row align-items-end mb-4">
                    <div class="col-8">
                        <label for="headingSize" class="form-label">Ukuran Heading</label>
                        <input type="range" class="form-range" id="headingSize" min="10" max="72"
                            value="30" oninput="updateHeadingStyle()">
                        <small id="headingSizeValue">30 px</small>
                    </div>
                    <div class="col-4">
                        <label for="headingColor" class="form-label">Warna Heading</label>
                        <input type="color" class="form-control form-control-color" id="headingColor" value="#ffffff"
                            onchange="updateHeadingStyle()">
                    </div>
                </div>

                <!-- Subtitle -->
                <div class="mb-3">
                    <label for="subtitleText" class="form-label">Teks Subjudul</label>
                    <input type="text" class="form-control" id="subtitleText" placeholder="Masukkan teks subjudul"
                        oninput="updateSubtitleStyle()">
                </div>
                <div class="row align-items-end mb-4">
                    <div class="col-8">
                        <label for="subtitleSize" class="form-label">Ukuran Subjudul</label>
                        <input type="range" class="form-range" id="subtitleSize" min="10" max="72"
                            value="22" oninput="updateSubtitleStyle()">
                        <small id="subtitleSizeValue">22 px</small>
                    </div>
                    <div class="col-4">
                        <label for="subtitleColor" class="form-label">Warna Subjudul</label>
                        <input type="color" class="form-control form-control-color" id="subtitleColor" value="#ffffff"
                            onchange="updateSubtitleStyle()">
                    </div>
                </div>

                <!-- Checkout Button -->
                <button class="btn btn-primary w-100" data-bs-toggle="modal" data-bs-target="#checkoutModal">Lanjut ke
                    Checkout</button>
                <button class="btn btn-secondary mt-3 d-none" onclick="downloadImage()">Download Gambar</button>

            </div>

            <!-- Preview Area -->

            <div class="col-md-8">
                <h5 class="fw-bold">Preview Template</h5>
                <!-- Skeleton untuk preview area -->
                <div id="previewSkeletonWrapper"
                    style="aspect-ratio: 16 / 10; width: 100%; max-width: 800px; border-radius: 10px; overflow: hidden; background-size: cover; background-position: center;">
                    <div class="skeleton-box preview-skeleton mb-3"></div>
                    <div class="skeleton-box skeleton-text"></div>
                    <div class="skeleton-box skeleton-text" style="width: 30%;"></div>
                </div>

                <div id="previewArea"
                    class="bg-light d-flex justify-content-center align-items-center position-relative d-none"
                    style="aspect-ratio: 16 / 10; width: 100%; max-width: 800px; border-radius: 10px; overflow: hidden; background-size: cover; background-position: center;">
                    <h2 id="previewHeading" class="position-absolute text-center fw-bold"
                        style="top: 50%; left: 43%; transform: translate(-50%, -50%); font-size: 30px; color: rgb(255, 255, 255); text-shadow: 1px 1px 2px black;">

                    </h2>
                    <p id="previewSubtitle" class="position-absolute text-center"
                        style="top: 58%; left: 43%; transform: translate(-50%, -50%); font-size: 22px; color: rgb(255, 255, 255); text-shadow: 1px 1px 2px black;">

                    </p>
                </div>

                <!-- Hidden Capture Area -->
                <div id="finalCaptureArea"
                    style="position: fixed; top: -10000px; left: -10000px; width: 800px; height: 500px;">
                    <div id="canvasTemplateWrapper" class="position-relative w-100 h-100"
                        style="background-size: cover; background-position: center;">
                        <h2 id="captureHeading" class="position-absolute text-center fw-bold"
                            style="top: 50%; left: 43%; transform: translate(-50%, -50%); font-size: 30px; color: rgb(255, 255, 255); text-shadow: 1px 1px 2px black;">

                        </h2>
                        <p id="captureSubtitle" class="position-absolute text-center"
                            style="top: 58%; left: 43%; transform: translate(-50%, -50%); font-size: 22px; color: rgb(255, 255, 255); text-shadow: 1px 1px 2px black;">

                        </p>

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

    <?php echo $__env->make('partials.checkout-modal', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>

<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
    <script>
        window.addEventListener("load", function() {
            // Delay sedikit biar keliatan smooth (opsional)
            setTimeout(() => {
                document.getElementById("templateSkeletonWrapper").classList.add('d-none');
                document.getElementById("templateButtonWrapper").classList.remove('d-none');
            }, 500); // 500ms biar user lihat efek loading
        });
    </script>

    <script>
        // ──────────────── GLOBAL STATE ────────────────
        let selectedTemplateId = null;
        let selectedPrice = 0;
        let selectedWeight = 0;


        document.addEventListener("DOMContentLoaded", () => {
            document.getElementById("previewArea").style.display = "none";
            document.getElementById('headingText').addEventListener('input', checkCheckoutAvailability);
            document.getElementById('subtitleText').addEventListener('input', checkCheckoutAvailability);

            checkCheckoutAvailability(); // inisialisasi saat halaman load
        });



        // ──────────────── TEMPLATE SELECTION ────────────────
        function selectTemplate(previewUrl, fullUrl, templateId, price = 0, weight = 0) {
            selectedTemplateId = templateId;
            selectedPrice = parseInt(price);
            selectedWeight = parseInt(weight);

            console.log("🎯 Selected Template:", templateId, "Price:", selectedPrice, "Weight:", selectedWeight);

            const previewEl = document.getElementById("previewArea");
            const skeletonEl = document.getElementById("previewSkeletonWrapper");

            // Step 1: Tampilkan skeleton, sembunyikan preview
            skeletonEl.classList.remove("d-none");
            previewEl.classList.add("d-none");
            previewEl.classList.remove("fade-in", "fade-out");

            // Pasang dulu gambar preview ringan
            previewEl.style.backgroundImage = `url('${previewUrl}')`;

            const img = new Image();
            img.crossOrigin = "anonymous";
            img.src = fullUrl;

            img.onload = () => {
                const tempCanvas = document.createElement('canvas');
                tempCanvas.width = img.width;
                tempCanvas.height = img.height;
                const ctx = tempCanvas.getContext('2d');
                ctx.drawImage(img, 0, 0);
                const base64 = tempCanvas.toDataURL("image/png");

                // Pasang gambar asli ke capture area
                document.getElementById("canvasTemplateWrapper").style.backgroundImage = `url('${base64}')`;

                // Update teks
                updateHeadingStyle();
                updateSubtitleStyle();

                // Step 2: Setelah image selesai diload → hide skeleton + tampilkan preview
                setTimeout(() => {
                    skeletonEl.classList.add("d-none");
                    previewEl.classList.remove("d-none");
                    previewEl.classList.add("fade-in");
                }, 300); // 300ms biar ada efek smooth
            };

            updateSubtotal();
        }

        function checkCheckoutAvailability() {
            const heading = document.getElementById('headingText').value.trim();
            const subtitle = document.getElementById('subtitleText').value.trim();
            const button = document.querySelector('[data-bs-target="#checkoutModal"]');

            if (heading || subtitle) {
                button.removeAttribute('disabled');
            } else {
                button.setAttribute('disabled', 'disabled');
            }
        }


        function updateSubtotal() {
            const qty = parseInt(document.getElementById("qty").value) || 1;
            const subtotal = selectedPrice * qty;
            document.getElementById("subtotal").innerText = formatRupiah(subtotal);

            const ongkirText = document.getElementById("ongkir").innerText.replace(/[^\d]/g, '') || "0";
            const ongkir = parseInt(ongkirText);
            const total = subtotal + ongkir;

            document.getElementById("total").innerText = formatRupiah(total);
        }

        function formatRupiah(angka) {
            return new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: 'IDR',
                minimumFractionDigits: 0
            }).format(angka);
        }

        function updateHeadingStyle() {
            const inputText = document.getElementById('headingText').value.trim();
            const size = document.getElementById('headingSize').value + 'px';
            const color = document.getElementById('headingColor').value;

            document.getElementById('headingSizeValue').innerText = size;

            // 🔹 PREVIEW area → tampilkan dummy kalau kosong
            const previewEl = document.getElementById('previewHeading');
            previewEl.innerText = inputText || 'Teks Anda';
            previewEl.style.fontSize = size;
            previewEl.style.color = color;

            // 🔸 FINAL CAPTURE area → hanya tampilkan jika tidak kosong
            const captureEl = document.getElementById('captureHeading');
            if (inputText) {
                captureEl.innerText = inputText;
                captureEl.style.fontSize = size;
                captureEl.style.color = color;
            } else {
                captureEl.innerText = ''; // kosongkan
            }
        }


        function updateSubtitleStyle() {
            const inputText = document.getElementById('subtitleText').value.trim();
            const size = document.getElementById('subtitleSize').value + 'px';
            const color = document.getElementById('subtitleColor').value;

            document.getElementById('subtitleSizeValue').innerText = size;

            // 🔹 PREVIEW area → tampilkan dummy kalau kosong
            const previewEl = document.getElementById('previewSubtitle');
            previewEl.innerText = inputText || 'Subjudul Anda';
            previewEl.style.fontSize = size;
            previewEl.style.color = color;

            // 🔸 FINAL CAPTURE area → hanya tampilkan jika tidak kosong
            const captureEl = document.getElementById('captureSubtitle');
            if (inputText) {
                captureEl.innerText = inputText;
                captureEl.style.fontSize = size;
                captureEl.style.color = color;
            } else {
                captureEl.innerText = ''; // kosongkan
            }
        }


        // ──────────────── IMAGE DOWNLOAD HANDLER ────────────────
        async function downloadImage() {
            const el = document.getElementById("finalCaptureArea");

            // Pastikan semua font custom sudah siap
            await document.fonts.ready;

            // Optional delay untuk memastikan layout stabil
            setTimeout(() => {
                html2canvas(el, {
                    useCORS: true,
                    allowTaint: true,
                    scale: 2,
                    backgroundColor: null,
                    // HAPUS foreignObjectRendering: true karena bikin blank
                }).then(canvas => {
                    const link = document.createElement("a");
                    link.download = "preview.png";
                    link.href = canvas.toDataURL("image/png");
                    link.click();
                });
            }, 200); // delay kecil
        }


        function formatRupiah(angka) {
            return new Intl.NumberFormat('id-ID', {
                style: 'currency',
                currency: 'IDR',
                minimumFractionDigits: 0
            }).format(angka);
        }

        function captureAndCheckout() {
            const el = document.getElementById("finalCaptureArea");
            document.getElementById("loadingOverlay").style.display = "flex";

            html2canvas(el, {
                useCORS: true,
                scale: 2
            }).then(canvas => {
                const imageData = canvas.toDataURL("image/png");

                const qty = parseInt(document.getElementById("qty").value) || 1;
                const totalWeight = selectedWeight * qty;
                const subTotal = selectedPrice * qty;
                const courierPrice = parseInt($('input[name="service"]:checked').data('price')) || 0;
                const total = subTotal + courierPrice;
                const courierInput = $('input[name="service"]:checked');

                const formData = new FormData();
                formData.append("nama", document.getElementById("nama").value);
                formData.append("phone", document.getElementById("phone").value);
                formData.append("alamat", document.getElementById("address").value);
                formData.append("propinsi", $('#dlvr-province option:selected').text().trim());
                formData.append("kota", $('#dlvr-city option:selected').text().trim());
                formData.append("kecamatan", $('#dlvr-district option:selected').text().trim());

                formData.append("kurir", courierInput.data('code') || '');
                formData.append("jenispengiriman", courierInput.val());
                formData.append("ongkir", courierInput.data('price') || 0);

                formData.append("template_id", selectedTemplateId);
                formData.append("heading", document.getElementById("headingText").value);
                // formData.append("headingSize", document.getElementById("headingSize").value);
                // formData.append("headingColor", document.getElementById("headingColor").value);

                formData.append("subtitle", document.getElementById("subtitleText").value);
                // formData.append("subtitleSize", document.getElementById("subtitleSize").value);
                // formData.append("subtitleColor", document.getElementById("subtitleColor").value);

                formData.append("sub_total", subTotal);
                formData.append("total", total);
                formData.append("qty", qty);
                formData.append("weight", totalWeight);

                formData.append("image_data", imageData);

                const API_URL = "<?php echo e(env('API_URL')); ?>";

                fetch(`${API_URL}/order/store`, {
                        method: "POST",
                        body: formData
                    })
                    .then(res => res.json())
                    .then(data => {
                        document.getElementById("loadingOverlay").style.display = "none";
                        // alert("✅ Berhasil! ID Order: " + data.id);
                        window.location.href = "/checkout/" + data.id; 

                    })
                    .catch(err => {
                        document.getElementById("loadingOverlay").style.display = "none";
                        console.error("❌ Upload gagal", err);
                        // alert("Gagal kirim data.");
                    });
            });
        }


        $(document).ready(function() {
            // ───── PROVINSI -> KOTA ─────
            $('#dlvr-province').on('change', function() {
                const provinceId = $(this).val();
                const provName = $(this).find('option:selected').data('prov');
                console.log("📦 Provinsi dipilih:", provinceId, provName);

                $('#city').val(''); // reset hidden field
                $('#district').val('');
                $('#dlvr-district').empty().append('<option value="">-- Pilih Kecamatan --</option>');
                $('#dlvr-city').empty().append('<option value="">-- Memuat Kota... --</option>');


                // 🔁 RESET SEMUA
                $('#city').val('');
                $('#district').val('');
                $('#jeniskirim').val('');

                $('#dlvr-city').empty().append('<option value="">-- Pilih Kota --</option>');
                $('#dlvr-district').empty().append('<option value="">-- Pilih Kecamatan --</option>');

                $('#dlvr-courier').addClass('d-none');
                $('#dlvr-courier').find('[data-kt-buttons="true"]').empty();

                // $('#subtotal').text('Rp 0');
                $('#ongkir').text('Rp 0');
                $('#total').text('Rp 0');
                $('#submit-button').prop('disabled', true);

                $('.btn-courier').prop('checked', false);

                $.ajax({
                    url: '<?php echo e(route('get.cities')); ?>',
                    method: 'GET',
                    data: {
                        province_id: provinceId
                    },
                    success: function(data) {
                        console.log("📥 Data kota:", data);
                        $('#dlvr-city').empty().append(
                            '<option value="">-- Pilih Kota --</option>');
                        $.each(data, function(key, city) {
                            $('#dlvr-city').append(
                                `<option value="${city.id}" data-city="${city.name}">${city.name}</option>`
                            );
                        });
                    },
                    error: function(xhr) {
                        console.error("❌ Gagal ambil kota:", xhr.responseText);
                        alert("Gagal mengambil kota.");
                    }
                });
            });

            // ───── KOTA -> KECAMATAN ─────
            $('#dlvr-city').on('change', function() {
                const cityId = $(this).val();
                const cityName = $(this).find('option:selected').data('city');
                console.log("🏙️ Kota dipilih:", cityId, cityName);

                $('#city').val(cityName);
                $('#district').val('');
                $('#dlvr-district').empty().append('<option value="">-- Memuat Kecamatan... --</option>');

                $.ajax({
                    url: '<?php echo e(route('get.district')); ?>',
                    method: 'GET',
                    data: {
                        city_id: cityId
                    },
                    success: function(data) {
                        console.log("📥 Data kecamatan:", data);
                        $('#dlvr-district').empty().append(
                            '<option value="">-- Pilih Kecamatan --</option>');
                        $.each(data, function(key, district) {
                            $('#dlvr-district').append(
                                `<option value="${district.id}" data-district="${district.name}">${district.name}</option>`
                            );
                        });
                    },
                    error: function(xhr) {
                        console.error("❌ Gagal ambil kecamatan:", xhr.responseText);
                        alert("Gagal mengambil kecamatan.");
                    }
                });

            });

            // ───── KECAMATAN SELECTED ─────
            $('#dlvr-district').on('change', function() {
                const districtId = $(this).val();
                const districtName = $(this).find('option:selected').data('district');
                const qty = parseInt($('#qty').val()) || 1;
                const weight = qty * selectedWeight;

                console.log("🏘️ Kecamatan dipilih:", districtId, districtName, "| Berat total:", weight);
                $('#district').val(districtName);

                $.ajax({
                    url: '<?php echo e(route('get.courier')); ?>',
                    method: 'GET',
                    data: {
                        district_id: districtId,
                        weight: weight
                    },
                    success: function(data) {
                        const courierContainer = $('#dlvr-courier').find(
                            '[data-kt-buttons="true"]');
                        courierContainer.empty();

                        let count = 0;
                        $.each(data.data, function(index, cost) {
                            if (!cost.service || !cost.cost) return;

                            const optionHtml = `
<div class="col-md-4">
    <input type="radio" class="btn-check btn-courier" name="service"
        id="courier-${index}" data-price="${cost.cost}" data-code="${cost.code}" value="${cost.service}" autocomplete="off" />
    <label class="btn btn-outline btn-outline-dashed btn-outline-default w-100 p-4 mb-3" for="courier-${index}">
        <span class="fw-bolder fs-4">${cost.service}</span>
        <div class="text-muted small">${cost.description}</div>
        <div>Harga: ${formatRupiah(cost.cost)}</div>
        <div class="small">Estimasi: ${cost.etd}</div>
    </label>
</div>`;

                            courierContainer.append(optionHtml);
                            count++;
                        });

                        if (count > 0) {
                            $('#dlvr-courier').removeClass('d-none');
                        } else {
                            courierContainer.append(
                                '<div class="col-12 text-center text-muted">Tidak ada layanan kurir tersedia.</div>'
                            );
                            $('#dlvr-courier').removeClass('d-none');
                        }
                    },
                    error: function(xhr) {
                        console.error("❌ Gagal ambil kurir:", xhr.responseText);
                        alert("Gagal mengambil kurir.");
                    }
                });
            });

            // ───── HANDLE PEMILIHAN KURIR ─────
            $(document).on('change', '.btn-courier', function() {
                if ($(this).is(':checked')) {
                    const price = parseInt($(this).data('price')) || 0;
                    const qty = parseInt($('#qty').val()) || 1;
                    const subtotal = selectedPrice * qty;
                    const total = subtotal + price;

                    $('#ongkir').text(formatRupiah(price));
                    $('#subtotal').text(formatRupiah(subtotal));
                    $('#total').text(formatRupiah(total));

                    // Aktifkan tombol checkout
                    $('#submit-button').prop('disabled', false);
                }
            });

            $('#qty').on('change input', function() {
                const districtId = $('#dlvr-district').val();

                // Reset ongkir & button
                $('#ongkir').text('Rp 0');
                $('#total').text(formatRupiah(selectedPrice * ($('#qty').val() || 1)));
                $('#submit-button').prop('disabled', true);

                // Uncheck semua kurir
                $('.btn-courier').prop('checked', false);

                // Re-fetch kurir
                if (districtId) {
                    $('#dlvr-district').trigger('change');
                }
            });



        });
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/plossayokesen/public_html/resources/views/exerience-plossa.blade.php ENDPATH**/ ?>