<?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();
$project=$this->item;
$maxPictures = 5;
$nrPictures = count($project->pictures);
$allowedNr = $maxPictures - $nrPictures;
$allowedNr=($allowedNr<0)?0:$allowedNr;
$allowedNr = ($allowedNr == 0)?$maxPictures:$allowedNr;

?>

<?php
$appSetings = JBusinessUtil::getApplicationSettings();
$user = JBusinessUtil::getUser();

$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();
$jbdTabs->setOptions($options);
?>

<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 == 'project.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="button-row">
	        <button id="save-btn" type="button" class="btn btn-success button-save" onclick="saveCompanyProjectInformation('apply')">
	            <i class="la la-edit"></i> <?php echo JText::_("LNG_SAVE")?>
	        </button>
	        <button type="button" class="btn btn-success button-close" onclick="saveCompanyProjectInformation('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()">
	            <span class="ui-button-text"><i class="la la la-close"></i> <?php echo JText::_("LNG_CANCEL")?></span>
	        </button>
	    </div>
	    <div class="clear"></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" enctype="multipart/form-data">
        <div class="row">
            <div class="col-md-9">
                <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 ajax-chosen-select <?php echo !$this->appSettings->item_decouple?"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="row">
                	<div class="col-12">
                        <fieldset class="boxed" >
                        	<div class="row">
                        		<div class="col-md">
                        			<h3> <?php echo JText::_('LNG_PROJECT');?></h3>
                            		<p><?php echo JText::_('LNG_PROJECT_INFO_TXT');?></p>		
                        		</div>
                        		<div class="col-md-5 my-auto text-right">
                			         <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 $project->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 $project->status==0? 'checked="checked"' :""?> />
                                        <label class="btn" for="status0"><?php echo JText::_('LNG_UNPUBLISHED')?></label>
                                    </fieldset>
                            	</div>
                        	</div>
                            <div class="form-container" id="tax-form-box">
                                <div class="form-group">
                                    <label for="name"><?php echo JText::_('LNG_NAME') ?><?php echo JBusinessUtil::showMandatory(ATTRIBUTE_MANDATORY) ?></label>
                                    <?php
                                    if($appSetings->enable_multilingual){
                                        echo $jbdTabs->startTabSet('tab_group_name');
                                        foreach( $this->languages as $k=>$lng ){
                                            echo $jbdTabs->addTab('tab_group_name', 'tab-' . $lng, $k);
                                            $langContent = isset($this->translations[$lng."_name"])?$this->translations[$lng."_name"]:"";
                                            if($lng == JBusinessUtil::getLanguageTag() && empty($langContent)){
                                                $langContent = $project->name;
                                            }
                                            echo "<input type='text' name='name_$lng' id='name_$lng' class='input_txt validate[required]' value=\"".stripslashes($langContent)."\"  maxLength='100'>";
                                            echo $jbdTabs->endTab();
                                        }
                                        echo $jbdTabs->endTabSet();
                                    } else { ?>
                                        <input type="text" name="name" id="name" class="input_txt validate[required]" value="<?php echo $project->name ?>"  maxLength="100">
                                    <?php } ?>
                                </div>

                                <div class="form-group">
                                    <label for="description"><?php echo JText::_('LNG_DESCRIPTION') ?></label>
                                    <?php
                                    if($appSetings->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])?$this->translations[$lng]:"";
                                            if($lng==JBusinessUtil::getLanguageTag() && empty($langContent)) {
                                                $langContent = $project->description;
                                            }
                                            echo "<textarea id='description_$lng' name='description_$lng' class='input_txt' cols='75' rows='5'>$langContent</textarea>";
                                            echo $jbdTabs->endTab();
                                        }
                                        echo $jbdTabs->endTabSet();
                                    } else { ?>
                                        <textarea name="description" id="description" class="input_txt"  cols="75" rows="5"><?php echo $project->description ?></textarea>
                                        <?php
                                    } ?>
                                </div>
                            </div>
                   		 </fieldset>

                        <fieldset class="boxed">
                            <h2> <?php echo JText::_('LNG_PROJECT_PICTURES');?> </h2>
                            <p> <?php echo JText::_('LNG_PROJECT_PICTURES_INFORMATION_TEXT');?>.</p>
                            <a class="btn btn-outline-danger" id="remove-pictures" href="javascript:void(0);" onclick="uploadInstance.removeAllPicture()"><?php echo JText::_('LNG_DELETE_ALL')?></a>
                            <input type='button' name='btn_removefile' id='btn_removefile' value='x' style='display:none'>
                            <input type='hidden' name='crt_pos' id='crt_pos' value=''>
                            <input type='hidden' name='crt_path' id='crt_path' value=''>
    
                            <div class="jupload" id="pictures-list">
                                <div class="jupload-header">
                                    <div class="jupload-header-title"></div>
                                    <div class="jupload-header-desc"></div>
                                </div>
                                <div class="jupload-body">
                                    <ul id="sortable" class="jbd-item-list">
                                        <?php
                                        if (!empty($project->pictures)) {
                                            foreach ($project->pictures as $picture ) { ?>
                                                <li class="jbd-item" id="jbd-item-<?php echo $picture['id'] ?>">
                                                    <div class="jupload-files">
                                                        <div class="jupload-files-img">
                                                            <img src='<?php echo BD_PICTURES_PATH.$picture['picture_path']?>'>
                                                        </div>
                                                        <div class="jupload-files-info">
                                                            <div class="jupload-filename">
                                                                <p><?php echo substr(basename($picture['picture_path']),0,30)?></p>
                                                                <input id="jupload-filename-<?php echo $picture['id'] ?>" type="text"
                                                                       name="picture_info[]" value="<?php echo $picture['picture_info']?>">
                                                            </div>
                                                            <div class="jupload-actions jbd-item-actions">
                                                                <label for="jupload-filename-<?php echo $picture['id'] ?>">
                                                                    <i class="la la-pencil"></i>
                                                                </label>
    
                                                                <input type="hidden" name="picture_enable[]" id="picture_enable_<?php echo $picture['id'] ?>" value="<?php echo $picture['picture_enable'] ?>" />
                                                                <input type='hidden' name='picture_path[]' id='picture_path_<?php echo $picture['id'] ?>' value='<?php echo $this->escape($picture['picture_path'])?>' />
                                                            </div>
                                                        </div>
                                                    </div>
                                                </li>
    
                                                <?php
                                            }
                                        } ?>
                                    </ul>
    
                                    <div class="dropzone dropzone-previews container-fluid" id="file-upload">
                                        <div id="actions" style="margin-left:-15px;" class="row">
                                            <div class="col d-flex justify-content-center">
                                                <!-- The fileinput-button span is used to style the file input field as button -->
                                                <span class="btn btn-success fileinput-button dz-clickable mr-1">
                                                                        <i class="glyphicon glyphicon-plus"></i>
                                                                        <span><?php echo JText::_('LNG_ADD_FILES'); ?></span>
                                                                    </span>
                                                <button  class="btn btn-primary start" id="submitAll">
                                                    <i class="glyphicon glyphicon-upload"></i>
                                                    <span><?php echo JText::_('LNG_UPLOAD_ALL'); ?></span>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </fieldset>
					</div>
            	</div>
                <div class="jbd-admin-column">
                    <?php if(isset($isProfile)) { ?>
                        <div class="button-row">
                            <button id="save-btn" type="button" class="btn btn-success button-save" onclick="saveCompanyProjectInformation('apply')">
                                <i class="la la-edit"></i> <?php echo JText::_("LNG_SAVE")?>
                            </button>
                            <button type="button" class="btn btn-success button-close" onclick="saveCompanyProjectInformation('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()">
                                <span class="ui-button-text"><i class="la la la-close"></i> <?php echo JText::_("LNG_CANCEL")?></span>
                            </button>
                        </div>
                        <?php
                    } ?>
                </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 $project->id ?>" />
        <input type="hidden" name="view" id="view" value="project" />
        <?php echo JHTML::_( 'form.token' ); ?>
    </form>
