<!-- new crud.html for Foundry BS- 5-->
<body>
	<?php
	require "%relativeSiteAssetPath%/sc_assets/api.php";
	require '%relativeSiteAssetPath%/sc_assets/Database.php';
	require '%relativeSiteAssetPath%/sc_assets/Post.php';
    require '%relativeSiteAssetPath%/sc_assets/logging.php';

if (%id=logging%){
$_SESSION['logging'] = true;
}else{
	$_SESSION['logging'] = false;
}
$_SESSION['format'] = '%id=dformat%';
$_SESSION['separator'] = '%id=dseparate%';
$_SESSION['hours'] = %id=hours%;
$_SESSION['relcrudpath'] = dirname(__FILE__);
	?>
	<script src='%relativeSiteAssetPath%/sc_assets/flatpickr/flatpickr.js'></script>
%[if %(%id=picker% == 1)% ]%
	
		<script src='%relativeSiteAssetPath%/sc_assets/iro.js'></script>
%[endif]%

%%[[if publish]]%%
		%[if %(%id=picker% == 1)% ]%

		<!-- Modal for color picker -->
		<div class="modal-cp fade hide" id="colorpicker-modal">
		<div class="modal-cp-dialog">
			<div class="modal-cp-content">
			<div class="modal-cp-header">
				<h5 class="modal-cp-title">Select a color - Click Ok</h5>
			</div>
			<div class="modal-cp-body">
				<div id="colorpicker"></div>
			</div>
			<div class="modal-cp-footer">
				<button type="button" class="btn button danger tiny cp-btn-default" data-dismiss="modal" id="colorpicker-cancel">Cancel</button>
				<button type="button" class="btn button success tiny cp-btn-primary" id="colorpicker-submit">OK</button>
			</div>
			</div>
		</div>
		</div>
		%[endif]%
%%[[endif]]%%

