<?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.
JBusinessUtil::loadJQueryChosen();

$appSetings = JBusinessUtil::getApplicationSettings();
$user = JBusinessUtil::getUser();
$item=$this->item;
?>

<?php
$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) {

        jQuery("#item-form").validationEngine('detach');
        if (task == 'announcement.cancel' || !jbdUtils.validateCmpForm(false, false)) {
            Joomla.submitform(task, document.getElementById('item-form'));
        }
        jQuery("#item-form").validationEngine('attach');
    }
})
</script>

<div id="jbd-container" class="jbd-container jbd-edit-container">
    <?php  if(isset($isProfile)) { ?>
        <div class="row py-2 mb-2">
            <div class="col-md-12">
                <div>
                    <div class="button-row">
                        <button type="button" class="btn btn-success button-save" onclick="saveAnnouncementCompanyInformation('apply');">
                            <span class="ui-button-text"><i class="la la-edit"></i> <?php echo JText::_("LNG_SAVE")?></span>
                        </button>
                        <button type="button" class="btn btn-success button-close" onclick="saveAnnouncementCompanyInformation('save');">
                            <span class="ui-button-text"><i class="la la-check"></i> <?php echo JText::_("LNG_SAVE_AND_CLOSE")?></span>
                        </button>
                        <button type="button" class="btn btn-dark button-cancel" onclick="cancel()">
                            <i class="la la-close"></i> <?php echo JText::_("LNG_CANCEL")?>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    <?php  } ?>

    <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="<?php echo (!isset($isProfile))?"col-md-9":"col-md-12"?>">
            
	            <div class="row">
	    			<div class="col-12">
	    				<fieldset class="boxed">
	    					<div class="row align-items-center">
	    			 			<div class="col-md ">
	    			 				<strong><?php echo JText::_('LNG_SELECT_A_BUSINESS')?> <?php echo JBusinessUtil::showMandatory(ATTRIBUTE_MANDATORY)?></strong>
	    			 			</div>
	    			 			<div class="col-md">
	    			 				<select data-placeholder="<?php echo JText::_("LNG_SELECT_OR_SEARCH_COMPANY") ?>" class="form-control input-medium chosen-select ajax-chosen-select validate[required]" name="company_id" id="company_id">
	                                	<option value=""><?php echo JText::_("LNG_SELECT_OR_SEARCH_COMPANY")?></option>
	                                    <?php if (!empty($this->item->company_id))
		                                    echo JHtml::_('select.options', $this->item->companyOptions, 'id', 'name', $this->item->company_id);
	                                    ?>
	                                    <?php echo JHtml::_('select.options', $this->companyOptions, 'id', 'name', -1); ?>
	            					</select>
	    			 			</div>
	    			 		</div>
	        			</fieldset>
	    			 </div>
		   		</div>
	   			 
                <div class="">
                    <fieldset class="boxed" style="max-width: unset;">
                        <h2> <?php echo JText::_('LNG_ANNOUNCEMENT'); ?></h2>
                        <?php if (!empty($item->id)){ ?>
                            <a href="javascript:changeAction('<?php echo $item->id ?>',true)"><?php echo JText::_("LNG_DISPLAY_SAVED_ITEM")?></a>
                        <?php } ?>

                        <div class="form-container" id="tax-form-box">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="state"><?php echo JText::_('LNG_CALL_TO_ACTION')?></label>
                                        <select data-placeholder="<?php echo JText::_("LNG_SELECT_CALL_TO_ACTION") ?>" class="form-control input-medium chosen-select" name="call_to_action" id="call_to_action" onchange="changeAction(this.value)">
                                            <?php foreach($this->actions as $action){ ?>
                                                <option value = '<?php echo $action->id?>' <?php echo $action->id==$item->call_to_action? "selected" : ""?>> <?php echo $action->name ?></option>
                                            <?php }	?>
                                        </select>
                                    </div>
                                   
                                    <div class="form-group">
                                        <label for="icon"><?php echo JText::_('LNG_ICON')?><?php echo JBusinessUtil::showMandatory(ATTRIBUTE_MANDATORY); ?> (<a href="https://icons8.com/line-awesome" target="_blank"> Line Awesome </a>) </label>
                                        <input type="text" name="icon" id="icon" value="<?php echo $this->escape($item->icon) ?>"
                                               placeholder="<?php echo JText::_('LNG_ICON_PLACEHOLDER')?>" class="form-control validate[required]" maxlength="100" onchange="changeIcon(this.value)">
                                    </div>

                                    <div class="form-group">
                                        <label for="button_text"><?php echo JText::_('LNG_BUTTON_TEXT')?></label>
                                        <?php
                                        if($this->appSettings->enable_multilingual) {
                                            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."_short"])?$this->translations[$lng."_short"]:"";
                                                if($lng==JBusinessUtil::getLanguageTag() && empty($langContent)) {
                                                    $langContent = $this->item->button_text;
                                                }
                                                echo "<input type='text' id='button_text_$lng' name='button_text_$lng' value=\"".stripslashes($langContent)."\" class='form-control' maxlength='100'
                                                oninput='changeButtonText(this.value)'>";
                                                echo $jbdTabs->endTab();
                                            }
                                            echo $jbdTabs->endTabSet();
                                        } else { ?>
                                            <input type="text" name="button_text" id="button_text" value="<?php echo $this->escape($item->button_text) ?>" class="form-control" maxlength="100"
                                               oninput="changeButtonText(this.value)">
                                        <?php } ?>
                                        
                                    </div>

                                    <div class="form-group">
                                        <label for="button_link"><?php echo JText::_('LNG_BUTTON_LINK')?></label>
                                        <input type="text" name="button_link" id="button_link" value="<?php echo $this->escape($item->button_link) ?>" class="form-control" maxlength="100"
                                               oninput="changeButtonLink(this.value)">
                                    </div>

                                    <div class="form-group">
                                        <label for="startDate"><?php echo JText::_('LNG_EXPIRATION_DATE')?> </label>
                                        <?php echo JHTML::_('calendar', $this->item->expiration_date, 'expiration_date', 'expiration_date', $this->appSettings->calendarFormat, array('style'=>'display:inline;','class'=>'inputbox calendar-date', 'size'=>'10', 'maxlength'=>'10')); ?>
                                    </div>

                                    <div class="form-group">
                                        <label for="status"><?php echo JText::_('LNG_STATUS')?> </label>
                                        <fieldset id="status_fld" class="radio btn-group btn-group-yesno">
                                            <input type="radio" class="validate[required]" name="status" id="status1" value="1" <?php echo $item->status==1? 'checked="checked"' :""?> />
                                            <label class="btn" for="status1"><?php echo JText::_('LNG_PUBLISHED')?></label>
                                            <input type="radio" class="validate[required]" name="status" id="status0" value="0" <?php echo $item->status==0? 'checked="checked"' :""?> />
                                            <label class="btn" for="status0"><?php echo JText::_('LNG_UNPUBLISHED')?></label>
                                        </fieldset>
                                        <div class="clear"></div>
                                    </div>
                                </div>

                                <div class="col-md-7">

                                    <div class="form-group announcement-preview">
                                        <label><?php echo JText::_('LNG_PREVIEW')?></label>
                                                <div class="listing-announcement">
                                                    <div class="announcement-container">
                                                        <i class="" id="icon-attr" aria-hidden="true"></i>
                                                        <p>
                                                            <strong id="text-attr"></strong>
                                                            <span id="description-attr"></span>
                                                        </p>
                                                        <a target="_blank" id="button-attr" href="#" class="announcement-btn"></a>
                                                        <div class="clearfix"></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label for="title"><?php echo JText::_('LNG_TITLE')?><?php echo JBusinessUtil::showMandatory(ATTRIBUTE_MANDATORY); ?></label>
                                        <?php
                                        if ($this->appSettings->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 = $this->item->title;
                                                }
                                                $langContent = $this->escape($langContent);
                                                echo "<input type='text' name='title_$lng' id='title_$lng' value=\"".stripslashes($langContent)."\" class='form-control validate[required]' maxlength='100'
                                                oninput='changeTitleText(this.value)'>";
                                                echo $jbdTabs->endTab();
                                            }
                                            echo $jbdTabs->endTabSet();
                                        } else { ?>
                                            <input type="text" name="title" id="title" value="<?php echo $this->escape($item->title) ?>" class="form-control validate[required]" maxlength="100"
                                                oninput="changeTitleText(this.value)">
                                        <?php } ?>                                        
                                    </div>

                                    <div class="form-group">
                                        <label for="description"><?php echo JText::_('LNG_DESCRIPTION')?></label>
                                        <?php
                                            if($this->appSettings->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 = $this->item->description;
                                                    }
                                                    echo "<textarea id='description_$lng' name='description_$lng' class='form-control h-auto' cols='75' rows='5' maxLength='255' oninput='changeDescText(this.value)'>$langContent</textarea>";
                                                    echo $jbdTabs->endTab();
                                                }
                                                echo $jbdTabs->endTabSet();
                                                }else {
                                                    ?>
                                            <textarea name="description" id="description" class="form-control h-auto" cols="75" rows="5" maxLength="255"
                                                    oninput="changeDescText(this.value)"><?php echo $item->description ?></textarea>
                                            <?php
                                            }
                                            ?>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </fieldset>
                </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" id="id" value="<?php echo $item->id ?>" />
        <input type="hidden" name="view" id="view" value="announcement" />
        <?php echo JHTML::_( 'form.token' ); ?>
    </form>
