<?php
/**
 * @package    JBusinessDirectory
 * @subpackage  com_jbusinessdirectory
 *
 * @copyright   Copyright (C) 2007 - 2015 CMS Junkie. All rights reserved.
 * @license     GNU General Public License version 2 or later;
 */

defined('_JEXEC') or die('Restricted access');

// Include the component HTML helpers.
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html');

// Load the tooltip behavior.
?>

<?php
$appSetings = JBusinessUtil::getApplicationSettings();
$tax=$this->item;

$options = array(
        'onActive' => 'function(title, description) {
		description.setStyle("display", "block");
		title.addClass("open").removeClass("closed");
	}',
        'onBackground' => 'function(title, description) {
		description.setStyle("display", "none");
		title.addClass("closed").removeClass("open");
	}',
        'startOffset' => 0,  // 0 starts on the first tab, 1 starts the second, etc...
        'useCookie' => true, // this must not be a string. Don't use quotes.
);
$jbdTabs = new JBDTabs();
?>

<script type="text/javascript">
    window.addEventListener('load', function() {
        Joomla.submitbutton = function (task) {

            var defaultLang = "<?php echo JBusinessUtil::getLanguageTag() ?>";

            jQuery("#item-form").validationEngine('detach');
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent("click", true, true);
            var tab = ("tab-" + defaultLang);
            if (!(document.getElementsByClassName(tab)[0] === undefined || document.getElementsByClassName(tab)[0] === null))
                document.getElementsByClassName(tab)[0].dispatchEvent(evt);
            if (task == 'tax.cancel' || !jbdUtils.validateCmpForm(true, false)) {
                Joomla.submitform(task, document.getElementById('item-form'));
            }
            jQuery("#item-form").validationEngine('attach');
        }
    });
</script>

