<?php require('../../connection.php');
function calendarMonth($month,$year){
$number = cal_days_in_month(CAL_GREGORIAN, $month, $year); // 31
return $number;	
}

function ordinalSuffix($num) {
$suffixes = array("st", "nd", "rd");
$lastDigit = $num % 10;
if(($num < 20 && $num > 9) || $lastDigit == 0 || $lastDigit > 3) return "th";
return $suffixes[$lastDigit - 1];
}

if($_REQUEST['type']=="day"){
$s=strtotime($_REQUEST['date']." 00:00:00");
$e=strtotime($_REQUEST['date']."  23:59:59");
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `diary` WHERE `date_start` BETWEEN '$s' AND '$e'  ORDER BY abs(date_start) ASC")or die(mysqli_error());
$stmt->execute();$q=$stmt->get_result();$stmt->close();	
?>
<div class="alert alert-info mb-4"><p class="lead">Diary entries for: <?= $_REQUEST['date'];?></p></div>
<table class="table table-striped">
<thead><tr><th>Entry</th><th>Time</th></tr>
</thead>
<tbody>
<?php while($d=mysqli_fetch_array($q)){?>
<tr><td width="70%"><?= $d['title']?></td><td><?= date('H:i',$d['date_start'])?> - <?= date('H:i',$d['date_end'])?></td></tr>
<tr><td colspan="2"><?= $d['desc']?></td></tr>
<tr><td colspan="2"><hr /></td></tr>
<?php }?>
</tbody>
</table>
<div class="clearfix"></div>
<?php }

if($_REQUEST['type']=="month"){
$s=strtotime("01-".$_REQUEST['date']."-".$_REQUEST['year']." 00:00:00");
$mth=date('m',$s);
$lastday=calendarMonth($mth,$_REQUEST['year']);
$e=strtotime($lastday."-".$_REQUEST['date']."-".$_REQUEST['year']." 23:59:59");
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `diary` WHERE `date_start` BETWEEN '$s' AND '$e' ORDER BY abs(date_start)ASC")or die(mysqli_error());
$stmt->execute();$q=$stmt->get_result();$stmt->close();	
$num=mysqli_num_rows($q);

?>
<div class="alert alert-info mb-4"><p class="lead">Diary entries for: <?= $_REQUEST['date']." ".$_REQUEST['year']?></p></div>
<table class="table table-striped">
<thead><tr><th>Entry</th><th>Day</th><th>Time</th></tr>
</thead>
<tbody>
<?php while($d=mysqli_fetch_array($q)){?>
<tr><td width="70%"><?= $d['title']?></td><td><?= date('d',$d['date_start']).ordinalSuffix(date('d',$d['date_start']))?></td><td><?= date('H:i',$d['date_start'])?> - <?= date('H:i',$d['date_end'])?></td></tr>
<tr><td colspan="3"><?= $d['desc']?></td></tr>
<tr><td colspan="3" style="background:#cccccc"><hr /></td></tr>
<?php }?>
</tbody>
</table>
<div class="clearfix"></div>
<?php }?>