<?php
/* Copyright (C) 2013-2021	Charlene BENKE	<charlie@patas-monkey.com>
*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 *	\file	   	htdocs/myschedule/tabs/massdelete.php
 *	\ingroup		myschedule
 *	\brief	  	Page of fichinter myschedule
 */

$res=0;
if (! $res && file_exists("../../main.inc.php")) 
	$res=@include("../../main.inc.php");		// For root directory
if (! $res && file_exists("../../../main.inc.php")) 
	$res=@include("../../../main.inc.php");	// For "custom" directory

require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';

require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';

if ($conf->projet->enabled)
	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';

if ($conf->contrat->enabled)
	require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';

//require_once DOL_DOCUMENT_ROOT."/holiday/class/holiday.class.php";

dol_include_once('/myschedule/core/lib/myschedule.lib.php');
dol_include_once('/myschedule/class/myschedule.class.php');

$langs->load('companies');
$langs->load('interventions');
$langs->load('bills');
$langs->load('myschedule@myschedule');

$id 	= GETPOST('id', 'int');
$ref 	= GETPOST('ref', 'alpha');
$action	= GETPOST('action', 'alpha');

// si non renseigné on prend le paramétre par défaut TODO, à valider
$choiceperiod= GETPOST('choiceperiod')?GETPOST('choiceperiod', 'alpha'):'week';
$firstdayweek= GETPOST('firstdayweek')?strtotime( GETPOST('firstdayweek', 'alpha')):"";


$perioduser=GETPOST('perioduser', 'int');
if (!$perioduser && $user->admin == 0  && $user->rights->myschedule->alluser == 0)
	$perioduser=$user->id;

$periodsoc=GETPOST('periodsoc', 'int');
if ($periodsoc ==0 && ! empty($user->societe_id))
	$periodsoc = $user->societe_id;


$dolstatut=GETPOST('dolstatut')?GETPOST('dolstatut', 'int'):-1;

$filterbystatut = explode(",", GETPOST('filterbystatut',"text") !=""?GETPOST('filterbystatut', 'text'):"nouser,notmade,notplanned,made");

$periodyear=GETPOST('periodyear', 'int');
if (!$periodyear)
	$periodyear=date('Y');

$periodyearmonth=GETPOST('periodyearmonth', 'int');
if (!$periodyearmonth)
	$periodyearmonth=date('Y');

$periodmonth=GETPOST('periodmonth', 'int');
if (! $periodmonth )
	$periodmonth=date('m');

$periodweek=GETPOST('periodweek', 'int');
if (!$periodweek)
	$periodweek=date('W');

if ($choiceperiod == 'week') {
	if ($firstdayweek == "") 
		$firstdayweek = firstdayweek($periodweek, $periodyear);
	else
		$periodweek = date("W", $firstdayweek);

	$periodmonth=date('m', $firstdayweek);
	$lastdayweek = strtotime(date("Y-m-d", strtotime(date('d-m-Y', $firstdayweek)))." +6 day"); 

	$fullcalendarfirstday=date("Y-m-d", $firstdayweek);
	$fullcalendarlastday=date("Y-m-d", $lastdayweek);	
} 
if ($choiceperiod=='month') {
	$fullcalendarfirstday=date("Y-m-d", dol_mktime(0, 0, 0, $periodmonth, 1, $periodyearmonth));
	$fullcalendarlastday=date("Y-m-d", dol_mktime(0, 0, 0, $periodmonth, 30, $periodyearmonth));
} 

// Security check
if (! empty($user->societe_id))
	$socid=$user->societe_id;
$result = restrictedArea($user, 'ficheinter', $id, 'fichinter');


/*
 * View
 */
$arrayofcss = array
	( '/myschedule/js/main.min.css'
);

$arrayofjs = array
	( '/myschedule/js/main.min.js'
	, '/myschedule/js/moment.min.js'
	, '/myschedule/js/locales/fr.js'
);

llxHeader('', "", "", '', 0, 0, $arrayofjs, $arrayofcss, '');


$form = new Form($db);
$formother = new Formother($db);
if ($conf->projet->enabled)
	$projet_static = new Project($db);
if ($conf->contrat->enabled)
	$contrat_static = new Contrat($db);

$now=dol_now();

/*
 * Show object in view mode
 */
$title=$langs->trans("mySchedule")." - ".$langs->trans("MassShift");

print load_fiche_titre($title, "", 'myschedule@myschedule');

print '<form method="POST" name=massaction id=massaction action="massclonelist.php">';

print '<table class="noborder " >';
print '<tr><td valign=bottom width=25%>';
// ici la période actuelle
if( $choiceperiod == "week") {
	print "<h2>".$langs->trans("Week")." : ".$periodweek ." - ". $periodyear."</h2>";
} else {
	print "<h2>".$langs->trans("Month")." : ".$periodmonth ." / ". $periodyearmonth."</h2>";
}
print '<br>';
print $langs->trans("DropPeriodClone");
print '</td><td valign=bottom align=left>';
if( $choiceperiod == "week") {
	print $formother->selectyear($periodyear, 'periodyear');
	print select_week($periodweek, 'periodweek');
	print "<input type=hidden name='periodyear_old' id='periodyear_old' value='".$periodyear."'>";
	print "<input type=hidden name='periodweek_old' id='periodweek_old' value='".$periodweek."'>";
} else {
	print $formother->selectyear($periodyearmonth, 'periodyearmonth');
	print $formother->select_month($periodmonth, 'periodmonth', 0, 1, "");

	print "<input type=hidden name='periodyearmonth_old' id='periodyearmonth_old' value='".$periodyearmonth."'>";
	print "<input type=hidden name='periodmonth_old' id='periodmonth_old' value='".$periodmonth."'>";

}
// on mémorise l'ancienne période sélectionné
print "<input type=hidden name='choiceperiod' id='choiceperiod' value='".$choiceperiod."'>";