<div id="jbd-container" class="jbd-container jbd-edit-container">
    <form action="<?php echo JRoute::_('index.php?option=com_jbusinessdirectory&layout=edit&id='.(int) $this->item->id); ?>" method="post" name="adminForm" id="item-form" class="form-horizontal">
        <div class="row">
            <div class="col-md-7">
                <div class="row">
                    <div class="col-md-12">
                        <fieldset class="boxed">
                            <h2> <?php echo JText::_('LNG_TAX'); ?></h2>
                            <p> <?php echo JText::_('LNG_TAXES_INFORMATION_TEXT'); ?></p>
                            <span id="tax_details">
                                <div class="form-container label-w-100" id="tax-form-box">
                                    <div class="form-group">
                                        <label for="tax_name"><?php echo JText::_('LNG_NAME') ?><?php echo JBusinessUtil::showMandatory(ATTRIBUTE_MANDATORY)?></label>
                                        <?php
                                        if($appSetings->enable_multilingual){
                                            $jbdTabs->setOptions($options);
                                            echo $jbdTabs->startTabSet('tab_groupsd_id');
                                            foreach( $this->languages as $k=>$lng ){
                                                echo $jbdTabs->addTab('tab_groupsd_id', 'tab-'.$lng, $k);
                                                $langContent = isset($this->translations[$lng."_name"])?$this->translations[$lng."_name"]:"";
                                                if($lng == JBusinessUtil::getLanguageTag() && empty($langContent)){
                                                    $langContent = $tax->tax_name;
                                                }
                                                $langContent=$this->escape($langContent);
                                                echo "<input type='text' name='name_$lng' id='name_$lng' class='input_txt form-control validate[required]' value=\"".stripslashes($langContent)."\"  maxLength='100'>";
                                                echo $jbdTabs->endTab();
                                            }
                                            echo $jbdTabs->endTabSet();
                                        } else { ?>
                                            <input type="text" name="tax_name" id="tax_name" class="input_txt form-control validate[required]" value="<?php echo $this->escape($tax->tax_name) ?>"  maxLength="100">
                                        <?php } ?>
                                    </div>

                                    <div class="form-group">
                                        <fieldset id="tax_type" class="radio btn-group btn-group-yesno">
                                            <input type="radio" class="validate[required]" name="tax_type" id="tax_type1" value="1" <?php echo $this->item->tax_type==1? 'checked="checked"' :""?> />
                                            <label class="btn" for="tax_type1"><?php echo JText::_('LNG_VALUE')?></label>
                                            <input type="radio" class="validate[required]" name="tax_type" id="tax_type2" value="2" <?php echo $this->item->tax_type==2? 'checked="checked"' :""?> />
                                            <label class="btn" for="tax_type2"><?php echo JText::_('LNG_PERCENT')?></label>
                                        </fieldset>
                                    </div>

                                    <div class="form-group">
                                        <label for="tax_amount"><?php echo JText::_('LNG_AMOUNT') ?><?php echo JBusinessUtil::showMandatory(ATTRIBUTE_MANDATORY)?></label>
                                        <input type="text" name="tax_amount" id="tax_amount"
                                               class="input_txt form-control validate[required]"
                                               value="<?php echo $tax->tax_amount ?>" maxlength="60">
                                    </div>

                                    <div class="mb-2 d-flex justify-content-start">
                                        <a href="javascript:void(0)" class="btn btn-primary" onclick="addTaxEntry()">
                                            <i class="la la-plus"></i>
                                        </a>
                                    </div>

                                    <div class="form-group" id="tax-country-config">
                                        <?php foreach ($this->item->countryAmounts as $val) { ?>

                                        <div class="d-flex justify-content-between mb-2">
                                            <select class="tax-chosen mt-2" name="onetomany_tax_countries_country_id[]" id="countries">
                                                <?php foreach ($this->countries as $country) {
                                                    $selected = "";
                                                    if ($country->id == $val->country_id) {
                                                        $selected = "selected";
                                                    } ?>
                                                    <option value="<?php echo $country->id ?>" <?php echo $selected ?>><?php echo $country->country_name ?></option>
                                                <?php } ?>
                                            </select>

                                            <input type="text" name="onetomany_tax_countries_amount[]" class="ml-2 validate[required]" value="<?php echo $val->amount ?>" style="min-height: 27px !important;">
                                            <a href="javascript:void(0);" onclick="jQuery(this).parent().remove()" class="m-auto"><i class="la la-times"></i></a>
                                        </div>

                                        <?php } ?>
                                    </div>

                                    <div class="form-group">
                                        <label for="services"><?php echo JText::_('LNG_SERVICES') ?><?php echo JBusinessUtil::showMandatory(ATTRIBUTE_MANDATORY) ?></label>
                                        <select data-placeholder="<?php echo JText::_("LNG_SELECT_SERVICE") ?>" class="form-control select chosen-select validate[required]" multiple name="servicesId[]" id="services">
                                            <?php
                                            foreach ($this->item->services as $service) {
                                                $selected = false;
                                                foreach($this->item->selectedServices as $sService) {
                                                    if($sService->app_id == $service->id)
                                                        $selected = true;
                                                } ?>
                                                <option <?php echo $selected ? "selected" : ""?> value='<?php echo $service->id ?>'>
                                                    <?php echo $service->name ?>
                                                </option>
                                                <?php
                                            } ?>
                                        </select>
                                    </div>

                                    <div class="form-group">
                                        <label for="tax_description"><?php echo JText::_('LNG_DESCRIPTION') ?></label>
                                        <?php
                                        if($appSetings->enable_multilingual) {
                                            $jbdTabs->setOptions($options);
                                            echo $jbdTabs->startTabSet('tab_groupsd_id');
                                            foreach( $this->languages  as $k=>$lng ) {
                                                echo $jbdTabs->addTab('tab_groupsd_id', 'tab-'.$lng, $k);
                                                $langContent = isset($this->translations[$lng])?$this->translations[$lng]:"";
                                                if($lng==JBusinessUtil::getLanguageTag() && empty($langContent)) {
                                                    $langContent = $tax->tax_description;
                                                }
                                                echo "<textarea id='description_$lng' name='description_$lng' class='input_txt form-control h-auto' cols='75' rows='5' maxLength='250'>$langContent</textarea>";
                                                echo $jbdTabs->endTab();
                                            }
                                            echo $jbdTabs->endTabSet();
                                        } else { ?>
                                            <textarea name="tax_description" id="tax_description" class="input_txt form-control h-auto"  cols="75" rows="5"  maxLength="250"><?php echo $tax->tax_description ?></textarea>
                                            <?php
                                        } ?>
                                    </div>

                                    <input type="hidden" name="id" id="id" value="<?php echo $tax->id ?>"/>
                                    <hr/>
                                </div>
                            </span>
                        </fieldset>
                    </div>
                </div>
            </div>
        </div>
        <input type="hidden" name="option" value="<?php echo JBusinessUtil::getComponentName()?>" />
        <input type="hidden" name="task" id="task" value="" />
        <input type="hidden" name="id" value="<?php echo $tax->id ?>" />
        <input type="hidden" name="view" id="view" value="tax" />
        <?php echo JHTML::_( 'form.token' ); ?>
    </form>
</div>

<script>
    window.addEventListener('load', function() {
        jQuery(".chosen-select").chosen({placeholder_text_single: "<?php echo JText::_('LNG_SELECT_OPTION')  ?>" , placeholder_text_multiple: "<?php echo JText::_('LNG_SELECT_OPTION')  ?>"});
        jQuery('.tax-chosen').chosen();
    });

    let countries = <?php echo json_encode($this->countries) ?>;

    function addTaxEntry() {
        let selectedCountries = [];
        jQuery('.tax-chosen').each(function() {
            selectedCountries.push(jQuery(this).find(':selected').val());
        });

        let html = `
            <div class="d-flex justify-content-between mb-2">
               <select class="tax-chosen" name="onetomany_tax_countries_country_id[]" id="countries">
                ${countries.map((country) => {
            if (!selectedCountries.includes(country.id)) {
                return `<option value="${country.id}">${country.country_name}</option>`
            }
        })}
                </select>

                <input type="text" name="onetomany_tax_countries_amount[]" class="ml-2 validate[required]" style="min-height: 27px !important;">
                <a href="javascript:void(0);" onclick="jQuery(this).parent().remove()" class="m-auto"><i class="la la-times"></i></a>
            </div>
	    `;

        jQuery('#tax-country-config').append(html);
        jQuery('.tax-chosen').chosen();
    }
</script>