<?php

$kanban_path = $_SESSION['Config']['KANBAN_PATH']; // Param of table Config
$kanban_icon = $_SESSION['Config']['KANBAN_ICON'];
$kanban_ajax = $_SESSION['Config']['KANBAN_AJAX']; 


$language = $_SESSION['language'];
$kanban_option  = $_SESSION['kanban_option'];

//  Load lanes 
$data_lane=[];
$rs = DB::Query("SELECT `idlanes`, `name`, `color`, `orden`, `is_end` FROM lanes ORDER BY `orden`"); 
while( $data = $rs->fetchAssoc() ) // Read all record
	{
		$data_lane[] = $data;
	}

// load Task
If ($kanban_option == 'project') {
    $where = "t.`projects_project_id` =".$_SESSION['project_id'];
} else {
    $where = "t.`owner` = ".$_SESSION['user_id'];
}
$data_task = [];
$sql="
SELECT
t.`task_id`,
p.`short_name`,
t.`name`,
t.`start_date`,
t.`duration`,
catalog_code,
t.`status`,
t.`situation`,
u.`login`
FROM tasks t
join projects p on (t.`projects_project_id` = p.`project_id`)
join ( SELECT c.catalog_num, c.catalog_code FROM `catalog` AS c INNER JOIN super_catalog AS s ON c.super_catalog_idsuper_catalog = s.idsuper_catalog
       where super_code = 'DURATION_TYPE' AND LANGUAGE = '$language' ) d on (t.`duration_type` = d.catalog_num)
join users u on (t.`owner` = u.`user_id`)
where $where and t.access = 0
order by t.`status`, t.`start_date`, t.`task_id`  ";

$rs = DB::Query($sql); 
while( $data = $rs->fetchAssoc() )  // Read all record
	{
		$data_task[] = $data;
	}

$style_lane = '';
foreach ($data_lane as $lane) {
// .success {background: #00b961;}
    $style_lane .= ".".$lane['name']."{ background:".$lane['color']."}";
}
$display = "
    <link rel=\"stylesheet\" href=\"$kanban_path/jkanban.css\" />


    <style>

      #myKanban {
        overflow-x: auto;
        padding: 5px 0; /* 10px */
      }
			.kanban-title-board {
			  color: white;
			}
