<?php 
   /**
    *
    * copyright (c) 2013-2022 Heliac Technologies
    * license http://opensource.org/licenses/gpl-license.php GNU GPL v3 
    *
    * linee guida per l'utilizzo del logo http://www.geecom.org/articolo.php?id=34&alias=linee-guida-per-l%27uso-del-logo-geecom
    */

    include "include/costanti.php";
    include "include/util.php";
    include "gUtil/DbManager.php";
    include "classi/GeneratoreUrl.php";
    include "template/stile.php";
    include "classi/GestoreJavascript.php";
    include "template/include/includeClassiTemplate.php";
    
    //i dati del database sono definiti nel file costanti.php
    $geecomDb = new DbManager($costantiDatabase);		
    $gestoreJavascript = new GestoreJavascript();

    $impostazioni = recuperaImpostazioni($geecomDb);
    $configurazioneAspetto = $geecomDb->leggiSingolaRiga("geec_configurazioniAspetto", "si","selezionataAdmin");
    $inclusioni            = $geecomDb->leggiSingolaRiga("geecAd_inclusioni", 1);

    $idTiket = filter_input(INPUT_GET,"id",FILTER_SANITIZE_NUMBER_INT);

    session_start();
    if(!isset($_SESSION["geecomUser_email"]) ) {
        header("Location: index.php");
    }
    else {
	$utente = $geecomDb->leggiSingolaRIga("geec_utenti",$_SESSION["geecomUser_id"]);
        $ticket = $geecomDb->leggiSingolaRiga("geecAd_comunicazioni", $idTiket);
        $data   = date("d/m/Y",strtotime($ticket["dataCreazione"]));
        if($ticket["priorita"]=="alta") {
            $classePriorita="text-danger";
        }
        else if($ticket["priorita"]=="media") {
            $classePriorita="text-warning";
        }
        else {
            $classePriorita="text-muted";
        }
    }
    
    $lingua = "italiano";
?>
<html>

<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <meta name="generator" content="Geecom Admin"/>
    <title><?php echo $impostazioni["nomePiattaforma"]; ?></title>

    <!-- Favicon-->
    <link rel="icon" href="favicon.ico" type="image/x-icon">
	
	<?php 
            include "include/includeCssBase.php";
	?>
    	<link rel="stylesheet" href="plugins/OwlCarousel2/assets/owl.carousel.min.css">
