<?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;
use Joomla\CMS\Factory;

EDocmanHelper::loadBootstrapJs();
$controlGroupClass = $bootstrapHelper->getClassMapping('control-group');
$controlLabelClass = $bootstrapHelper->getClassMapping('control-label');
$controlsClass     = $bootstrapHelper->getClassMapping('controls');
$config			   = EdocmanHelper::getConfig();
?>
<div id="sharing-form">
	<div class="modal-header">
		<h2><?php echo Text::_('EDOCMAN_SHARING_DOCUMENT'); ?></h2>
	</div>
	<div class="alert alert-success">
		<p id="sharing-complete-message"></p>
	</div>
	<div class="modal-body">
		<form class="edocman-download-form form form-horizontal" name="download-form" id="download-form">
			<p class="text-info" id="sharing-instruction"><?php $title = Text::_('EDOCMAN_COMPLETE_FORM_TO_SHARE'); 
			$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_YOUR_NAME') ?><span class="required">*</span>
				</label>
				<div class="<?php echo $controlsClass; ?>">
					<input type="text" name="name" id="name" class="input-large form-control"/>
				</div>
			</div>
			<div class="<?php echo $controlGroupClass;  ?>">
				<label class="<?php echo $controlLabelClass; ?>" for="name">
					<?php echo  Text::_('EDOCMAN_YOUR_FRIEND_NAME') ?><span class="required">*</span>
				</label>
				<div class="<?php echo $controlsClass; ?>">
					<input type="text" name="friend_name" id="friend_name" class="input-large form-control"/>
				</div>
			</div>
			<div class="<?php echo $controlGroupClass;  ?>">
				<label class="<?php echo $controlLabelClass; ?>" for="name">
					<?php echo  Text::_('EDOCMAN_YOUR_FRIEND_EMAIL') ?><span class="required">*</span>
				</label>
				<div class="<?php echo $controlsClass; ?>">
					<input id="friend_email" type="text" name="friend_email" value="" class="input-large form-control"><br>
				</div>
			</div>
			<div class="<?php echo $controlGroupClass;  ?>">
				<label class="<?php echo $controlLabelClass; ?>" for="name">
					<?php echo  Text::_('EDOCMAN_MESSAGE') ?>
				</label>
				<div class="<?php echo $controlsClass; ?>">
					<textarea class="form-control" name="message" id="message" cols="50" rows="5" style="width:100% !important;"></textarea>
				</div>
			</div>
		</form>
	</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 = {};
		}

		// Wait for the DOM to be fully loaded
		document.addEventListener('DOMContentLoaded', function() {
			// Hide elements
			const progressElements = document.querySelectorAll('.progress');
			progressElements.forEach(function(element) {
				element.style.display = 'none';
			});
			
			const alertSuccessElements = document.querySelectorAll('.alert-success');
			alertSuccessElements.forEach(function(element) {
				element.style.display = 'none';
			});
			
			// Add click event listener to send button
			const sendButtons = document.querySelectorAll('.btn-send');
			sendButtons.forEach(function(button) {
				button.addEventListener('click', function(e) {
					e.preventDefault();
					const validate = validateForm();
					if (validate) {
						// Disable the button
						sendButtons.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="" />';
						button.parentNode.insertBefore(waitSpan, button);
						
						// Prepare data for AJAX request
						const data = new FormData();
						data.append('task', 'document.share_document');
						data.append('document_id', <?php echo $item->id; ?>);
						data.append('Itemid', <?php echo Factory::getApplication()->getInput()->getInt('Itemid'); ?>);
						data.append('name', document.getElementById('name').value);
						data.append('friend_name', document.getElementById('friend_name').value);
						data.append('friend_email', document.getElementById('friend_email').value);
						data.append('message', document.getElementById('message').value);
						
						// Send AJAX request
						fetch('<?php echo Uri::root(true);?>/index.php?option=com_edocman', {
							method: 'POST',
							body: data
						})
						.then(function(response) {
							if (!response.ok) {
								throw new Error('Network response was not ok');
							}
							return response.text();
						})
						.then(function(html) {
							// Hide modal body
							const modalBodyElements = document.querySelectorAll('.modal-body');
							modalBodyElements.forEach(function(element) {
								element.style.display = 'none';
							});
							
							// Set completion message
							document.getElementById('sharing-complete-message').innerHTML = html;
							
							// Remove loading indicator
							const waitElements = document.querySelectorAll('.wait');
							waitElements.forEach(function(element) {
								element.remove();
							});
							
							// Show success alert
							const alertSuccessElements = document.querySelectorAll('.alert-success');
							alertSuccessElements.forEach(function(element) {
								element.style.display = 'block';
							});
						})
						.catch(function(error) {
							alert(error.message);
						});
					}
				});
			});
			
			function validateForm() {
				const emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
				const names = document.getElementById('name').value;
				const friend_names = document.getElementById('friend_name').value;
				const friend_email = document.getElementById('friend_email').value;
				const inputVal = [names, friend_names, friend_email];
				
				const inputMessage = ["name", "friend 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 errorSpan = document.createElement('span');
					errorSpan.className = 'error';
					errorSpan.textContent = ' Please enter your ' + inputMessage[0];
					document.getElementById('name').insertAdjacentElement('afterend', errorSpan);
					return false;
				}
				
				// Validate friend name
				if (inputVal[1] === "") {
					const errorSpan = document.createElement('span');
					errorSpan.className = 'error';
					errorSpan.textContent = ' Please enter your ' + inputMessage[1];
					document.getElementById('friend_name').insertAdjacentElement('afterend', errorSpan);
					return false;
				}
				
				// Validate email
				if (inputVal[2] === "") {
					const errorSpan = document.createElement('span');
					errorSpan.className = 'error';
					errorSpan.textContent = ' Please enter your ' + inputMessage[2];
					document.getElementById('friend_email').insertAdjacentElement('afterend', errorSpan);
					return false;
				} else if (!emailReg.test(friend_email)) {
					const errorSpan = document.createElement('span');
					errorSpan.className = 'error';
					errorSpan.textContent = ' Please enter a valid email address';
					document.getElementById('friend_email').insertAdjacentElement('afterend', errorSpan);
					return false;
				}
				
				return true;
			}
		});

</script>