";
$display .= $style_lane;
$display .=
"  </style>
  </head>
  <body>
    <div id=\"myKanban\"></div>

    <script src=\"$kanban_path/jkanban.js\"></script>

    <script>
    var HttpClient = function() {
        this.get = function(aUrl, aCallback) {
            var anHttpRequest = new XMLHttpRequest();
            anHttpRequest.onreadystatechange = function() { 
                if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                    aCallback(anHttpRequest.responseText);
            }

            anHttpRequest.open( \"GET\", aUrl, true );            
            anHttpRequest.send( null );
        }
    }
      // -----------------------------------------------------------------------------------------------------
      var site ='$kanban_ajax?'; // Para informar del cambio de Lane
      var lane = ''; // Variable para saber la Lane que recibe el objeto
      var task = ''; // Variable para saber la tarea que se cambia
      
      // -----------------------------------------------------------------------------------------------------
        function onShowNotification () {
            // console.log('notification is shown!');
        }

        function onCloseNotification () {
            // console.log('notification is closed!');
        }

        function onClickNotification () {
            // console.log('notification was clicked!');
        }

        function onErrorNotification () {
            console.error('Error showing notification. You may need to request permission.');
        }

        function onPermissionGranted () {
            console.log('Permission has been granted by the user');
            doNotification();
        }

        function onPermissionDenied () {
            console.warn('Permission has been denied by the user');
        }

        function doNotification (response='') {
        }

      // -----------------------------------------------------------------------------------------------------
      var KanbanTest = new jKanban({
        element: \"#myKanban\",
        gutter: \"10px\",
        widthBoard: \"350px\",
        itemHandleOptions:{
          enabled: true,
        },
        click: function(el) {
          console.log(\"Trigger on all items click!\");
          console.log(el);
        },
        dropEl: function(el, target, source, sibling){
          console.log('dropEL');
          console.log(target.parentElement.getAttribute('data-id'));
          lane = target.parentElement.getAttribute('data-id');
          console.log(el, target, source, sibling)
        },
        buttonClick: function(el, boardId) {
          console.log('buttonClick');
          console.log(el);
          console.log(boardId);
          // create a form to enter element
					var url = \"kanban_add.php?boardId=\"+boardId;
					var header = 'Add Task ';
					window.popup = Runner.displayPopup({url : url,
						width: 900,
						height: 550,
						header: header
					});          
        },
        addItemButton: false,
        boards: [";

for ($i = 0; $i < count($data_lane); $i++) {
    $lane = $data_lane[$i];
    $lane_pos = $data_lane[$i+1];
    $lane_min = $data_lane[$i-1];
    $display .= "{ id: \"".$lane['name']."\", title: \"".$lane['name']."\", class: \"".$lane['name']."\",  item: [ \n  ";
    $display_task = 0;
    for ($k = 0; $k < count($data_task); $k++) {
        $task = $data_task[$k];
        $task['name']= addslashes($task['name']); // save " in Name
        if ($task['status'] === $lane['idlanes']) {
            $display_task = 1;
						// Situation = semaphore
						 $img_situation = '';
						 switch ($task['situation']) {
						// <img src=\\\"$kanban_icon/red.png\\\"> <img src=\\\"$kanban_icon/lock.png\\\">
							case 0:
									$img_situation = " <img src=\\\"$kanban_icon/green.png\\\">";
									break;
							case 1:
									$img_situation = " <img src=\\\"$kanban_icon/orange.png\\\">";
									break;
							case 2:
									$img_situation = " <img src=\\\"$kanban_icon/red.png\\\">";
									break;
							case 3:
									$img_situation = "  <img src=\\\"$kanban_icon/red.png\\\"> <img src=\\\"$kanban_icon/lock.png\\\">";
									break;
							}

            $display .= "{ id: \"".$task['task_id']."\", title: \"".
            "<img src=\\\"$kanban_icon/id.png\\\">".$task['task_id']."<img src=\\\"$kanban_icon/title.png\\\">".$task['name'].
            "<BR><img src=\\\"$kanban_icon/project.png\\\">".$task['short_name']."<img src=\\\"$kanban_icon/date.png\\\">".substr($task['start_date'], 0, -8).", ".$task['duration']." ".$task['catalog_code'].
            "<BR><img src=\\\"$kanban_icon/user.png\\\">".$task['login'].$img_situation."\",\n";
            $display .= "
								 click: function(el) {
										task = el.dataset.eid;
										var url = \"kanban_view.php?editid1=\"+task;
										var header = '<B> Task: '+ task +'</B>';

										window.popup = Runner.displayPopup({url : url,
																		width: 900,
																		height: 550,
																		header: header
										});
                },
                drag: function(el, source) {
                      console.log(\"START DRAG: \" + el.dataset.eid);
                },
                dragend: function(el) {
                      task = el.dataset.eid;
                      console.log(\"END DRAG: \" + task);                
                      console.log(lane);
                     // Solicitud de actuaización de cambio de tarea  
                      var client = new HttpClient();
                      client.get(site+'id='+task+'&lane='+lane, function(response) {
                       console.log('Respuesta: '+response);
                        doNotification(response);
                      });    
                },
                drop: function(el) {
                     console.log(\"DROPPED: \" + el.dataset.eid);
                }";
            $display .= "\n },";
        }
    }
    if ($display_task === 1 ){ 
				$display_task = 0;
				$display = substr($display, 0, -1); // Quitar la última ","                
     }
    $display .= " ] }\n ,";
}

$display = substr($display, 0, -1); // Quitar la última "," 
$display .= " ]} ); </script>";

echo $display;
//$value = $display;
?>