<style>
.ListPropertyRowCard {
    margin-bottom: 20px; /* Adjust this value to increase or decrease space between cards */
}
</style>
<div id='ListPropertiesMainContainer'>




</div>

<br><br><br>
<script>


    LoadDataPageFunc = {};
    LoadDataPageFunc.newpropertyrow = function (objrow, rownum) {
        let rows = [];
        let rowcoldetail = '';
        let firstimagesrc = '/assets/no-image.png';
        const imgwidth = '200px'; const imgheight = "200px";
        const hash = objrow.hashkey || false;
        if (!objrow || !hash) { rowcoldetail = 'No Data'; return createCard('Unknown', cardid = 'PropertyRowCard-' + rownum, '', cardbodyid = '', rowcoldetail, cardbodyclassadd = 'ListPropertyRow',true,'ListPropertyRowCard'); }

        let created = objrow.created || false;
        let modified = objrow.modified || false;
        let name = objrow.name || false;
        let description = objrow.description || false;
        let status = objrow.status || false;
        let remarks = objrow.remarks || false;
        let referralid = objrow.referralid || false;
        let createdby = objrow.createdby || false;
        let category = objrow.category || '';
        let subcategory = objrow.subcategory || '';
        let photourl = objrow.photourl || false;
        let sqm = objrow.sqm || false;
        let bedrooms = objrow.bedrooms || false;
        let rooms = objrow.rooms || false;
        let toilet = objrow.toilet || false;

        let kitchen = objrow.kitchen || false;
        let floors = objrow.floors || false;
        let price = objrow.price || false;
        let specs = objrow.specs || false;
        let location = objrow.location || false

        status = InttoStrDetailsFuncs.PropertyStatus(status);
        modified = formatDateTimetoReadable(modified);
        created = formatDateTimetoReadable(created);

        let photobinarystring = '';
        let base64string = '';
        let blob;

        try { photourl = JSON.parse(photourl); } catch (e) { photourl = photourl; }

        if (photourl) { if (Array.isArray(photourl)) { photourl = photourl[0]; } else { } }
        let photohash =photourl;

        if (photourl) { photourl = '/RequestData/File/' + photourl; }


        /*
        photobinarystring = reqcacheload(photourl);
        if (photobinarystring) {
            blob = binaryStringToBlob(photobinarystring);
            console.log('blob ',blob);
            if (blob){
            photourl = CreateObjectURLfrombinaryStringforIMGUse(photobinarystring);
            console.log(photourl);
            }
        }
            */

        let photoelementID='PropertyRowCard-Image-'+ rownum;
        photoblob = reqcacheload(photourl);
        if (photoblob) {
            photourl = URL.createObjectURL(photoblob);
        }else{
            LoadAndCreateURLfromFileHash(photohash).then(bloburl => {
               $('#'+photoelementID).attr('src', bloburl);
            });
        }





        rows.push(`<div class="col-12"><center><a   href="javascript:void(0);return;" onclick="ButtonGo('${'ViewPropertyDetails'}', '${hash}')"><img id="${photoelementID}" src="` + photourl + '" style="width:' + imgwidth + '; height:' + imgheight + ';"></a></center>');
        rows.push('<br>');
        rows.push('<div class="col">');



        if (modified !== false) {
            rows.push(dualcolrow('Last Activity', modified, rowclass = ''));
        }

        if (status !== false) {
            rows.push(dualcolrow('Status', status, rowclass = ''));
        }

        if (location !== false) {
            rows.push(dualcolrow('Location', location, rowclass = ''));
        }

        if (createdby !== false) {
            rows.push(dualcolrow('Filled By', createdby, rowclass = ''));
        }

        if (subcategory !== false) {
            rows.push(dualcolrow(category, subcategory, rowclass = ''));
        }

        if (sqm !== false) {
            rows.push(dualcolrow('Size', sqm + ' sqm', rowclass = ''));
        }

        if (bedrooms !== false) {
            rows.push(dualcolrow('Bedrooms', bedrooms, rowclass = ''));
        }

        if (rooms !== false) {
            rows.push(dualcolrow('Rooms', rooms, rowclass = ''));
        }

        if (toilet !== false) {
            rows.push(dualcolrow('Toilet', toilet, rowclass = ''));
        }

        if (kitchen !== false) {
            rows.push(dualcolrow('Kitchen', kitchen));
        }
        if (floors !== false) {
            rows.push(dualcolrow('Floors', floors));
        }
        if (price !== false) {
            rows.push(dualcolrow('Price', price));
        }




        rows.push('<div id="PropertyListRowCardHash-' + rownum + '" style="display:none;">' + hash + '</div>');


        if (description !== false) {
            rows.push('<br><div class="row">' + col('<center>Description</center>', '-12'));
            rows.push(col('<textarea>' + description + '</textarea>', '-12') + '</div>');
        }

        rows.push('</div></div>');

        rows.push(row(col('<br>' + buttonprimary('View Details', '', `ButtonGo('ViewPropertyDetails', '${hash}')`, '-12', 'ListPropertyGoRow-' + rownum))));
        let FinalBody = rows.join('');

        return createCard(name, cardid = 'PropertyRowCard-' + rownum, created, cardbodyid = '', FinalBody, cardbodyclassadd = 'ListPropertyRow','',false,'ListPropertyRowCard');
    };



    LoadDataPageFunc.main = function () {
        const searchcard = UIInputGroup('Search', 'text', 'ListProperty_Search', '', classs = '', span = '', '/assets/clear.png');
        // let PropertyListContainer = UICardSimple('', 'Loading Please Wait...', 'PropertyListContainer');
        let PropertyListContainer = '<div id="PropertyListContainer"><center>Loading Please Wait...</center></div>';
        const FinalInnerHTML = searchcard + PropertyListContainer;
        const MainCard = UICardSimple('Properties', FinalInnerHTML, 'MAINCARDBODY_PROPERTYLIST');
        $('#ListPropertiesMainContainer').html(MainCard);

    };



    LoadDataPageFunc.CardResultInterSectionPreloadDetails = function () {
        let hashkey = '';
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const cardId = $(entry.target).attr('id');
                    const variablePart = cardId.split('-')[1];
                    const hashKeyDivId = 'PropertyListRowCardHash-' + variablePart;
                    hashkey = $('#' + hashKeyDivId).text();
                    if (hashkey) {
                        request.url('/ViewProperty/Details/data').success((response) => {
                        }).data({ target: hashkey }).fromVarCache(true).type('POST').go();
                    }
                    hashkey = '';
                }
            });
        }, { threshold: 0.1 });


        $('#PropertyListContainer .card').each(function () {
            observer.observe(this);
        });
    };

    LoadDataPageFunc.populatepropertylist = function () {
        let request = new RequestData(true);
        request
            .url('/ListProperty/List/data')
            .type('POST')
            .data(null)
            .fromVarCache(true)
            .success((response) => {
                if ($('#card-body-MAINCARDBODY_PROPERTYLIST').length === 0) { return false; }
                if (!response) {
                    $('#card-body-MAINCARDBODY_PROPERTYLIST').html('No Properties');
                    return;
                }

                const PropertyList = response.List;
                //PropertyList.reverse();
                PropertyList.sort((a, b) => new Date(b.created) - new Date(a.created));
                let newhtmlrows = ''; let arrayrows = [];
                const count = PropertyList.length;


                for (let i = 0; i < count; i++) {
                    arrayrows.push(LoadDataPageFunc.newpropertyrow(PropertyList[i], i));
                }

                newhtmlrows = arrayrows.join('');
                $('#PropertyListContainer').html(newhtmlrows);
                LoadDataPageFunc.CardResultInterSectionPreloadDetails();
            })
            .error((err) => {
                console.error(err);
            })
            .go();

    };

    function SearchKeyUPListPropertyPage() {
        $('#ListProperty_Search').on('keyup', function () {

            let searchTerm = $(this).val().toLowerCase();

            $('#PropertyListContainer .card').each(function () {

                let title = $(this).find('.card-title').text().toLowerCase();
                let cols = $(this).find('.col').text().toLowerCase();

                if (title.includes(searchTerm) || cols.includes(searchTerm)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        });
    }

    LoadDataPageFunc.ClearSearch = function () {
        $('#ListProperty_Search').val('');
        $('#ListProperty_Search').trigger('keyup');
    };

    $(document).ready(function () {
        LoadDataPageFunc.main();
        LoadDataPageFunc.populatepropertylist();
        changeTopbarTitle('Properties');
        SearchKeyUPListPropertyPage();
        $('#imgspanListProperty_Search').attr('onclick', 'LoadDataPageFunc.ClearSearch();');

    });
</script>