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

<head>
    <meta charset="UTF-8">
    <title>Silsilah Keluarga</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script src="<?= base_url('assets/js/familytree.js') ?>"></script>
</head>
<style>
    /*CSS*/
    html,
    body {
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
        overflow: hidden;
        font-family: Helvetica;
    }

    #tree {
        width: 100%;
        height: 100%;
    }
</style>

<body>
    <div class="row">
        <div id="tree"></div>
    </div>

    <!-- Debugging output -->
    <script>
        $(document).on('click', 'button[data-edit-from-save]', function(e) {
            e.preventDefault();
            const formData = {};

            // Cari form terdekat yang memuat input
            const $form = $(this).closest('form[data-bft-edit-form]');

            $form.find('[data-binding]').each(function() {
                const fieldName = $(this).data('binding');
                const fieldValue = $(this).val();
                formData[fieldName] = fieldValue;
            });


            $.ajax({
                url: '<?= base_url('Family/save_member_data') ?>', // Pastikan path controller benar
                type: 'POST',
                data: formData,
                success: function(response) {
                    var data = JSON.parse(response);
                    if (data.status === 'success') {
                        alert('Data berhasil disimpan!');
                    } else {
                        alert('Error saving data: ' + data.message);
                    }
                },
                error: function() {
                    alert('Terjadi kesalahan saat mengirim data.');
                }
            });
        });


        FamilyTree.templates.tommy_female.defs =
            `<g transform="matrix(0.05,0,0,0.05,-12,-9)" id="heart">
        <path fill="#F57C00" d="M438.482,58.61c-24.7-26.549-59.311-41.655-95.573-41.711c-36.291,0.042-70.938,15.14-95.676,41.694l-8.431,8.909  l-8.431-8.909C181.284,5.762,98.663,2.728,45.832,51.815c-2.341,2.176-4.602,4.436-6.778,6.778 c-52.072,56.166-52.072,142.968,0,199.134l187.358,197.581c6.482,6.843,17.284,7.136,24.127,0.654 c0.224-0.212,0.442-0.43,0.654-0.654l187.29-197.581C490.551,201.567,490.551,114.77,438.482,58.61z"/>
    <g>`;
        FamilyTree.templates.tommy_male.defs =
            `<g transform="matrix(0.05,0,0,0.05,-12,-9)" id="heart">
        <path fill="#F57C00" d="M438.482,58.61c-24.7-26.549-59.311-41.655-95.573-41.711c-36.291,0.042-70.938,15.14-95.676,41.694l-8.431,8.909  l-8.431-8.909C181.284,5.762,98.663,2.728,45.832,51.815c-2.341,2.176-4.602,4.436-6.778,6.778 c-52.072,56.166-52.072,142.968,0,199.134l187.358,197.581c6.482,6.843,17.284,7.136,24.127,0.654 c0.224-0.212,0.442-0.43,0.654-0.654l187.29-197.581C490.551,201.567,490.551,114.77,438.482,58.61z"/>
    <g>`;



        FamilyTree.templates.tommy.field_1 = '<text data-width="230" data-text-overflow="multiline-4-ellipsis" style="font-size: 20px;" fill="#fff" x="10" y="28" text-anchor="start">{val}</text>';

        FamilyTree.elements.myTextArea = function(data, editElement, minWidth, readOnly) {
            var id = FamilyTree.elements.generateId();
            var value = data[editElement.binding] || ''; // Jika undefined, set jadi string kosong
            var rOnlyAttr = readOnly ? 'readonly' : '';
            var rDisabledAttr = readOnly ? 'disabled' : '';

            return {
                html: `<div style="display: flex; flex-direction: column; margin-bottom: 10px;">
                   <label for="${id}" style="font-weight: bold; margin-bottom: 5px;">${editElement.label}</label>
                   <textarea ${rDisabledAttr} ${rOnlyAttr} id="${id}" name="${id}" 
                             style="width: 100%; height: 100px; padding: 8px; border-radius: 5px; border: 1px solid #ccc; font-size: 14px;"
                             data-binding="${editElement.binding}">${value}</textarea>
               </div>`,
                id: id,
                value: value
            };
        };

        FamilyTree.elements.myLink = function(data, editElement, minWidth, readOnly) {
            var id = FamilyTree.elements.generateId();
            var value = data[editElement.binding] || ''; // Jika undefined, set jadi string kosong
            var rOnlyAttr = readOnly ? 'readonly' : '';
            var rDisabledAttr = readOnly ? 'disabled' : '';

            // Cek apakah value adalah URL
            var isURL = /^https?:\/\/[^\s]+$/.test(value);

            // Jika readOnly dan isinya URL, tampilkan sebagai link
            if (readOnly && isURL) {
                return {
                    html: `<div style="display: flex; flex-direction: column; margin-bottom: 10px;">
                       <label style="font-weight: bold; margin-bottom: 5px;">${editElement.label}</label>
                       <a href="${value}" target="_blank" style="color: blue; text-decoration: underline;">${value}</a>
                   </div>`,
                    id: id,
                    value: value
                };
            }

            // Jika bukan URL atau bisa diedit, tampilkan sebagai textarea
            return {
                html: `<div style="display: flex; flex-direction: column; margin-bottom: 10px;">
                   <label for="${id}" style="font-weight: bold; margin-bottom: 5px;">${editElement.label}</label>
                   <textarea ${rDisabledAttr} ${rOnlyAttr} id="${id}" name="${id}" 
                             style="width: 100%; height: 100px; padding: 8px; border-radius: 5px; border: 1px solid #ccc; font-size: 14px;"
                             data-binding="${editElement.binding}">${value}</textarea>
               </div>`,
                id: id,
                value: value
            };
        };



        var family = new FamilyTree(document.getElementById('tree'), {
            mouseScrool: FamilyTree.none,
            mode: 'dark',
            template: 'hugo',
            nodeMenu: {
                edit: {
                    text: 'Edit'
                },
                details: {
                    text: 'Details'
                },
            },
            nodeBinding: {
                field_0: 'name',
                field_1: 'country',
                img_0: 'photo'
            },
            editForm: {
                titleBinding: "name",
                photoBinding: "photo",
                generateElementsFromFields: false,
                addMoreBtn: 'Add element',
                elements: [{
                        type: 'textbox',
                        label: 'ID',
                        binding: 'id',
                        readOnly: true
                    },
                    {
                        type: 'textbox',
                        label: 'Nama Lengkap',
                        binding: 'name'
                    },
                    {
                        type: 'textbox',
                        label: 'Pekerjaan',
                        binding: 'email'
                    },
                    [{
                            type: 'textbox',
                            label: 'Phone',
                            binding: 'phone'
                        },
                        {
                            type: 'date',
                            label: 'Tanggal Lahir',
                            binding: 'born'
                        }
                    ],
                    {
                        type: 'myLink',
                        label: 'Alamat / Gmap',
                        binding: 'city'

                    },
                    {
                        type: 'myTextArea',
                        label: 'Deskripsi / Biografi',
                        binding: 'country'

                    },
                    {
                        type: 'textbox',
                        label: 'Photo Url',
                        binding: 'ImgUrl',
                        btn: 'Upload'
                    }

                ]
            },
        });

        family.editUI.on('button-click', function(sender, args) {
            if (args.name == 'city') {
                var data = family.get(args.nodeId);
                window.open(data.city);
            }
        });

        family.on('field', function(sender, args) {
            if (args.name == 'born' && args.value) {
                var date = new Date(args.value);
                if (!isNaN(date.getTime())) { // Cek jika tanggal valid
                    // Format ke "DD Month YYYY" (contoh: "15 January 1990")
                    args.value = date.toLocaleDateString('en-US', {
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric'
                    });
                }
            }
        });

        family.on('field', function(sender, args) {
            if (args.name == 'city' && args.value) {
                args.value = '<a target="_blank" href="' + args.value + '"> Link Google Maps </a>';
            }
        });


        family.on('expcollclick', function(sender, isCollapsing, nodeId) {
            var node = family.getNode(nodeId);
            if (isCollapsing) {
                family.expandCollapse(nodeId, [], node.ftChildrenIds)
            } else {
                family.expandCollapse(nodeId, node.ftChildrenIds, [])
            }
            return false;
        });

        family.on('render-link', function(sender, args) {
            if (args.cnode.ppid !== undefined)
                args.html += '<use data-ctrl-ec-id="' + args.node.id + '" xlink:href="#heart" x="' + (args.p.xa || 0) + '" y="' + (args.p.ya || 0) + '"/>';

            if (args.cnode.isPartner && args.node.partnerSeparation == 30)
                args.html += '<use data-ctrl-ec-id="' + args.node.id + '" xlink:href="#heart" x="' + (args.p.xb || 0) + '" y="' + (args.p.yb || 0) + '"/>';
        });




        family.editUI.on('element-btn-click', function(sender, args) {
            // Now try selecting the input based on the data-binding attribute directly
            var memberId = $('.bft-edit-form-fields').find('[data-binding="id"]').val();

            FamilyTree.fileUploadDialog(function(file) {
                var formData = new FormData();
                formData.append('photo', file);
                formData.append('id', memberId); // Kirim ID anggota keluarga dalam FormData

                $.ajax({
                    url: '<?= base_url('Family/upload_photo') ?>', // Pastikan path controller benar
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function(response) {
                        var data = JSON.parse(response);
                        if (data.status === 'success') {
                            alert('File uploaded successfully!');

                            // Update foto anggota keluarga di UI
                            updateFamilyMemberPhoto(memberId, data.photo_url);
                        } else {
                            alert('Error uploading file: ' + data.message);
                        }
                    }
                });
            });
        });


        // Fungsi untuk memperbarui foto anggota keluarga di UI
        function updateFamilyMemberPhoto(id, photoUrl) {
            // Cari anggota keluarga berdasarkan ID dan update foto di UI
            var memberElement = $('#member-' + id); // Misalnya elemen anggota keluarga punya ID member-ID
            memberElement.find('.photo').attr('src', photoUrl); // Update foto dengan URL baru
        }


        family.load([
            <?php foreach ($family_members as $index => $member) { ?> {
                    "id": <?php echo $member['id']; ?>,
                    <?php if (!is_null($member['mid'])) { ?> "mid": <?php echo $member['mid']; ?>,
                    <?php } ?>
                    <?php if (!is_null($member['fid'])) { ?> "fid": <?php echo $member['fid']; ?>,
                    <?php } ?>
                    <?php if (!is_null($member['pids'])) { ?> "pids": [<?php echo $member['pids']; ?>],
                    <?php } ?> "gender": '<?php echo $member['gender']; ?>',
                    "photo": "<?php echo $member['photo']; ?>",
                    "name": "<?php echo $member['name']; ?>",
                    "born": "<?php echo !empty($member['born']) ? $member['born'] : ''; ?>",
                    "phone": "<?php echo !empty($member['phone']) ? $member['phone'] : ''; ?>",
                    "email": "<?php echo !empty($member['email']) ? $member['email'] : ''; ?>",
                    "city": "<?php echo !empty($member['city']) ? htmlspecialchars($member['city'], ENT_QUOTES, 'UTF-8') : ''; ?>",
                    "country": "<?php echo !empty($member['country']) ? $member['country'] : ''; ?>",


                }
                <?php if ($index < count($family_members) - 1) {
                    echo ',';
                } ?>
            <?php } ?>
        ]);
    </script>
</body>

</html>