<?php

session_start();
if($_GET['kalenteri']) {
	$_SESSION['kalenteri'] = (int) $_GET['kalenteri'];
} else {
	$_SESSION['kalenteri'] = 1;
}
require 'config.php';

    function getKalenterit($dbh)
    {
    	$kalenterit = $dbh->prepare("SELECT * FROM kalenterit");
    	$kalenterit->execute();
    	return $kalenterit->fetchAll();
    }

    function getKaikkiAjat($dbh, $paiva)
    {
        $kaikkiajat = $dbh->prepare("SELECT id, tunti, paiva FROM paivakalenteri WHERE paiva = :paiva AND (REPLACE (tunti, ':', '') >= ".BUSINESS_HOUR_START_FIX."00 AND REPLACE (tunti, ':', '') <= ".BUSINESS_HOUR_END_FIX."00)");
        $kaikkiajat->bindParam(':paiva', $paiva);
        $kaikkiajat->execute();
        return $kaikkiajat->fetchAll();
    }

    function getTunti($dbh, $id)
    {
        $tuntidata = $dbh->prepare("SELECT * FROM paivakalenteri_varaukset WHERE paivakalenteri_id = :id AND kalenteri = :kalenteri");
        $tuntidata->bindParam(':id', $id);
        $tuntidata->bindParam(':kalenteri', $_SESSION['kalenteri']);
        $tuntidata->execute();
        return $tuntidata->fetch();
    }

    function getToimipiste($dbh, $id)
    {
        $toimipiste = $dbh->prepare("SELECT * FROM toimipisteet WHERE id = :id");
        $toimipiste->bindParam(':id', $id);
        $toimipiste->execute();
        $t = $toimipiste->fetch();
        return $t['nimi'];
    }

    define("WEEK", date("W")+1);
    //define("YEAR", date("Y"));
    define("YEAR", '2019');
    define("WEEKSINYEAR", date("W", mktime(00, 00, 00, 12, 28, YEAR)));
	
	 $dayNum = date("N", strtotime('+6 hours'));
	 $current = strtotime('next monday');
	 if($dayNum == 6 OR $dayNum == 7) {
		$current = strtotime("+7 days", $current);
	 }
	 
	
	
    if (isset($_GET['week'])):
        if (preg_match("/^[0-9]{4}W[0-9]{2}$/", $_GET['week'])):
            $current = strtotime($_GET['week']);
        endif;
    endif;
    if (isset($_GET['weeks']) && isset($_GET['years'])):
        $current = strtotime("{$_GET['years']}W" . (($_GET['weeks'] < 10) ? "0" : "") . $_GET['weeks']);
    endif;
    
    $paivat = array();
    $paivat[] = date('Y-m-d',$current);
    $paivat[] = date('Y-m-d',strtotime("+1 days", $current));
    $paivat[] = date('Y-m-d',strtotime("+2 days", $current));
    $paivat[] = date('Y-m-d',strtotime("+3 days", $current));
    $paivat[] = date('Y-m-d',strtotime("+4 days", $current));

    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="Mika Saarinen">
        <link rel="shortcut icon" href="ico/favicon.png">

        <title>PMO</title>

        <!-- Bootstrap core CSS -->
        <link href="/css/bootstrap.css" rel="stylesheet">

        <!-- Custom styles for this template -->
        <link href="/css/jumbotron.css" rel="stylesheet">

        <style>
            .popover {
                width: 400px !important;
                max-width: 400px;
            }
        </style>

        <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
        <![endif]-->
    </head>
    <body>
    <div class="navbar navbar-inverse" role="navigation" style="background: transparent; border: 0px; border-color: transparent; margin-bottom: 0px;">
        <div class="container">
            <div class="navbar-header">

                <img src="/images/pmo.png" />

            </div>

            <!--/.navbar-collapse -->
        </div>
    </div>
    <div class="container">
	<?php //print_r($_SESSION); ?>

    <div class="row">
        <div class="col-md-12">
		
		
			<h2 style="text-align:center;margin-top: 0px;" class="hidden-xs">Varauskalenteri
                <?php if (isset($_GET['week'])): ?>
                    <span style="font-size: 20px;">Viikko <?php echo substr($_GET['week'], 5, 2); ?>
                        / <?php echo substr($_GET['week'], 0, 4); ?></span>
                <?php else: ?>
                    <span style="font-size: 20px;">
						Viikko <?php echo date("W - Y", strtotime($paivat[0])); ?></span>
                <?php endif; ?>
            </h2>
            <h2 style="text-align:center;" class="visible-xs">Varauskalenteri<br />
                <?php if (isset($_GET['week'])): ?>
                    <span style="font-size: 20px;">Viikko <?php echo substr($_GET['week'], 5, 2); ?>
                        / <?php echo substr($_GET['week'], 0, 4); ?></span>
                <?php else: ?>
                    <span style="font-size: 20px;">
						Viikko <?php echo date("W - Y", strtotime($paivat[0])); ?></span>
                <?php endif; ?>
            </h2>
        </div>
    </div>
    <div class="row">
        <div class="col-md-2 alert alert-info">
			<h3 style="margin-top: 2px;">Kalenteri</h3>

			<form method="get">
				<input type="hidden" name="korjaus" value="1"/>
				
				<p>
					<select name="kalenteri" class="form-control" style="margin-bottom: 4px;">
                    <?php foreach(getKalenterit($dbh) as $calendar) { ?>
                        <option value="<?php echo $calendar['id'] ?>" <?php if($calendar['id'] == $_SESSION['kalenteri']) echo 'selected="selected"'; ?>><?php echo $calendar['name'] ?></option>
					<?php } ?>
					</select>
					
					<select name="week" class="form-control">
						<?php for ($w = WEEK; $w <= WEEKSINYEAR; $w++): ?>
							<option value="<?php echo YEAR . "W";
							if ($w < 10) echo "0";
							echo $w; ?>" <?php if(isset($_GET['week'])&&$_GET['week']==YEAR  . "W" . (($w<10)?"0{$w}":$w))echo 'selected="selected"';?>>Viikko <?php echo $w . " / " . YEAR; ?></option>
						<?php endfor; ?>
						<?php if (WEEK > 45): ?>
							<?php for ($w = 1; $w < 20; $w++): ?>
								<option value="<?php echo (YEAR + 1) . "W";
								if ($w < 10) echo "0";
								echo $w; ?>" <?php if(isset($_GET['week'])&&$_GET['week']==(YEAR+1) . "W" . (($w<10)?"0{$w}":$w))echo 'selected="selected"';?>>Viikko <?php echo $w . " / " . (YEAR + 1); ?></option>
							<?php endfor; ?>
						<?php endif; ?>
					</select>
				</p>
				<button class="btn btn-primary btn-block">Tarkastele</button>
				
			</form>
			
			<h3>Ajanvaraus</h3>
			<input class="btn btn-danger btn-block" TYPE="button" onClick="history.go(0)" VALUE="Nollaa valinnat">
			<button class="btn btn-warning btn-block" style="margin-bottom: 4px;" id="varaa">Varaa valitut ajat</button><strong>Valitut ajat:</strong>
			<div id="booking_times">
			Ei valintoja.
			</div>
			<hr />
			<button type="button" class="btn btn-block btn-info" id="varausten_tiedot" data-toggle="collapse" data-target=".varaukset">
                        Näytä varausten tiedot
            </button> 
		</div>
        <?php foreach ($paivat as $paiva): ?>
            <div class="col-md-2" style="padding-left: 2px; padding-right: 0px;">
                <div class=" panel panel-primary">
                    <div class="panel-heading" style="padding: 1px 15px;">
                        <h2 style="font-size: 26px; line-height:normal;margin-top: 12px;">
                            <?php 
                                $paiva_numero = date("N", strtotime($paiva));  

                                switch($paiva_numero):
                                    case 1:
                                        echo 'Maanantai';
                                    break;
                                    case 2:
                                        echo 'Tiistai';
                                    break;
                                    case 3:
                                        echo 'Keskiviikko';
                                    break;
                                    case 4:
                                        echo 'Torstai';
                                    break;
                                    case 5:
                                        echo 'Perjantai';
                                    break;
                                endswitch;
                            ?>
                            <br /><span style="font-size: 20px;"><?php echo date('d.m.Y',strtotime($paiva)); ?></span></h2>
                        
                    </div>
                    <div class="panel-body">
                        <ul class="list-group">
                            <?php foreach (getKaikkiAjat($dbh, $paiva) as $tunti): 
                            $tunti_tiedot = getTunti($dbh, $tunti['id']);
                            if($tunti_tiedot): ?>
						          
                                <li class="list-group-item" >
                                    <?php 

                                    echo $tunti['tunti']; 
                                    
                                    ?>

                                    <?php if($tunti_tiedot['tila'] == 1): ?>
                                        <span class="btn btn-success btn-xs valitse-btn" style="float: right;" data-id="<?php echo $tunti_tiedot['uid']; ?>" data-date="<?php echo date('d.m.Y',strtotime($paiva)); ?>" data-hour="<?php echo $tunti['tunti']; ?>" >Vapaa</span>
                                        <?php if($tunti_tiedot['toimipiste'] > 0) { echo getToimipiste($dbh, $tunti_tiedot['toimipiste']); } ?>
                                    <?php endif; ?>

                                    <?php if($tunti_tiedot['tila'] == 2): ?>
                                        <span class="btn btn-danger btn-xs vaihto-varattu-badge" data-id="<?php echo $tunti_tiedot['uid']; ?>" style="float: right;" >Varattu</span>
                                        <div class="varaukset collapse" style="padding: 0px 10px;font-size: 10px;">    
                                            Opettaja:<br /> <strong><?php echo $tunti_tiedot['opettaja']; ?></strong><br />
                                            Oppilas:<br /> <strong><?php echo $tunti_tiedot['oppilas']; ?></strong>
                                        </div>
                                    <?php endif; ?>

                                  
                                </li>
								
                            <?php 
                            endif;
							endforeach; ?>
                        </ul>

                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

   
    


    
    <div class="modal fade" id="booking-modal">
        <div class="modal-dialog">
            <div class="modal-content">
                <form action="varaa2.php" method="post" id="booking-form">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title">Ajanvaraus</h4>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-success" id="booking-success">
                            <strong>Kiitos varauksestasi!</strong> Valitsemasi ajat on nyt varattu ja sähköpostiisi on toimitettu vahvistus ajanvarauksesta.
                        </div>
                        <div class="alert alert-warning" id="booking-warning">
                        </div>
                        <div class="alert alert-danger" id="booking-fail">
                            <strong>Varaus epäonnistui</strong> Kaikki kentät ovat pakollisia.
                        </div>
                        <div id="booking-form-content">
                            <input type="hidden" class="form-control" id="booking_ajat" name="booking[ajat]" />
							
							<div class="form-group">
                                <label for="name">Opettajan nimi *</label>
                                <input type="text" class="form-control" id="opettaja" name="booking[opettaja]"
                                       placeholder="Nimi" required="required" size="100"/>
                            </div>
							
							<div class="form-group">
                                <label for="name">Oppilaan nimi *</label>
                                <input type="text" class="form-control" id="oppilas" name="booking[oppilas]"
                                       placeholder="Nimi" required="required" size="100"/>
                            </div>
							
							<div class="form-group">
                                <label for="name">Säestettävät kappaleet *</label>
                                <textarea class="form-control"  name="booking[kappaleet]" required="required"></textarea>
                            </div>
							
							<div class="form-group">
                                <label for="name">Tiedoksi säestäjälle</label>
                                <textarea class="form-control"  name="booking[lisatietoja]"></textarea>
                            </div>
							
							
                            <div class="form-group">
                                <label for="email">Sähköpostiosoite, johon vahvistus varauksesta *</label>
                                <input type="email" class="form-control" required="required" id="email" name="booking[sahkoposti]"
                                       placeholder="Sähköpostiosoite" size="100"/>
                            </div>
                                 
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Sulje</button>
                        <button type="submit" id="booking-form-submit" class="btn btn-primary">Varaa</button>
                    </div>
                </form>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>



    </div>
    <!-- /container -->

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="/js/jquery-1.10.2.js"></script>
    <script src="/js/bootstrap.min.js"></script>
    <script>

    $(function () {
		
        
		
		$( ".muutos" ).change(function() {
		
			if($(this).val() == 'Varaus') {
				$( ".varaajan_nimi" ).toggle( "slow", function() {});
			} else {
				$(".varaajan_nimi").hide();
			}
		  
		});
		
		var booking_times = [];
        var booking_ids = [];
		var index;
		var booking_cart;
		$("#varaa").attr('disabled','disabled');
		
        // Hide alerts by default
        $("#booking-success").hide();
        $("#booking-fail").hide();
        $("#booking-warning").hide();
		

        // Handle varaa button
        $("#varaa").click(function (event) {
            event.preventDefault();
            $('#booking-modal').modal('show');
        });
		
		// Handle valitse button
        $(".valitse-btn").click(function (event) {
            event.preventDefault();
			if (0 < booking_times.length) {
				booking_times[booking_times.length] = $(this).attr('data-date') + " klo " + $(this).attr('data-hour');
			} else {
				booking_times[0] = $(this).attr('data-date') + " klo " + $(this).attr('data-hour');
			}

            if (0 < booking_ids.length) {
                booking_ids[booking_ids.length] = $(this).attr('data-id');
            } else {
                booking_ids[0] = $(this).attr('data-id');
            }
			//$(this).attr('disabled','disabled');
			$(this).text('Valittu');
			$(this).removeClass('valitse-btn').removeClass('btn-success').addClass('btn-warning').off('click');
			
			var booking_cart = "";
			for	(index = 0; index < booking_times.length; index++) {
				booking_cart += booking_times[index] + "<br />";
			}
			
			var jsonAjat = JSON.stringify(booking_ids);
			
			$("#varaa").removeAttr('disabled');
			$("#booking_times").html(booking_cart);
			$("#booking_ajat").val(jsonAjat);
            console.log(booking_times);
            //$('#booking-modal').modal('show');
        });

        // Handle booking form submit
        $("#booking-form").submit(function (event) {
            event.preventDefault();
            $("#booking-form-submit").attr('disabled','disabled');
            $("#booking-success").hide();
            $("#booking-fail").hide();

            var form = $(this);
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize(),
            }).done(function (data) {
                    $("#booking-form-submit").removeAttr('disabled');
                    if (data == "") {
                        $("#booking-success").show();
                        $("#booking-form-content").hide();
                        $("#booking-form-submit").hide();
                    } else if (data.substring(0, 3) == "100") {
                        $("#booking-warning").show();
                        $("#booking-warning").html(data.substring(3));
                        $("#booking-form-content").hide();
                        $("#booking-form-submit").hide();
                    } else {
                        $("#booking-fail").show();
                        $("#booking-fail").html(data);
                    }
					setTimeout(function (){

					location.reload(true);	 //something you want delayed

					 }, 2000);
                });
        });
    });
</script>
    </body>


    </html>