</head>

    <body>

        <div class="wrapper">
            <?php
                include "template/include/menuPrincipale.php";
            ?>
            <!-- Contenuto principale  -->
            <div id="content" class="p-0 extramargin d-flex flex-column">
                <div class="page-wrapper">
                    <?php
                        include "template/include/barraSuperiore.php";

                        $queryUltimaRisposta = "SELECT * FROM geecAd_risposteTicket WHERE idTicket={$ticket["id"]} ORDER BY dataCreazione DESC LIMIT 1";
                        $risUltimaRisposta   = $geecomDb->eseguiQueryLettura($queryUltimaRisposta);
                        if($risUltimaRisposta->num_rows>0) {
                            $ultimaRisposta = $risUltimaRisposta->fetch_assoc();
                            $dataRisposta = date("d/m/Y",strtotime($ultimaRisposta["dataCreazione"]));
                            $oraRisposta  = date("H:i",strtotime($ultimaRisposta["dataCreazione"]));
                        }
                        else {
                            $ultimaRisposta = null;
                        }
                    ?>
                    <main class="p-4">
                        <div class="container">
                            <?php 
                                if(isset($_GET["status"])) {
                                    if($_GET["status"]==200) {
                                        echo"<div class=\"alert alert-success alert-dismissible fade show\" role=\"alert\">
                                                Ticket creato
                                                <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">
                                                    <span aria-hidden=\"true\">&times;</span>
                                                </button>
                                            </div>";
                                    }
                                    else if($_GET["status"]==222) {
                                        echo"<div class=\"alert alert-success alert-dismissible fade show\" role=\"alert\">
                                                Risposta inserita
                                                <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">
                                                    <span aria-hidden=\"true\">&times;</span>
                                                </button>
                                            </div>";
                                    }
                                    else if($_GET["status"]==250) {
                                        echo"<div class=\"alert alert-success alert-dismissible fade show\" role=\"alert\">
                                                Ticket chiuso
                                                <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">
                                                    <span aria-hidden=\"true\">&times;</span>
                                                </button>
                                            </div>";
                                    }
                                }
                            ?>
                            <div class="row">
                                <div class="col elenco-alternato">
                                    <div class="card p-4 ticket">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <small>
                                                <strong class="d-block">ID:<?php echo $ticket["id"]; ?> - <span class="<?php echo $classePriorita; ?>">Priorità <?php echo StampaContenuti::fiammePriorita($ticket["priorita"])?></span></strong>
                                                <span>Creato il <strong><?php echo $data; ?></strong> <i class="far fa-clock"></i> <strong>10:30</strong></span> 
                                                <span class="mx-2 d-none d-lg-inline-block">|</span>
                                                <span><?php echo(($ultimaRisposta==null) ? "Ancora Nessuna risposta":"Ultima risposta del <strong>$dataRisposta</strong> <i class=\"far fa-clock\"></i> <strong>$oraRisposta</strong>"); ?></span>
                                            </small>
                                            <span class="badge badge-<?php echo(($ticket["stato"]!="chiuso") ? "danger" : "info"); ?> d-flex align-items-center px-2"><?php echo ucfirst($ticket["stato"]); ?></span>
                                        </div>
                                        <h5 class="text-primary"><?php echo $ticket["oggetto"]; ?></h5>
                                        <p><?php echo $ticket["testo"]; ?></p>
		                                <?php
					            $queryAllegati = "SELECT * FROM geecAd_allegatiComunicazioni WHERE idComunicazione={$ticket["id"]}";
					            $risAllegati   = $geecomDb->eseguiQueryLettura($queryAllegati);
					            if($risAllegati->num_rows>0) {
					            	?>
							    <div class="bg-light p-2">
						                <h6>Allegati</h6>
						                <div class="form-row bg-light row-cols-2 row-cols-sm-3 row-cols-lg-4 row-cols-lg-6">
						                	<?php
									    while($allegato = $risAllegati->fetch_assoc()) {
									    	$datiFile = pathinfo($allegato["percorso"]);
									    	if($datiFile["extension"]=="jpg" || $datiFile["extension"]=="jpeg" || $datiFile["extension"]=="png") {
											?>
											<div class="col">
												<a href="<?= $allegato["percorso"] ?>" target="_blank">
												<div class="aspect-ratio-16-9">
													<img class="img-fluid" src="<?= $allegato["percorso"] ?>">
												</div>
												</a>
											</div>
											<?php
									    	}
									    	else {
											?>
											<div class="col">
												<a class="btn btn-outline-primary btn-block btn-sm" href="<?= $allegato["percorso"] ?>" target="_blank"><i class="fas fa-file-download fa-lg d-block mb-2"></i> <?= str_replace("file/allegatiComunicazioni/","",$allegato["percorso"]) ?></a>
											</div>
											<?php
									    	}
									    }
						                	?>
						                </div>
							    </div>
					            	<?php
					            }
		                                ?>
                                    </div>
					
                                    <?php 
                                        $query = "SELECT * FROM geecAd_risposteTicket WHERE idTicket={$ticket["id"]}";
                                        $ris   = $geecomDb->eseguiQueryLettura($query);
                                        while($risposta = $ris->fetch_assoc()) {
                                            StampaContenuti::stampaRispostaTicket($risposta);
                                        }

                                        if($ticket["stato"]!="chiuso") {
                                    ?>

                                    <!-- rispondi -->
                                    <div class="card ticket">
                                        <div class="card-header collapsed"><span class="title">Rispondi</span>
                                            <div class="btn-group float-right" role="group" aria-label="Basic example">
                                                <button class="btn btn-light " data-toggle="collapse" href="#nuovoTicket"> <i class="fas fa-minus fa-xs"></i> </button>
                                            </div>
                                        </div>
                                        <div id="nuovoTicket" class="card-body collapse show noOverflow">
                                            <form name="formRispondiTicket" action="controller/controllerComunicazioni.php" method="post">
                                                <input class="d-none" type="text" name="id" value="<?php echo $ticket["id"]; ?>">
                                                <input class="d-none" type="text" name="operazione" value="rispondiTicket">
                                                <div class="form-group">
                                                    <textarea class="form-control tiny" id="testo" rows="5" name="testo" placeholder="Scrivi qui la risposta" required></textarea>
                                                </div>
                                                <div class="form-group">
                                                    <button type="button" class="btn btn-primary float-right invia" onclick="rispondiTicket()">Invia</button>
                                                </div>
                                            </form>
                                        </div>	
                                    </div>
                                    <!-- /rispondi -->

                                </div>
                            </div>
                            <hr>
                            <button class="btn btn-success float-right mb-4" onclick="chiudiTicket(<?= $ticket["id"] ?>)">Chiudi ticket </button>
                            <?php
                                }
                            ?>
                        </div>
                    </main>
                </div>
            <?php
                include "template/include/footer.php";
            ?>
            </div>
        </div>
        <?php 
             if($impostazioni["accessoFacebook"]=="si") {
                include "include/facebookSdk.php";
             }

            include"include/includeJsBase.php"; 
            include"template/include/includeJsTemplate.php"; 
        ?>
        <script>
            function rispondiTicket() {
                var testo   = tinymce.activeEditor.getContent();

                if(testo=="") {
                    alert("Inserisci la risposta");
                }
                else if(testo.indexOf("<script>")>-1) {
                    alert("Attenzione: non puoi inserire script nei campi di testo");
                }
                else {
                    document.formRispondiTicket.submit();
                }
            }

            function chiudiTicket(idTicket) {
                $.ajax({
                    type:"POST",
                    url:"controller/controllerComunicazioni.php",
                    data:{
                        operazione:"chiudiTicket",
                        id:idTicket
                    },
                    success:function(text) {
                        if(text=="ok") {
                            location.href="dettagliTicket.php?id="+idTicket+"&status=250";
                        }
                        else {
                            alert(text);
                        }
                    },
                    error: function() {
                        alert("Si sono verificato problemi durante la richiesta, riprova tra qualche istante");
                    }
                });
            }
        </script>
    </body>

</html>
