<?php
//  Mostrar, en gráfico de Daypilot, los recursos reservador y los tiempos en que están reservados en el rango de estudio.
//  Show, in Daypilot chart, the reserve resources and the times they are reserved in the study range.

$V_limitDateMin = $_SESSION['limitDateMin'];
$V_limitDateMax = $_SESSION['limitDateMax'];
$V_reservations_where = $_SESSION['reservations_where'];
$V_label_head_reservations = GetCustomLabel ("VIEW_RESERVATIONS");

$date_range_evaluations_min = $_SESSION['config'][array_search('DATE_RANGE_EVALUATIONS_MIN', array_column($_SESSION['config'], 'name'))][value];
$date_range_evaluations_max = $_SESSION['config'][array_search('DATE_RANGE_EVALUATIONS_MAX', array_column($_SESSION['config'], 'name'))][value];
$date = new DateTime(now());
$V_now = strtotime($date->format('d-m-Y H:i:s')."$date_range_evaluations_min days");
$V_now  = date("Y-m-d",$V_now)."T00:00:01";
$V_tot_day = $date_range_evaluations_max - $date_range_evaluations_min;

if ($_SESSION['language'] == 'Spanish') {
    $language = 'es-es'; // Spanish
    $range_row = 20;
    $formatDate = "dd/MM/yyyy HH:mm"; 
    $formatDatePHP = "d/m/Y H:i"; 
    $startTx = 'Inicio';
    $endTx = 'Fin';
    $userTx = 'Usuario';
} else {
    $language = 'en-us'; // English
    $range_row = 40;
    $formatDate = "MM/dd/yyyy HH:mm";  
    $formatDatePHP = "m/d/Y H:i"; 
    $startTx = 'Start';
    $endTx = 'End';
    $userTx = 'User';
}


$V_resources = '';
$V_event = '';
$strSQL = "
SELECT distinct
media.idmedia,
-- media.type_media_idtype_media,
media.code,
media.title,
media.description,
media.owner_id,
-- type_media.code,
-- type_media.title,
type_media.color
FROM media
INNER JOIN reservations ON media.idmedia = reservations.media_idmedia
INNER JOIN type_media ON media.type_media_idtype_media = type_media.idtype_media
where
reservations.startDate <= '$V_limitDateMax'
and reservations.endDate >= '$V_limitDateMin'
";
if ($V_reservations_where <> ''){ // Filter?
    $strSQL .= "and ".$V_reservations_where ;
}
$strSQL .= " order by media.code ";
$rsSQL = db_query($strSQL,$conn);
while ($data1 = db_fetch_array($rsSQL)) {
    $V_resources .= "{ \"name\" : \""."<b>".$data1['code']."</b>"." - ".$data1['title']."\", \"id\" : \"".$data1['code']."\"}, \n";
    $V_idmedia = $data1['idmedia'];
    $strSQL2 = "
SELECT
reservations.idreservations,
-- reservations.media_idmedia,
-- reservations.users_user_id,
reservations.startDate startDate,
reservations.endDate endDate,
users.user_id,
users.login,
users.username
FROM reservations
INNER JOIN users ON (reservations.users_user_id = users.user_id)
WHERE
reservations.media_idmedia = $V_idmedia
and reservations.startDate <= '$V_limitDateMax'
and reservations.endDate >= '$V_limitDateMin' ";
    $rsSQL2 = db_query($strSQL2,$conn);
    while ($data2 = db_fetch_array($rsSQL2)) {   
       $V_start = date($formatDatePHP,strtotime($data2['startDate']));
       $V_end = date($formatDatePHP,strtotime($data2['endDate']));
       $V_color = $data1['color'];
       $V_event .= "
{
      \"start\": \"".$data2['startDate']."\",
      \"end\": \"".$data2['endDate']."\",
      \"id\": \"".$data2['idreservations']."\",
      \"resource\": \"".$data1['code']."\",
      \"text\": \"".$data2['login']."\",
      \"user\": \"".$data2['login'].' - '.$data2['username']."\",          
      \"barColor\": \"$V_color\"
    },";
}
}
if (strlen($V_resources) <> 0) {
    $V_resources = substr($V_resources, 0, -1); // rest last comma
}
if (strlen($V_event) <> 0) {
    $V_event = substr($V_event, 0, -1); // rest last comma
}



// ---------------------------------------------- Template of javascript ---------------------------------
$html = <<<EOT

<!-- daypilot libraries -->
<script src="daypilot/js/daypilot-all.min.js?v=2019.4.4160" type="text/javascript"></script>

<div id="dp"></div>
<!-- color page -->
<style>
.scheduler_default_timeheadercol
{
    background: #f5e3b8;
}
.scheduler_default_rowheader,
.scheduler_default_corner
{
    background: #f5e3b8;
}
</style>
<script>
  var dp = new DayPilot.Scheduler("dp", {
    cellWidthSpec: "Fixed",
    cellWidth: $range_row,
    autoScroll: "Disabled",
    locale: "$language",
    timeHeaders: [{"groupBy":"Day"},{"groupBy":"Hour"}],
    scale: "Hour",
    startDate: "$V_now",
    days: $V_tot_day,
    // days: DayPilot.Date.today().daysInMonth(),
    // startDate: DayPilot.Date.today().firstDayOfMonth(),
    showNonBusiness: false,
    businessBeginsHour: 8,
    businessEndsHour: 21,
    eventHeight: 30,
    eventMovingStartEndEnabled: true,
    timeRangeSelectedHandling: "Disabled",
    eventMoveHandling: "Disabled",
    eventResizeHandling: "Disabled",
    eventDeleteHandling: "Disabled",
    eventClickHandling: "Enabled",
    eventHoverHandling: "Bubble",
    treeEnabled: false,
  });

// bubble, with async loading
dp.bubble = new DayPilot.Bubble({   
    onLoad: function(args) {
        var ev = args.source;
        args.async = true;  // notify manually using .loaded()
        // simulating slow server-side load
        setTimeout(function() {
            args.html = "<div style='font-weight:bold'>" + ev.resource() + "</div><div>$userTx: " + ev.text() + "</div><div>$startTx: " + ev.start().toString("$formatDate ") + "</div><div>$endTx: " + ev.end().toString("$formatDate ") + "</div><div>Id: " + ev.id() + "</div>";
            args.loaded();
        }, 50);
    }
}); 

dp.onEventClicked = function(args) {
  console.log('Select: '+args.e.text());
  var reservation = args.e.id();
  var url = "v_reservations_view.php?editid1="+reservation;
  var header = '<h2 data-itemtype="view_header" data-itemid="view_header" data-pageid="10">'+'$V_label_head_reservations '+'</h2>' ;
  window.popup = Runner.displayPopup({
            url: url,
            width: 800,
            height: 550,
            header: header
    });
  };    
        
   dp.resources = [$V_resources]; 

   dp.events.list = [$V_event];
  dp.init();
</script>
EOT;

echo $html;

?>