<div class="well">

		<h3 class="text-primary">%id=idhead%</h3>
		<hr style="border-top:1px dotted #ccc;"/>
		<button type="button" class="button success" data-toggle="sc-modal" data-target="#form_sc-modal"><span class="glyphicon glyphicon-plus"></span> Add Event</button>
		<br /><br/ >
		<!-- <table class="table table-bordered"> -->
	<table class="table sc-table">
		<thead class="alert-info">
				<tr>
					<!-- <th>Id</th> -->
					<th>%id=idtitle%</th>
					%[if %id=crudshowallday%]%
					<th>%id=idallday%</th>
					%[endif]%
					<!-- <th>%id=idevurl%</th>-->
					%[if %id=crudshowstart%]%
					<th>%id=idstart%</th>
					%[endif]%
					%[if %id=crudshowend%]%
					 <th>%id=idend%</th>
					%[endif]% 
					 <!--
						<th>%id=iddetail%</th>
 					-->
					 %[if %id=crudshowvenue%]%
					 <th>%id=idvenue%</th>
					 %[endif]%
					 <!-- ADD FILTER HEADER HERE -->
					 <!--
						<th>%id=idadd%</th>
						<th>%id=idsocial%</th>
						<th>%id=idsponsors%</th>
						<th>%id=idtext%</th>
						<th>%id=idborder%</th>
						<th>%id=idback%</th>
					-->
					<th class='no-controls'></th>
				</tr>
			</thead>
			<tbody>
				%%[[if publish]]%%
				<?php
				// Instantiate DB & connect
               $database = new Database();
               $db = $database->connect();
					// Instantiate object
					$post = new Post($db);
					$result = $post ->read();
					while($fetch = $result->fetch()){
				?>
				<tr>
					<td><?php echo $fetch['title']?></td>
					%[if %id=crudshowallday%]%
						<td><?php echo $fetch['allDay']?></td>
							
					%[endif]%
					%[if %id=crudshowstart%]%
					 <?php
						if($fetch['allDay'] == 'True'){
							echo '<td>'.substr($fetch['ev_start'], 0, 10).'</td>'; 
						}else{
							echo '<td>'.$fetch['ev_start'].'</td>';
						}
					?>
					%[endif]%	
					
										
					%[if %id=crudshowend%]%
					<?php
						if($fetch['allDay'] == 'True'){
							echo '<td>'.substr($fetch['ev_end'], 0, 10).'</td>'; 
						}else{
							echo '<td>'.$fetch['ev_end'].'</td>';
						}
					?>
						
					%[endif]%
					%[if %id=crudshowvenue%]%
					<td><?php echo $fetch['venue']?></td>
					%[endif]%
					<!-- // add filter field here -->
				%%[[endif]]%%

			%%[[if !publish]]%%
				<td>The actual data</td>
				<td>can only be rendered</td>
				<td>on the published page. %id=dformat% %id=dseparate% %id=hours%</td>
			%%[[endif]]%%
		<td><button class="button edit" type="button" data-toggle="sc-modal" data-target="#update_event<?php echo $fetch['id']?>"><span class="glyphicon glyphicon-edit"></span> </button>
		<a href="%relativeSiteAssetPath%/sc_assets/delete.php?id=<?php echo $fetch['id']?>"><button class="button trash"><span class="glyphicon glyphicon-trash"></span> </a></button></td>
				</tr>
				<div class="sc-modal fade" id="update_event<?php echo $fetch['id']?>">
					<div class="sc-modal-dialog">
						<div class="sc-modal-content sc-modal-center">
							<form action="%relativeSiteAssetPath%/sc_assets/update_event.php" method="POST">
								<div class="sc-modal-header">
									<h3 class="sc-modal-title">Update Event</h3>
								</div>
								<div class="sc-modal-body">
										<div class="form-group">
											<label>%id=idtitle%</label>
											<input type="text" class="form-control" value="<?php echo $fetch['title']?>" name="title" size="50"/>
											<input type="hidden" class="form-control" value="<?php echo $fetch['id']?>" name="id" size="50" />
										</div>
										
										<div class="form-group">
											%[if %id=shoDetUrl%]%
											<label>%id=idevurl%</label>
											%[endif]%
											<input %[if %id=shoDetUrl%]%type="text"%[else]% type="hidden"%[endif]% class="form-control" value="<?php echo $fetch['event_url']?>" name="event_url" size="50"/>
										</div>
						<!-- all day edit -->
							%[if %id=shoallday%]%						
								<div class="form-group radio-group">
								<label>%id=idallday%</label>
								<label for="allday_true">
									<input type="radio" id="allday_true" name="allDay" value="True" <?php if ($fetch['allDay'] === 'True') echo 'checked'; ?>>
									True
								</label>
								<label for="allday_false">
									<input type="radio" id="allday_false" name="allDay" value="False" <?php if ($fetch['allDay'] === 'False') echo 'checked'; ?>>
									False
								</label>
								</div>
							%[endif]%
							<!-- end all day edit -->


									<div class="form-group">
											<label>%id=idstart%</label>
											<input type="text" class="form-control" id="start" value="<?php echo $fetch['ev_start']?>" name="ev_start" size="50"/>
										</div>
										<div class="form-group">
											<label>%id=idend%</label>
											<input type="text" class="form-control" id="end" value="<?php echo $fetch['ev_end']?>" name="ev_end" size="50"/>
										</div>
												
										<div class="form-group">
											%[if %id=shoDetails%]%
												<label for = "details">%id=iddetail%</label>
											%[endif]%	
												<textarea id ="details" %[if %id=shoDetails%]%type="text"%[else]% style="display:none"%[endif]% rows="8" cols="50" wrap="soft" class="form-control" name="details"/><?php echo strip_tags($fetch['details'])?></textarea>
											</div>
										<div class="form-group">
											%[if %id=shoVenue%]%
											<label>%id=idvenue%</label>
											%[endif]%
											<input %[if %id=shoVenue%]%type="text"%[else]% type="hidden"%[endif]% class="form-control" value="<?php echo $fetch['venue']?>" name="venue" size="50"/>
										</div>
										<div class="form-group">
											%[if %id=shoAddress%]%
												<label for = "add">%id=idadd%</label>
											%[endif]%	
												<textarea id ="add" %[if %id=shoAddress%]% type="text"%[else]% style="display:none"%[endif]% rows="3" cols="50" wrap="soft" class="form-control" name="venue_add"/><?php echo strip_tags($fetch['venue_add'])?></textarea>
											</div>
										<div class="form-group">
											%[if %id=shoSocialUrl%]%
											<label>%id=idsocial%</label>
											%[endif]%
											<input %[if %id=shoSocialUrl%]%type="text"%[else]% type="hidden"%[endif]% class="form-control" value="<?php echo $fetch['social_url']?>" name="social_url" size="50"/>
										</div>
										<div class="form-group">
											%[if %id=shoSponsors%]%
											<label>%id=idsponsors%</label>
											%[endif]%
											<input %[if %id=shoSponsors%]%type="text"%[else]% type="hidden"%[endif]% class="form-control" value="<?php echo strip_tags($fetch['sponsors'])?>" name="sponsors" size="50"/>
										</div>
										<div class="form-group">
											%[if %id=shoTxtCol%]%
											<label>%id=idtext%</label>
											%[endif]%
											<input id="txtpickerEdit" %[if %id=shoTxtCol%]%type="text"%[else]% type="hidden"%[endif]%  class="form-control colorpicker-field" value="<?php echo $fetch['textColor']?>" name="textColor" size="50"/>
										</div>
										<div class="form-group">
											%[if %id=shoBrdCol%]%
											<label>%id=idborder%</label>
											%[endif]%
											<input id="bordpickerEdit" %[if %id=shoBrdCol%]%type="text"%[else]% type="hidden"%[endif]% class="form-control colorpicker-field" value="<?php echo $fetch['borderColor']?>" name="borderColor" size="50"/>
										</div>
										<div class="form-group">
											%[if %id=shoBckCol%]%
											<label>%id=idback%</label>
											%[endif]%
											<input id="backpickerEdit" %[if %id=shoBckCol%]%type="text"%[else]% type="hidden"%[endif]%  class="form-control colorpicker-field" value="<?php echo $fetch['backgroundColor']?>" name="backgroundColor" size="50"/>
										</div>
								</div>
								<div style="clear:both;"></div>
								<div class="sc-modal-footer">
									<button class="button warning" name="update"><span class="glyphicon glyphicon-update"></span> Update</button>
									<button type="button" class="button danger" data-dismiss="sc-modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
								</div>
							</form>
							<?php writeFile(); // in api.php ?>
						</div>
					</div>
				</div>
			%%[[if publish]]%%
						<?php
							}
						?>
			%%[[endif]]%%
					</tbody>
		</table>				
	</div>
	