</div>

<?php JBusinessUtil::loadUploadScript(false, true); ?>

<script>
    jQuery(".button-cancel").click(function() {
        jQuery(this).addClass("loader")
    })
    var projectFolder = '<?php echo PROJECT_PICTURES_PATH.((int)$this->item->id)."/"?>';
    var projectFolderPath = '<?php echo JBusinessUtil::getUploadUrl() ?>&t=<?php echo strtotime("now")?>&picture_type=<?php echo PICTURE_TYPE_OFFER?>&_path_type=1&_target=<?php echo urlencode(PROJECT_PICTURES_PATH.((int)$this->item->id)."/")?>';
    var removePath = '<?php echo JBusinessUtil::getUploadUrl('remove') ?>&_path_type=3&_filename=';
    var maxPictures = '<?php echo $maxPictures ?>';

    var uploadInstance;
    
    window.addEventListener('load', function() {

        uploadInstance = JBDUploadHelper.getUploadInstance({
            'maxPictures': maxPictures,
            'removePath': removePath
        });

        uploadInstance.btn_removefile();
        uploadInstance.imageUploaderDropzone(
            "#file-upload",
            '<?php echo JBusinessUtil::getUploadUrl() ?>&t=<?php echo strtotime("now")?>&_path_type=1&picture_type=<?php echo PICTURE_TYPE_GALLERY?>&_target=<?php echo urlencode(PROJECT_PICTURES_PATH.($this->item->id+0)."/")?>',
            ".fileinput-button","<?php echo JText::_('LNG_DRAG_N_DROP',true); ?>",
            projectFolder ,<?php echo $allowedNr ?>,
            "addPicture"
        );

        jQuery( "#sortable" ).sortable();
        jQuery( "#sortable" ).disableSelection();

        jQuery('#pictures-list').jbdList({
            statusCallback: uploadInstance.changePictureStatus,
            deleteCallback: uploadInstance.deletePicture,
            statusSelector: 'picture_enable_',
            deleteMsg: "<?php echo JText::_('LNG_CONFIRM_DELETE_PICTURE') ?>"
        });

        jQuery(".ajax-chosen-select").chosen({width: "95%", disable_search_threshold: -1, allow_single_deselect: true});
        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')  ?>";
        }
        
        if (jbdUtils.getProperty("isProfile") != 1) {
            var isProfile = false;
            var userId = 0;
        } else {
            var userId = '<?php echo $user->id ?>';
        }

        let urlGetCompanies = jbdUtils.getAjaxUrl('getCompaniesByStringAjax', 'companies', 'managecompanies');

        jQuery("#company_id").ajaxChosen({
                type: 'GET',
                url: urlGetCompanies,
                data: {
                    isProfile: isProfile,
                    userId: userId
                },
                dataType: 'json'
            },
            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
            });
    });

    function saveCompanyProjectInformation(task) {
        var defaultLang="<?php echo JBusinessUtil::getLanguageTag() ?>";
        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(jbdUtils.validateCmpForm(true, true))
            return false;
        jQuery("#task").val('managecompanyproject.'+task);
        var form = document.adminForm;
        form.submit();
    }

    function cancel() {
        jQuery("#task").val('managecompanyproject.cancel');
        var form = document.adminForm;
        form.submit();
    }
</script>