</div>

<script>
    jQuery(".button-cancel").click(function() {
        jQuery(this).addClass("loader")
    })
    function changeAction(value,saved){

        if (typeof saved == 'undefined') {
            saved = false;
        }

        var itemId = '<?php echo $item->id ?>';
        var title = '';
        var description = '';
        var icon = '';
        var button_text = '';
        var button_link = '';

        if (value == itemId && saved){
            title = '<?php echo $item->title ?>';
            description = '<?php echo str_replace( array( "\n", "\r" ), array( "<br/>", "\\r" ), $item->description ); ?>';
            icon = '<?php echo $item->icon ?>';
            button_text = '<?php echo $item->button_text ?>';
            button_link = '<?php echo $item->button_link ?>';
            jQuery('#call_to_action').val('<?php echo $item->call_to_action ?>');
            jbdUtils.updateChosenSelect('select#call_to_action');
        } else {
            <?php foreach ($this->actions as $action) { ?>
            var id = '<?php echo $action->id ?>';
            if (id == value) {
                title = '<?php echo $action->title ?>';
                description = '<?php echo $action->description ?>';
                icon = '<?php echo $action->icon ?>';
                button_text = '<?php echo $action->button_text ?>';
                //button_link = '<?php echo $action->button_link ?>';
            }
            <?php } ?>
        }

        jQuery(".listing-announcement").html();
        jQuery('.listing-announcement').html(
            '<div class="announcement-container">\n' +
                '<i class="'+icon+'" id="icon-attr" aria-hidden="true"></i>\n' +
                '<p>\n' +
                    '<strong id="text-attr" >'+title+'</strong>\n' +
                    '<span id="description-attr" >'+description+'</span>\n' +
                '</p>\n' +
                '<a target="_blank" id="button-attr" href="'+button_link+'" class="announcement-btn">'+button_text+'</a>\n' +
                '<div class="clearfix"></div>\n' +
            '</div>'
        );
        jQuery('#title').val(title);
        jQuery('#description').val(description);
        jQuery('#icon').val(icon);
        jQuery('#button_text').val(button_text);
        jQuery('#button_link').val(button_link);

    }

    function changeIcon(value){
        document.getElementById('icon-attr').className = value;
    }

    function changeButtonText(value){
        document.getElementById('button-attr').innerHTML = value;
    }

    function changeButtonLink(value){
        if(value.indexOf('http') == -1){
            value = 'http://'+value;
        }
        if (value == ''){
            value = '';
        }
        document.getElementById('b-attr').href = value;
    }

    function changeTitleText(value){
        console.log(document.getElementById('t-attr'));
        document.getElementById('text-attr').innerHTML = value;
    }

    function changeDescText(value){
        document.getElementById('description-attr').innerHTML = value;
    }

    function saveAnnouncementCompanyInformation(task) {
        jQuery("#item-form").validationEngine('detach');
        if (jbdUtils.validateCmpForm(false, false)) {
            return false;
        }
        jQuery("#item-form").validationEngine('attach');
        jQuery("#task").val('managecompanyannouncement.'+task);
        Joomla.submitform('managecompanyannouncement.'+task, document.getElementById('item-form'));
    }

    function cancel() {
        jQuery("#task").val('managecompanyannouncement.cancel');
        var form = document.adminForm;
        form.submit();
    }

    window.addEventListener('load', function() {
        jQuery(".chosen-select").chosen({width: "95%",disable_search_threshold:10,allow_single_deselect: true, search_contains: true, placeholder_text_single: "<?php echo JText::_('LNG_SELECT_OPTION')  ?>" , placeholder_text_multiple: "<?php echo JText::_('LNG_SELECT_OPTION')  ?>"});
        if(jQuery("#company_id_chosen input").length || jQuery("#company_id_chzn input").length){
            document.querySelector("#company_id_chosen input, #company_id_chzn input").placeholder = "<?php echo JText::_('LNG_COMPANY_SEARCH_HINT')  ?>";
        }
        let isProfile = true;
        let userId = '<?php echo $user->id ?>';
        if (jbdUtils.getProperty("isProfile") != 1) {
            let isProfile = false;
            let userId = 0;
        } 
        let url = jbdUtils.getAjaxUrl('getCompaniesByStringAjax', 'companies', 'managecompanies');

        jQuery("#company_id").ajaxChosen({
                type: 'GET',
                url: url,
                data: {
                    isProfile:isProfile,
                    userId:userId
                },
                dataType: 'json',
                cache:false,
            },
            function (data) {
                var results = [];
                jQuery.each(data, function (i, val) {
                    results.push({value: val.id, text: val.name});
                });
                return results;
            },
            {
                width: "95%",disable_search_threshold:-1,allow_single_deselect: true
            });
        <?php if (!empty($item->id)){ ?>
            changeAction('<?php echo $item->id ?>',true);
        <?php } else { ?>
            changeAction(1);
        <?php } ?>
        });
</script>