</div class="add-cnt">
	<div class="sc-modal fade" id="form_sc-modal" aria-hidden="true">
		<div class="sc-modal-dialog">
			<div class="sc-modal-content sc-modal-center">
				<form method="POST" action="%relativeSiteAssetPath%/sc_assets/save_event.php">
					<div class="sc-modal-header">
						<h3 class="sc-modal-title">Add Event</h3>
				
					<div class="sc-modal-body">
						
					
						<div class="form-group">
											<label>%id=idtitle%</label>
											<input type="text" class="form-control" name="title" size="50" placeholder="Your event title/name"required/>

											<input type="hidden" class="form-control" name="id" size="50"/>
										</div>
										<div class="form-group">
											%[if %id=shoDetUrl%]%
											<label>%id=idevurl%</label>
											%[endif]%
											<input %[if %id=shoDetUrl%]%type="text"%[else]% type="hidden"%[endif]% class="form-control" name="event_url" size="50" placeholder="Url to Details page on or off this site" value="%id=defurl%"/>
										</div>
									<!-- allday add -->
										%[if %id=shoallday%]%						
										<div class="form-group radio-group">
										<label>%id=idallday%</label>
										<label for="allday_true">
											<input type="radio" id="allday_true" name="allDay" value="True">
											True
										</label>
										<label for="allday_false">
											<input type="radio" id="allday_false" name="allDay" value="False" checked>
											False
										</label>
										</div>
										%[endif]%
									<!-- end allday add -->

										<div class="form-group">
											<label>%id=idstart%</label>
											<input type="text" class="form-control" id ="start" name="ev_start" size="50" placeholder="YYYY-MM-DD -or- DD/MM/YYYY -time- 00:00AM" required/>
										</div>
										<div class="form-group">
											<label>%id=idend%</label>
											<input type="text" class="form-control" id="end" name="ev_end" size="50" placeholder="YYYY-MM-DD -or- DD/MM/YYYY -time- 00:00AM" required/>
										</div>
										<div class="form-group">
											%[if %id=shoDetails%]%
											<label>%id=iddetail%</label>
											%[endif]%
											<textarea id ="details" %[if %id=shoDetails%]%type="text"%[else]% style="display:none"%[endif]% rows="8" cols="50" wrap="hard" class="form-control" name="details" placeholder="Details about your event"/></textarea>

										</div>
										<div class="form-group">
											%[if %id=shoVenue%]%
											<label>%id=idvenue%</label>
											%[endif]%
											<input %[if %id=shoVenue%]%type="text"%[else]% type="hidden"%[endif]% class="form-control" name="venue" size="50" placeholder="Where is the event?"/>
										</div>

										<div class="form-group">
											%[if %id=shoAddress%]%
												<label for = "add">%id=idadd%</label>
												%[endif]%
												<textarea id ="add" %[if %id=shoAddress%]%type="text"%[else]% style="display:none"%[endif]% rows="3" cols="50" wrap="hard" class="form-control" name="venue_add" placeholder="The address, phone no. etc."/></textarea>
											</div>

										<div class="form-group">
											%[if %id=shoSocialUrl%]%
											<label>%id=idsocial%</label>
											%[endif]%
											<input %[if %id=shoSocialUrl%]%type="text"%[else]% type="hidden"%[endif]% class="form-control" name="social_url" size="50"placeholder="A second url for more information"/>
										</div>
										<div class="form-group">
											%[if %id=shoSponsors%]%
											<label>%id=idsponsors%</label>
											%[endif]%
											<input %[if %id=shoSponsors%]%type="text"%[else]% type="hidden"%[endif]% class="form-control" name="sponsors" size="50" placeholder="Sponsor name(s) or url of logo image"/>
										</div>
											<div class="form-group">
												%[if %id=shoTxtCol%]%
											<label>%id=idtext%</label>
											%[endif]%
											<input id="txtpickerAdd" %[if %id=shoTxtCol%]%type="text"%[else]% type="hidden"%[endif]%  class="form-control colorpicker-field" name="textColor" size="50" placeholder="set the text color - black, red, blue etc."/>
										</div>
										<div class="form-group">
											%[if %id=shoBrdCol%]%
											<label>%id=idborder%</label>
											%[endif]%
											<input id="bordpickerAdd" %[if %id=shoBrdCol%]%type="text"%[else]% type="hidden"%[endif]% class="form-control colorpicker-field" name="borderColor" size="50" placeholder="set the border color - black, red, blue etc."/>
										</div>
										<div class="form-group">
											%[if %id=shoBckCol%]%
											<label>%id=idback%</label>
											%[endif]%
											<input id ="backpickerAdd" %[if %id=shoBckCol%]%type="text"%[else]% type="hidden"%[endif]% class="form-control colorpicker-field" name="backgroundColor" size="50" placeholder="set the background color - black, red, blue etc."/>
										</div>
								<div style="clear:both;"></div>
					<div class="sc-modal-footer">
						<button class="button small success" name="save">Save</button>
						<button type="button" class="button small danger" data-dismiss="sc-modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
					</div>
				</form>
				<?php writeFile(); //in api.php?>
			</div>
		</div>
	</div>
	