// on mémorise la liste des ligne d'inter sélectionné
print "<input type=hidden name='listinterdetid' id='listinterdetid'>";
print '</td><td align=right>';
print '<input type="button" class="butAction"  id="cloneElement" value="'.$langs->trans("CloneElement").'">';
print '<br><br>';
print '<input type="button" class="butActionDelete" id="cancel" value="'.$langs->trans("Cancel").'">';
print '</td></tr>';
print "</table>";


if( $choiceperiod == "month") {
	print $langs->trans("InfoForSelectAllDay");
	print "<br>";
	print $langs->trans("InfoForSelectAllMonth");
} else
	print $langs->trans("InfoForSelectAllDay");

print "<div id='calendar' ></div>";

print '</form>';
//print '<br>';
print "<script>";

print "document.addEventListener('DOMContentLoaded', function() {"."\n";
print "var calendarEl = document.getElementById('calendar');"."\n";
print "var calendar = new FullCalendar.Calendar(calendarEl, {"."\n";

print "locale: 'fr',\n";
if ($choiceperiod == 'week')
	print "dayHeaderFormat: {weekday: 'long', day: '2-digit', month : '2-digit'},\n";
else
	print "dayHeaderFormat: {weekday: 'long'},\n";
print "timeZone: 'UTC',\n";
print "editable: false,\n";
print "themeSystem: 'standard',\n";
print "droppable: false,\n";
print "fixedWeekCount: false,\n";

$startHourDay=convertSecondToTime($conf->global->MYSCHEDULE_startHourDay?$conf->global->MYSCHEDULE_startHourDay:2*3600, "allhourmin", 86400);
$endHourDay=convertSecondToTime($conf->global->MYSCHEDULE_endHourDay?$conf->global->MYSCHEDULE_endHourDay:23*3600, "allhourmin", 86400);
$startHourWork=convertSecondToTime($conf->global->MYSCHEDULE_startHourWork?$conf->global->MYSCHEDULE_startHourWork:9*3600, "allhourmin", 86400);
$endHourWork=convertSecondToTime($conf->global->MYSCHEDULE_endHourWork?$conf->global->MYSCHEDULE_endHourWork:20*3600, "allhourmin", 86400);
print "slotMinTime: '".$startHourDay."',\n";
print "scrollTime: '".$startHourWork."',\n";
print "slotMaxTime: '".$endHourDay."',\n";
print "businessHours: {\n";
print "	daysOfWeek: [ 1, 2, 3, 4, 5 ],\n"; // Monday - Thursday
print "startTime: '".$startHourWork."',\n"; // a start time (10am in this example)
print "endTime: '".$endHourWork."',\n"; // an end time (6pm in this example)
print "},\n";


print "headerToolbar: {\n";
print "start: '',\n";
print "end: ''\n";
print "  },\n";


// ouverture du popup de création
print "initialDate: '".$fullcalendarfirstday."',\n";
// selection du mode d'affichage de full calendar
switch($choiceperiod) {
	case "week":
		print "initialView: 'timeGridWeek',\n";
		print "allDaySlot: false,\n";
		break;
	case "month":
		print "initialView: 'dayGridMonth',"."\n";
		print "weekNumbers: true,\n";
		break;
}

// on charge la selection en masse 
include 'navlinks.inc.php'; // Must be include, not include_once

include 'events-load.inc.php'; // Must be include, not include_once

print "visibleRange: {\n";
print "    start: '".$fullcalendarfirstday."',\n";
print "    end: '".$fullcalendarlastday."'\n";
print "  },\n";
print "});"."\n";

print "calendar.render();"."\n";
// pour avoir l'agenda en blanc
print '$(".fc-daygrid").css("background", "white");';
print '$(".fc-timegrid").css("background", "white");';


// crée l'action sur le bouton et ajouter
print "$('#cloneElement').click( function() {\n"; 	// lancement de la suppression des évents
print "calendar.getEvents().forEach(function(item){\n";
// si l'évent a été sélectionné
print "    if (item.extendedProps.selected) \n";
//      on ajoute l'id de l'élément à la imputtext
print "        $('#listinterdetid').val($('#listinterdetid').val() + item.id+',');\n";
print "});\n";
// on submit la page et on passe à la suite 
print "$('#massaction').submit();\n";
print "});\n";


// on doit soumettre le formulaire pour récupérer les éléments sélectionnés
print "});"."\n";

// le cancel n'a pas besoin d'etre dans la déclaration du calendar
print "$('#cancel').click( function() {\n";
	print "window.open('".dol_buildpath("/myschedule/fichinter/", 1);
	print "fullcalendar.php?choiceperiod=".$choiceperiod;
	print "&periodyear=".$periodyear;
	print "&periodweek=".$periodweek;
	print "&periodmonth=".$periodmonth;
	print $urlPeriodFilter."', '_self');\n";
print "})\n";

print "</script>";

print '</div>'."\n";

// End of page
llxFooter();
$db->close();
