<?php

/**
 * @version        1.9.7
 * @package        Joomla
 * @subpackage     EDocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011 - 2024 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
// no direct access
defined( '_JEXEC' ) or die ;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;

EDocmanHelper::loadBootstrapJs();
$controlGroupClass = $bootstrapHelper->getClassMapping('control-group');
$controlLabelClass = $bootstrapHelper->getClassMapping('control-label');
$controlsClass     = $bootstrapHelper->getClassMapping('controls');
$rowFluidClass	   = $bootstrapHelper->getClassMapping('row-fluid');
$span12Class	   = $bootstrapHelper->getClassMapping('span12');
if(!isset($config))
{
	$config		   = EDocmanHelper::getConfig();
}
?>
<div id="form-content" class="modal fade" style="display: none;">
	<div class="modal-header">
		<?php
		if($config->twitter_bootstrap_version == 2){	
		?>
			<a class="close" data-dismiss="modal">x</a>
		<?php } ?>
		<h2><?php echo Text::_('EDOCMAN_DOWNLOAD_DOCUMENT'); ?></h2>
	</div>
	<div class="alert alert-success" id="downloadsuccess">
		<a href="#" class="close" data-dismiss="alert">&times;</a>
		<p id="download-complete-message" class="download-complete-message"></p>
	</div>
	<div class="modal-body-download <?php echo $rowFluidClass;?>">
		<div class="<?php echo $span12Class?>">
			<form class="edocman-download-form form form-horizontal" name="download-form">
				<p class="text-info" id="download-instruction"><?php echo Text::_('EDOCMAN_COMPLETE_FORM_TO_DOWNLOAD'); ?></p>
				<div class="<?php echo $controlGroupClass;  ?>">
					<label class="<?php echo $controlLabelClass; ?>" for="name">
						<?php echo  Text::_('EDOCMAN_NAME') ?><span class="required">*</span>
					</label>
					<div class="<?php echo $controlsClass; ?>">
						<input type="text" name="name" id="edocman-name" class="input-xlarge form-control"/>
					</div>
				</div>

				<div class="<?php echo $controlGroupClass;  ?>">
					<label class="<?php echo $controlLabelClass; ?>" for="name">
						<?php echo  Text::_('EDOCMAN_EMAIL') ?><span class="required">*</span>
					</label>
					<div class="<?php echo $controlsClass; ?>">
						<input id="email" type="email" name="email" value="" class="input-xlarge form-control"><br>
					</div>
				</div>
                <?php
                if($config->turn_on_privacy){
                ?>
                <div class="<?php echo $controlGroupClass;  ?>">
                    <input type="checkbox" name="privacy_agreement" id="privacy_agreement" value="0"/>
                    <span id="privacy_agreement_span">
                    <?php
                    echo Text::_('EDOCMAN_AGREE_PRIVACY_POLICY_MESSAGE');
                    ?>
                    </span>
                </div>
                <?php } ?>
			</form>
		</div>
	</div>
	<div class="modal-footer">
		<input class="btn btn-success btn-send" type="button" value="<?php echo Text::_('EDOCMAN_PROCESS'); ?>">
		<a href="#" class="btn btn-close" data-dismiss="modal"><?php echo Text::_('EDOCMAN_CLOSE'); ?></a>
	</div>
</div>

<script id="dynamic" type="text/javascript">
	(function() {
    if (typeof(Edocman) === 'undefined') {
        var Edocman = {};
    }
    
    // Since we're removing jQuery dependency, we don't need noConflict
    // Edocman.jQuery = jQuery.noConflict()
    
    document.addEventListener('DOMContentLoaded', function() {
        // Hide elements
        const progressElements = document.querySelectorAll('.progress');
        progressElements.forEach(function(element) {
            element.style.display = 'none';
        });
        
        const downloadSuccess = document.getElementById('downloadsuccess');
        if (downloadSuccess) {
            downloadSuccess.style.display = 'none';
        }
        
        const modal = document.getElementById('form-content');
        
        // Set up email popup click handlers
        const emailPopupButtons = document.querySelectorAll('.email-popup');
        emailPopupButtons.forEach(function(button) {
            button.addEventListener('click', function() {
                const documentTitle = this.getAttribute('data-document-title');
                const downloadInstruction = document.getElementById('download-instruction');
                if (downloadInstruction) {
                    let instruction = downloadInstruction.innerHTML;
                    instruction = instruction.replace('[DOCUMENT_TITLE]', documentTitle);
                    downloadInstruction.innerHTML = instruction;
                }
                
                const btnSend = document.querySelector('.btn-send');
                if (btnSend) {
                    btnSend.setAttribute('id', this.getAttribute('id'));
                }
            });
        });
        
        // Responsive modal setup
        const screenWidth = document.documentElement.clientWidth;
        
        if (modal) {
            if (screenWidth < 400) {
                modal.classList.remove('fade');
                modal.style.width = '300px';
                modal.style.height = '400px';
                modal.style.marginLeft = '0';
                
                // Bootstrap modal equivalent in vanilla JS
                // This is simplified and would need a proper modal implementation
                // or a vanilla JS modal library
            } else {
                modal.style.width = '500px';
                modal.style.height = '400px';
                modal.style.top = '20%';
                modal.style.marginLeft = '-250px'; // Half of the width
                
                // Bootstrap modal equivalent in vanilla JS
                // This is simplified and would need a proper modal implementation
            }
            
            // Close button handler
            const closeButtons = modal.querySelectorAll('.btn-close');
            closeButtons.forEach(function(button) {
                button.addEventListener('click', function(e) {
                    window.location = '<?php echo Uri::getInstance()->toString();?>';
                });
            });
            
            // Send button handler
            const sendButtons = modal.querySelectorAll('.btn-send');
            sendButtons.forEach(function(button) {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    const validate = validateForm();
                    if (validate) {
                        this.setAttribute('disabled', 'disabled');
                        
                        // Create loading image
                        const waitSpan = document.createElement('span');
                        waitSpan.className = 'wait';
                        waitSpan.innerHTML = '&nbsp;<img src="components/com_edocman/assets/images/loading.gif" alt="" />';
                        this.parentNode.insertBefore(waitSpan, this);
                        
                        const documentId = this.getAttribute('id');
                        const data = new FormData();
                        data.append('task', 'document.store_download');
                        data.append('document_id', documentId);
                        data.append('name', document.getElementById('edocman-name').value);
                        data.append('email', document.getElementById('email').value);
                        
                        fetch('<?php echo Uri::root(true);?>/index.php?option=com_edocman', {
                            method: 'POST',
                            body: data
                        })
                        .then(response => response.text())
                        .then(htmltext => {
                            const modalBodyDownload = document.querySelector('.modal-body-download');
                            if (modalBodyDownload) {
                                modalBodyDownload.style.display = 'none';
                            }
                            
                            const waitElements = document.querySelectorAll('.wait');
                            waitElements.forEach(function(element) {
                                element.remove();
                            });
                            
                            if (downloadSuccess) {
                                downloadSuccess.style.display = 'block';
                            }
                            
                            const downloadCompleteMessage = document.querySelector('.download-complete-message');
                            if (downloadCompleteMessage) {
                                downloadCompleteMessage.innerHTML = htmltext;
                            }
                        })
                        .catch(error => {
                            alert(error);
                        });
                    }
                });
            });
        }
        
        function validateForm() {
            const emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,10})?$/;
            const name = document.getElementById('edocman-name').value;
            const email = document.getElementById('email').value;
            const inputVal = [name, email];
            const inputMessage = ["name", "email address"];
            
            // Hide all error messages first
            const errorElements = document.querySelectorAll('.error');
            errorElements.forEach(function(element) {
                element.style.display = 'none';
            });
            
            // Validate name
            if (inputVal[0] === "") {
                const nameField = document.getElementById('edocman-name');
                const errorSpan = document.createElement('span');
                errorSpan.className = 'error';
                errorSpan.textContent = ' Please enter your ' + inputMessage[0];
                nameField.parentNode.insertBefore(errorSpan, nameField.nextSibling);
                return false;
            }
            
            // Validate email
            if (inputVal[1] === "") {
                const emailField = document.getElementById('email');
                const errorSpan = document.createElement('span');
                errorSpan.className = 'error';
                errorSpan.textContent = ' Please enter your ' + inputMessage[1];
                emailField.parentNode.insertBefore(errorSpan, emailField.nextSibling);
                return false;
            } else if (!emailReg.test(email)) {
                const emailField = document.getElementById('email');
                const errorSpan = document.createElement('span');
                errorSpan.className = 'error';
                errorSpan.textContent = ' Please enter a valid email address';
                emailField.parentNode.insertBefore(errorSpan, emailField.nextSibling);
                return false;
            }
            
            <?php
            if($config->turn_on_privacy){
            ?>
            // Validate privacy agreement
            const privacyAgreement = document.getElementById('privacy_agreement');
            if (privacyAgreement && privacyAgreement.checked === false) {
                const privacySpan = document.getElementById('privacy_agreement_span');
                if (privacySpan) {
                    const errorSpan = document.createElement('span');
                    errorSpan.className = 'error';
                    errorSpan.textContent = ' <?php echo Text::_('EDOCMAN_AGREE_PRIVACY_POLICY_ERROR');?>';
                    privacySpan.parentNode.insertBefore(errorSpan, privacySpan.nextSibling);
                }
                return false;
            }
            <?php } ?>
            
            return true;
        }
    });
})();
</script>