<script> 
	%[if %(%id=picker% == 1)% ]%
document.addEventListener('DOMContentLoaded', function() {
  // Initialize ColorPicker
  const colorPicker = new iro.ColorPicker('#colorpicker', {
    width: 200,
    color: '#ffffff',
    borderWidth: 1,
    borderColor: '#fff',
  });
	%[endif]%
  // Set date format
  var format = <?php echo "'".$_SESSION['format']."'"; ?>;
  var separate = <?php echo "'".$_SESSION['separator']."'"; ?>;
  
  var hours = <?php echo "'".$_SESSION['hours']."'"; ?>;
  let one = format.substr(0, 1);
  let two = format.substr(1,1);
  let three = format.substr(2,1); 
  let time;
  let use24;

  if (!(hours==1)) {
      time = 'h:i K';
      use24 = false;
  } else {
      time = 'H:i'
      use24 = true;
  }

  let finalFormat = one+separate+two+separate+three+' '+time;

  // Create an observer instance linked to the callback function
  var observer = new MutationObserver(function(mutationsList, observer) {
    for(let mutation of mutationsList) {
        if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
            console.log('class attribute was modified.');
            if (mutation.target.classList.contains('show')) {
                console.log('show class was added');
                let fpstart, fpend;

                const configStart = {
                    enableTime: true,
                    dateFormat: finalFormat,
                    time_24hr: use24,
                    onChange: function(selectedDates, dateStr, instance) {
                        if (fpend) {
                            fpend.destroy();
                        }

                        if (selectedDates.length > 0) {
                            const configEnd = {
                                enableTime: true,
                                dateFormat: finalFormat,
                                time_24hr: use24,
                                minDate: selectedDates[0],
                                defaultDate: selectedDates[0],
                            }

                            fpend = flatpickr("#end", configEnd);
                        }
                    },
                }

                fpstart = flatpickr("#start", configStart);
            } 
        }
    }
  });

  // Start observing the document with the configured parameters
  observer.observe(document.body, { attributes: true, subtree: true });

  // Close the color picker modal when the OK button is clicked
  const okButton = document.querySelector('#colorpicker-submit');
  okButton.addEventListener('click', function() {
    const colorPickerModal = document.querySelector('#colorpicker-modal');
    colorPickerModal.classList.remove('show');
  });

  // Close the color picker modal when the Cancel button is clicked
  const cancelButton = document.querySelector('#colorpicker-cancel');
  cancelButton.addEventListener('click', function() {
    const colorPickerModal = document.querySelector('#colorpicker-modal');
    colorPickerModal.classList.remove('show');
  });

  // Table sorting
  const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
  
  const comparer = (idx, asc) => (a, b) => ((v1, v2) => 
      v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
  )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));

  document.querySelectorAll('thead th').forEach(th => th.addEventListener('click', (() => {
      const table = th.closest('table');
      const tbody = table.querySelector('tbody');
      Array.from(tbody.querySelectorAll('tr'))
          .sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
          .forEach(tr => tbody.appendChild(tr) );
  })));
  %[if %(%id=picker% == 1)% ]%
});
%[endif]%
</script>





</body>
</html>