<?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">
	<div class="modal-header">
		<?php
		if($config->twitter_bootstrap_version == 2){	
		?>
		<?php } ?>
		<h2><?php echo Text::_('EDOCMAN_DOWNLOAD_DOCUMENT'); ?></h2>
	</div>
	<div class="alert alert-success" id="downloadsuccess">
		<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 $title =  Text::_('EDOCMAN_COMPLETE_FORM_TO_DOWNLOAD'); 
				$title = str_replace("[DOCUMENT_TITLE]", $item->title, $title);
				echo $title;
				?></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'); ?>">
	</div>
</div>

<script id="dynamic" type="text/javascript">
	if (typeof(Edocman) === 'undefined') {
    var Edocman = {};
}

// No need for jQuery.noConflict() in vanilla JS

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';
    }
    
    // Button click handler
    const sendButtons = document.querySelectorAll('.btn-send');
    sendButtons.forEach(function(button) {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const validate = validateForm();
            if (validate) {
                // Disable all send buttons
                const allSendButtons = document.querySelectorAll('.btn-send');
                allSendButtons.forEach(function(btn) {
                    btn.setAttribute('disabled', 'disabled');
                });
                
                // Add loading indicator before the button
                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);
                
                // Prepare data for submission
                const formData = new FormData();
                formData.append('task', 'document.store_download');
                formData.append('document_id', <?php echo $item->id; ?>);
                formData.append('name', document.getElementById('edocman-name').value);
                formData.append('email', document.getElementById('email').value);
                
                // Send AJAX request using Fetch API
                fetch('<?php echo Uri::root(true);?>/index.php?option=com_edocman&tmpl=component&format=raw&task=document.store_download', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.text();
                })
                .then(htmltext => {
                    // Hide download form
                    const modalBodyDownload = document.querySelector('.modal-body-download');
                    if (modalBodyDownload) {
                        modalBodyDownload.style.display = 'none';
                    }
                    
                    // Remove loading indicators
                    const waitElements = document.querySelectorAll('.wait');
                    waitElements.forEach(function(element) {
                        element.remove();
                    });
                    
                    // Show success message
                    if (downloadSuccess) {
                        downloadSuccess.style.display = 'block';
                    }
                    
                    // Update message content
                    const downloadCompleteMessage = document.querySelector('.download-complete-message');
                    if (downloadCompleteMessage) {
                        downloadCompleteMessage.innerHTML = htmltext;
                    }
                })
                .catch(error => {
                    alert(error.message);
                });
            }
        });
    });
    
    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
        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.innerHTML = ' 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.innerHTML = ' 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.innerHTML = ' Please enter a valid email address';
            emailField.parentNode.insertBefore(errorSpan, emailField.nextSibling);
            return false;
        }
        
        <?php
        if($config->turn_on_privacy){
        ?>
        // Validate privacy agreement
        if (document.getElementById('privacy_agreement').checked === false) {
            const privacySpan = document.getElementById('privacy_agreement_span');
            const errorSpan = document.createElement('span');
            errorSpan.className = 'error';
            errorSpan.innerHTML = ' <?php echo Text::_('EDOCMAN_AGREE_PRIVACY_POLICY_ERROR');?>';
            privacySpan.parentNode.insertBefore(errorSpan, privacySpan.nextSibling);
            return false;
        }
        <?php } ?>
        
        return true;
    }
});

</script>
