var hostingPackageTemplate =
    `<div class="d-flex align-items-center mb-1 row hosting-package-details" id="hosting-package-details-%ID%">
        <div class="col-md-6">
            <input type="text" class="mr-3 hosting-package-name" id="hosting-package-name-%ID%">
        </div>
        <div class="col-md-3">
            <label>Starting from</label>
        </div>
        <div class="col-md-3">
            <input type="text" class="small-fld hosting-package-starting" id="hosting-package-starting-%ID%">
        </div>
    </div>`;



var hostingLocationTemplate = `
<div class="d-flex align-items-center mb-1 hosting-package-location" id="hosting-location-%ID%">
    <input type="text" placeholder="Location Name" class="hosting-package-location-name" id="hosting-location-name-%ID%">
 </div>`;


$(document).ready(function () {
    var hostingDataWrapper = document.getElementById('hosting-data-wrapper');
    var hostingPackagesWrapper = document.getElementById('hosting-packages-wrapper');
    var hostingLocationsWrapper = document.getElementById('hosting-locations-wrapper');
    var hiddenDataField = document.getElementById('vq_hosting_companies_details');
    var hostingCompaniesBody = document.getElementById('hosting-companies-body');

    var hostingNameEl = document.getElementById('hosting-company-name');
    var hostingSlugEl = document.getElementById('hosting-company-slug');
    var hostingInEdit = -1;


    resetChanges = function () {
        hostingInEdit = -1;
        hostingNameEl.value = '';
        hostingSlugEl.value = '';
        hostingPackagesWrapper.innerHTML = '';
        hostingLocationsWrapper.innerHTML = '';
    };

    addHostingPackages = function () {
        const existingPackages = document.getElementsByClassName('hosting-package-details').length;
        hostingPackagesWrapper.insertAdjacentHTML('beforeend', hostingPackageTemplate.replace(/%ID%/g, existingPackages.toString()));
    };


    addHostingLocation = function () {
        const existingPackages = document.getElementsByClassName('hosting-package-location').length;
        hostingLocationsWrapper.insertAdjacentHTML('beforeend', hostingLocationTemplate.replace(/%ID%/g, existingPackages.toString()));
    };


    saveHostingCompany = function () {
        var hostingInfo = {};
        hostingInfo.name = hostingNameEl.value;
        hostingInfo.slug = hostingSlugEl.value;

        if (!hostingInfo.name || !hostingInfo.slug) {
            return alert('Title & Organization is required.');
        }

        const packages = hostingPackagesWrapper.getElementsByClassName('hosting-package-details');
        hostingInfo.packages = [];
        for (var i = 0; i < packages.length; i++) {
            const name = document.getElementById(`hosting-package-name-${i}`).value;
            const price = document.getElementById(`hosting-package-starting-${i}`).value;
            hostingInfo.packages.push({title: name, price: price});
        }

        const locations = hostingLocationsWrapper.getElementsByClassName('hosting-package-location');
        hostingInfo.locations = [];
        for (var i = 0; i < locations.length; i++) {
            const name = locations[i].getElementsByClassName('hosting-package-location-name')[0].value;
            hostingInfo.locations.push(name);
        }

        if (hostingInEdit > -1) {
            hostingCompaniesDetails[hostingInEdit] = hostingInfo;
        } else {
            hostingCompaniesDetails.push(hostingInfo);
        }

        populateTable();
    };


    populateTable = function() {
        hostingCompaniesBody.innerHTML = '';

        hostingCompaniesDetails.forEach(function(company, index) {
            var packagesStr = '';
            var locationsStr = '';
            if (company.packages) {
                company.packages.forEach(function (package) {
                    packagesStr += `<p>${package.title} Starting from $${package.price}</p>`;
                })
            }
            if (company.locations) {
                locationsStr = company.locations.join(', ');
            }
            var row = `<tr>`;
            row += `<td>${company.name}</td>`;
            row += `<td>${company.slug}</td>`;
            row += `<td>${packagesStr}</td>`;
            row += `<td>${locationsStr}</td>`;
            row += `<td><a onclick="editCompany(${index})">Edit</a> <a class="ml-2 button-link-delete" onclick="removeCompany(${index})">Remove</a></td>`;
            row += `</tr>`;

            hostingCompaniesBody.innerHTML += row;
        });
        hiddenDataField.value = JSON.stringify(hostingCompaniesDetails);
        resetChanges();
    };

    removeCompany = function(index) {
        if (confirm('Are you sure you want to remove the info of this hosting company?')) {
            hostingCompaniesDetails.splice(index, 1);
            populateTable();
        }
    };

    editCompany = function(index) {
        hostingInEdit = index;
        const companyInEdit = hostingCompaniesDetails[hostingInEdit];
        hostingNameEl.value = companyInEdit.name;
        hostingSlugEl.value = companyInEdit.slug;

        hostingPackagesWrapper.innerHTML = '';
        if (companyInEdit.packages) {
            companyInEdit.packages.forEach(function (pkg, ind) {
                hostingPackagesWrapper.insertAdjacentHTML('beforeend', hostingPackageTemplate.replace(/%ID%/g, ind.toString()));
                document.getElementById(`hosting-package-name-${ind}`).value = pkg.title;
                document.getElementById(`hosting-package-starting-${ind}`).value = pkg.price;
            });
        }

        hostingLocationsWrapper.innerHTML = '';
        if (companyInEdit.locations) {
            companyInEdit.locations.forEach(function (loc, ind) {
                hostingLocationsWrapper.insertAdjacentHTML('beforeend', hostingLocationTemplate.replace(/%ID%/g, ind.toString()));
                document.getElementById(`hosting-location-name-${ind}`).value = loc;
            });
        }

    };

    populateTable();





    // Hosting Server Locations

    var serverLocationsBody = document.getElementById('server-locations-body');
    var serverLocationsDataHidden = document.getElementById('vq-hosting-server-locations');
    var serverLocationEl = document.getElementById('server-location-field');
    var serverDomainEl = document.getElementById('server-domain-field');
    var serverLocationInEdit = -1;



    saveServerLocation = function () {
        var serverLocation = {};
        serverLocation.location = serverLocationEl.value;
        serverLocation.domain = serverDomainEl.value;

        if (!serverLocation.location || !serverLocation.domain) {
            return alert('Domain & Location is required.');
        }

        if (serverLocationInEdit > -1) {
            serverLocationsDetails[serverLocationInEdit] = serverLocation;
        } else {
            serverLocationsDetails.push(serverLocation);
        }
        populateServerLocationsTable();
    };


    populateServerLocationsTable = function() {
        serverLocationsBody.innerHTML = '';

        serverLocationsDetails.forEach(function(serverLoc, index) {
            var row = `<tr>`;
            row += `<td>${serverLoc.location}</td>`;
            row += `<td>${serverLoc.domain}</td>`;
            row += `<td><a onclick="editServerLocation(${index})">Edit</a> <a class="ml-2 button-link-delete" onclick="removeServerLocation(${index})">Remove</a></td>`;
            row += `</tr>`;

            serverLocationsBody.innerHTML += row;
        });
        serverLocationsDataHidden.value = JSON.stringify(serverLocationsDetails);
        resetServerLocationsChanges();
    };

    editServerLocation = function(index) {
        serverLocationInEdit = index;
        const locationInEdit = serverLocationsDetails[serverLocationInEdit];
        serverLocationEl.value = locationInEdit.location;
        serverDomainEl.value = locationInEdit.domain;
    };

    removeServerLocation = function(index) {
        if (confirm('Are you sure you want to remove the info of this server location?')) {
            serverLocationsDetails.splice(index, 1);
            populateServerLocationsTable();
        }
    };


    resetServerLocationsChanges = function () {
        serverLocationInEdit = -1;
        serverLocationEl.value = '';
        serverDomainEl.value = '';
    };


    populateServerLocationsTable();
});





