<?php require_once('../Connections/cmctrfdb.php'); ?>
<?php require_once('../webassist/mysqli/queryobj.php'); ?>
<?php
include('include/headscript.php'); ?>
<?php
// pickup the get variable
if (isset($_GET["certtype"])) {
    $certtype = $_GET["certtype"];
    if ($certtype == 7) {
        $certtype = 1;
    }
}
if (isset($_GET["tempcode"])) {
    $tempcode = $_GET["tempcode"];
}
if (isset($_GET["previousrepnumber"])) {
    $previousrepnumber = $_GET["previousrepnumber"];
} else {
    $previousrepnumber = "";
}
if (isset($_GET["idtrf"])) {
    $idtrf = $_GET["idtrf"];
}
if (isset($_POST["idtrf"])) {
    $idtrf = $_POST["idtrf"];
}
if (isset($_GET["issuebycimac"])) {
    $issuebycimac = $_GET["issuebycimac"];
} else {
    $issuebycimac = "";
}
if (isset($_GET["samplestore"])) {
    $samplestore = $_GET["samplestore"];
} else {
    $samplestore = "";
}
if (isset($_GET["notificatedorganismname"])) {
    $notificatedorganismname = $_GET["notificatedorganismname"];
} else {
    $notificatedorganismname = "";
}
if (isset($_GET["notificatedorganismname"])) {
    $notificatedorganismname = $_GET["notificatedorganismname"];
} else {
    $notificatedorganismname = "";
}
if (isset($_GET["previousrepnumber"])) {
    $previousrepnumber = $_GET["previousrepnumber"];
} else {
    $previousrepnumber = "";
}
if (isset($_GET["renewdate"])) {
    $renewdate = $_GET["renewdate"];
} else {
    $renewdate = "";
}
if (isset($_GET["filedescription"])) {
    $filedescription = $_GET["filedescription"];
} else {
    $filedescription = "";
}
if (isset($_GET["certtwoupd"])) {
    $certtwoupd = $_GET["certtwoupd"];
}
if (isset($_GET["certthreeupd"])) {
    $certthreeupd = $_GET["certthreeupd"];
}
if (isset($_GET["revwhy"])) {
    $revwhy = $_GET["revwhy"];
}
if (isset($_GET["certfourupd"])) {
    $certfourupd = $_GET["certfourupd"];
}
if (isset($_GET["toextend"])) {
    $toextend = $_GET["toextend"];
} else {
    $toextend = "";
}
?>
<?php

include 'ddown/dropdown.php';

$obj = new Dropdown();

$rows = $obj->fetchCountry();

?>
<?php
//calculate next trf number available
$lasttrfnumber = new WA_MySQLi_RS("lasttrfnumber", $cmctrfdb, 1);
$lasttrfnumber->setQuery("SELECT * FROM `trf-details` ORDER BY `trf-details`.trfnumber DESC LIMIT 1");
$lasttrfnumber->execute(); ?>
<?php
$lastnumber = $lasttrfnumber->getColumnVal("trfnumber");
$nextnumber = $lastnumber + 1;
?>
<?php
if (!isset($_GET["idtrf"])) {
    //check if the tempcode already exist
    $tempcodesearch = new WA_MySQLi_RS("tempcodesearch", $cmctrfdb, 1);
    $tempcodesearch->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.tempcode='$tempcode'");
    $tempcodesearch->execute();
}
?>
<?php //update certificate 2
if (isset($certtwoupd)) {

    $UpdateQuery = new WA_MySQLi_Query($cmctrfdb);
    $UpdateQuery->Action = "update";
    $UpdateQuery->Table = "`trf-details`";
    $UpdateQuery->bindColumn("previousreportnumber", "s", "$previousrepnumber", "WA_DEFAULT");
    $UpdateQuery->bindColumn("notificatedorganismname", "s", "$notificatedorganismname", "WA_DEFAULT");
    $UpdateQuery->addFilter("idtrfdetails", "=", "i", "" . ($idtrf)  . "");
    $UpdateQuery->execute();
    $UpdateGoTo = "";
    if (function_exists("rel2abs")) $UpdateGoTo = $UpdateGoTo ? rel2abs($UpdateGoTo, dirname(__FILE__)) : "";
    $UpdateQuery->redirect($UpdateGoTo);
}
?>
<?php //update certificate 3 and 8
if (isset($certthreeupd)) {
    if (isset($revwhy)) {
        $UpdateQuery = new WA_MySQLi_Query($cmctrfdb);
        $UpdateQuery->Action = "update";
        $UpdateQuery->Table = "`trf-details`";
        $UpdateQuery->bindColumn("previousreportnumber", "s", "$previousrepnumber", "WA_DEFAULT");
        $UpdateQuery->bindColumn("revisionfor", "s", "$revwhy", "WA_DEFAULT");
        $UpdateQuery->addFilter("idtrfdetails", "=", "i", "" . ($idtrf)  . "");
        $UpdateQuery->execute();
        $UpdateGoTo = "";
        if (function_exists("rel2abs")) $UpdateGoTo = $UpdateGoTo ? rel2abs($UpdateGoTo, dirname(__FILE__)) : "";
        $UpdateQuery->redirect($UpdateGoTo);
    } else {
        $UpdateQuery = new WA_MySQLi_Query($cmctrfdb);
        $UpdateQuery->Action = "update";
        $UpdateQuery->Table = "`trf-details`";
        $UpdateQuery->bindColumn("previousreportnumber", "s", "$previousrepnumber", "WA_DEFAULT");
        $UpdateQuery->bindColumn("renewdate", "s", "$renewdate", "WA_DEFAULT");
        $UpdateQuery->addFilter("idtrfdetails", "=", "i", "" . ($idtrf)  . "");
        $UpdateQuery->execute();
        $UpdateGoTo = "";
        if (function_exists("rel2abs")) $UpdateGoTo = $UpdateGoTo ? rel2abs($UpdateGoTo, dirname(__FILE__)) : "";
        $UpdateQuery->redirect($UpdateGoTo);
    }
}
?>
<?php //update certificate 4
if (isset($certfourupd)) {

    $UpdateQuery = new WA_MySQLi_Query($cmctrfdb);
    $UpdateQuery->Action = "update";
    $UpdateQuery->Table = "`trf-details`";
    $UpdateQuery->bindColumn("previousreportnumber", "s", "$previousrepnumber", "WA_DEFAULT");
    $UpdateQuery->bindColumn("toextend", "s", "$toextend", "WA_DEFAULT");
    $UpdateQuery->addFilter("idtrfdetails", "=", "i", "" . ($idtrf)  . "");
    $UpdateQuery->execute();
    $UpdateGoTo = "";
    if (function_exists("rel2abs")) $UpdateGoTo = $UpdateGoTo ? rel2abs($UpdateGoTo, dirname(__FILE__)) : "";
    $UpdateQuery->redirect($UpdateGoTo);
}
?>
<?php
// insert the new TRF into the table
if (!isset($_GET["idtrf"])) {
    if (empty($tempcodesearch->getColumnVal("idtrfdetails"))) {
        $InsertQuery = new WA_MySQLi_Query($cmctrfdb);
        $InsertQuery->Action = "insert";
        $InsertQuery->Table = "`trf-details`";
        $InsertQuery->bindColumn("trfnumber", "i", "$nextnumber", "WA_DEFAULT");
        $InsertQuery->bindColumn("idcompany", "i", "$idcompany", "WA_DEFAULT");
        $InsertQuery->bindColumn("iduser", "i", "$iduserlogin", "WA_DEFAULT");
        $InsertQuery->bindColumn("idcertification", "i", "$certtype", "WA_DEFAULT");
        $InsertQuery->bindColumn("previousreportnumber", "s", "$previousrepnumber", "WA_DEFAULT");
        $InsertQuery->bindColumn("tempcode", "s", "$tempcode", "WA_DEFAULT");
        $InsertQuery->bindColumn("notificatedorganismname", "s", "$notificatedorganismname", "WA_DEFAULT");
        $InsertQuery->saveInSession("");
        $InsertQuery->execute();
        $InsertGoTo = "";
        $InsertQuery->redirect($InsertGoTo);

        $tempcodesearch2 = new WA_MySQLi_RS("tempcodesearch", $cmctrfdb, 1);
        $tempcodesearch2->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.tempcode='$tempcode'");
        $tempcodesearch2->execute();

        $idtrf = $tempcodesearch2->getColumnVal("idtrfdetails");

        $code = "1";
        $InsertQuery = new WA_MySQLi_Query($cmctrfdb);
        $InsertQuery->Action = "insert";
        $InsertQuery->Table = "wheretrfstep";
        $InsertQuery->bindColumn("idtrf", "i", "$idtrf", "WA_DEFAULT");
        $InsertQuery->bindColumn("code", "i", "$code", "WA_DEFAULT");
        $InsertQuery->saveInSession("");
        $InsertQuery->execute();
        $InsertGoTo = "";
        $InsertQuery->redirect($InsertGoTo);

        $code = "2";
        $InsertQuery = new WA_MySQLi_Query($cmctrfdb);
        $InsertQuery->Action = "insert";
        $InsertQuery->Table = "wheretrfstep";
        $InsertQuery->bindColumn("idtrf", "i", "$idtrf", "WA_DEFAULT");
        $InsertQuery->bindColumn("code", "i", "$code", "WA_DEFAULT");
        $InsertQuery->saveInSession("");
        $InsertQuery->execute();
        $InsertGoTo = "";
        $InsertQuery->redirect($InsertGoTo);

        $UpdateQuery = new WA_MySQLi_Query($cmctrfdb);
        $UpdateQuery->Action = "update";
        $UpdateQuery->Table = "contacts";
        $UpdateQuery->bindColumn("idtrf", "i", "$idtrf", "WA_DEFAULT");
        $UpdateQuery->addFilter("tempcode", "=", "s", "" . ($tempcode)  . "");
        $UpdateQuery->execute();
        $UpdateGoTo = "";
        if (function_exists("rel2abs")) $UpdateGoTo = $UpdateGoTo ? rel2abs($UpdateGoTo, dirname(__FILE__)) : "";
        $UpdateQuery->redirect($UpdateGoTo);

        //include('uploadfilecertificate.php');
    }
}
?>
<?php
if (!isset($_GET["idtrf"])) {

    $trfnumberfinal = new WA_MySQLi_RS("trfnumberfinal", $cmctrfdb, 1);
    $trfnumberfinal->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.tempcode='$tempcode'");
    $trfnumberfinal->execute();
    $idtrf = $trfnumberfinal->getColumnVal("idtrfdetails");
    $idcertn = $trfnumberfinal->getColumnVal("idcertification");
} else {
    $trfnumberfinal = new WA_MySQLi_RS("trfnumberfinal", $cmctrfdb, 1);
    $trfnumberfinal->setQuery("SELECT * FROM `trf-details` WHERE `trf-details`.idtrfdetails='$idtrf'");
    $trfnumberfinal->execute();
    $idcertn = $trfnumberfinal->getColumnVal("idcertification");
}
?>
<?php
$typearticleselect = new WA_MySQLi_RS("typearticleselect", $cmctrfdb, 0);
$typearticleselect->setQuery("SELECT * FROM article_type ORDER BY article_type.name_articletype");
$typearticleselect->execute(); ?>
<?php
$charactarticle = new WA_MySQLi_RS("charactarticle", $cmctrfdb, 0);
$charactarticle->setQuery("SELECT * FROM article_characteristic ORDER BY article_characteristic.name_articlecharacteristic");
$charactarticle->execute(); ?>
<?php $idcert = $trfnumberfinal->getColumnVal("idcertification") ?>
<?php
$certname = new WA_MySQLi_RS("certname", $cmctrfdb, 1);
$certname->setQuery("SELECT * FROM certificationtype WHERE certificationtype.idcertificationtype='$idcert'");
$certname->execute(); ?>
<?php
$modelarticlelist = new WA_MySQLi_RS("modelarticlelist", $cmctrfdb, 1);
$modelarticlelist->setQuery("SELECT * FROM modelarticle ORDER BY modelarticle.namemodelarticle");
$modelarticlelist->execute();
?>
<?php
include('include/trfqueryscript.php');  ?>
<?php if ($idcertn == '5' && $samplestore == 'N') {
    header("Location: samplestore.php?idtrf=$idtrf&issuebycimac=$issuebycimac");
} elseif ($idcertn == '5' && $samplestore == 'Y' && $issuebycimac == 'N') {
    header("Location: adddocument.php?idtrf=$idtrf");
} elseif ($idcertn == '5' && $samplestore == 'Y' && $issuebycimac == 'Y') {
    header("Location: trfoption.php?idtrf=$idtrf");
} elseif ($idcertn == '6' && $issuebycimac == 'N') {
    header("Location: adddocument.php?idtrf=$idtrf");
} elseif ($idcertn == '6' && $issuebycimac == 'Y') {
    header("Location: trfoption.php?idtrf=$idtrf");
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title><?php echo $titlepage; ?> </title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta content="CIMAC TRF Portal" name="description" />
    <meta content="" name="author" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <!-- App favicon -->
    <link rel="shortcut icon" href="../images/favicon.ico">

    <!--Form Wizard-->
    <!-- Load jQuery -->
    <!--  <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>-->
    <!-- Load Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <!-- App css -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/jquery-ui.min.css" rel="stylesheet">
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/metisMenu.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" rel="stylesheet" type="text/css" />
    <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <!-- submit form with button -->
    <script>
        function formSubmit() {
            document.forms["myForm"].submit();
        }
    </script>
    <!-- upload image script -->
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
        $(document).ready(function() {
            $(".upload-doc").click(function() {
                $(".form-horizontal").ajaxForm({
                    target: '.preview'
                }).submit();
            });
        });
    </script>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <style>
        /* select2 css */
        .select2-container {
            width: 100% !important;
        }

        .select2-selection__choice,
        .select2-selection__choice__remove {
            background-color: blue !important;
            color: white !important;
            border: 1px solid blue !important;
        }

        /* select2 css end */

        input:invalid {
            border-color: #ff0000;
            background-color: #fff7e6;
        }

        input:focus {
            background: yellow;
        }

        input:valid {
            border-color: #66ff33;
            background-color: #eeffe6;
        }

        select:invalid {
            border-color: #ff0000;
            background-color: #fff7e6;
        }

        select:focus {
            background-color: yellow;
        }

        select:valid {
            border-color: #66ff33;
            background-color: #eeffe6;
        }
    </style>

    <style>
        #uploadForm {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: nowrap;
        }

        #uploadForm>label {
            margin-bottom: 0;
            white-space: nowrap;
        }

        #fileName {
            flex-grow: 1;
            flex-shrink: 1;
            flex-basis: auto;
            /* Si adatta al contenuto */
            width: 0;
            /* Permette di crescere o restringersi */
            max-width: 200px;
            /* Imposta una larghezza massima */
        }

        .btn-file {
            position: relative;
            overflow: hidden;
        }

        .btn-file input[type=file] {
            position: absolute;
            top: 0;
            right: 0;
            min-width: 100%;
            min-height: 100%;
            font-size: 100px;
            text-align: right;
            filter: alpha(opacity=0);
            opacity: 0;
            outline: none;
            background: white;
            cursor: inherit;
            display: block;
        }
    </style>
</head>

<body>

    <!-- Top Bar Start -->
    <?php include('include/topbar.php'); ?>
    <!-- Top Bar End -->

    <!-- Left Sidenav -->
    <?php include('include/leftsidenav.php'); ?>
    <!-- end left-sidenav-->
    <div class="page-wrapper">
        <!-- Page Content-->
        <div class="page-content">
            <div class="container-fluid">
                <!-- Page-Title -->
                <div class="row">
                    <div class="col-sm-12">
                        <div class="page-title-box">
                            <div class="float-right">
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="javascript:void(0);"><?php echo $titlepage; ?></a></li>
                                    <li class="breadcrumb-item active">Starter</li>
                                </ol>
                            </div>
                            <h4 class="page-title"><?php echo $titlewb; ?></h4>
                        </div><!--end page-title-box-->
                    </div><!--end col-->
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="media">


                                    <?php include('include/appform.php'); ?>
                                </div><!--end media-->

                            </div><!--end card-body-->
                        </div><!--end card-->

                        <div class="progress mb-4">
                            <div class="progress-bar" role="progressbar" style="width: 30%;" aria-valuenow="30" aria-valuemin="0" aria-valuemax="100">30%</div>
                        </div>

                        <?php if ($trfnumberfinal->getColumnVal("otherclient") == 'Y') { ?>
                            <div class="card">
                                <div class="card-body">



                                    <p><?php echo $nameclienttocertificate; ?></p>
                                    <?php
                                    $kindcont = "headercertificate";
                                    include('include/insertcont.php'); ?>
                                    <?php
                                    $certcontactdata = new WA_MySQLi_RS("certcontactdata", $cmctrfdb, 1);
                                    $certcontactdata->setQuery("SELECT * FROM contacts WHERE contacts.idtrf='$idtrf' AND contacts.kindofcontacts='$kindcont'");
                                    $certcontactdata->execute();
                                    ?>
                                    <table class="table table-bordered mb-0 table-centered">

                                        <thead>
                                            <tr>

                                                <th scope="col"><?php echo $anagraficacompany; ?></th>
                                                <th scope="col"><?php echo $anagraficaaddress; ?></th>
                                                <th scope="col"><?php echo $anagraficacity; ?></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>

                                                <td><?php echo ($certcontactdata->getColumnVal("companyname")); ?></td>
                                                <td><?php echo ($certcontactdata->getColumnVal("address")); ?></td>
                                                <td><?php echo ($certcontactdata->getColumnVal("city")); ?></td>
                                            </tr>
                                        </tbody>
                                    </table><br>

                                    <a class="badge_btn" onclick="window.open('contactpop.php?kindcontacts=headercertificate&idtrf=<?php echo $idtrf; ?>&idcontacts=<?php echo ($certcontactdata->getColumnVal("idcontacts")); ?>', '_blank', 'location=yes,height=500,width=850,scrollbars=yes,status=yes');"><button type="button" class="btn btn-primary waves-effect waves-light"><?php echo $edictcontacttitle; ?></button></a>
                                    <br>
                                    <br>


                                </div><!--end card-body-->
                            </div><!--end card-->

                        <?php } ?>

                        <div class="card">
                            <div class="card-body">
                                <h4 class="mt-0 header-title"><?php echo $samplecheck; ?></h4>
                                <p class="text-muted mb-3"><?php echo $samplecheck_help; ?></p>


                                <div class="upload-div">
                                    <!-- File upload form -->
                                    <form id="uploadForm" enctype="multipart/form-data">
                                        <span><?php echo $chooseimage; ?> <?php echo $allowedkind; ?></span>

                                        <div class="btn btn-gradient-success waves-effect waves-light btn-file">
                                            <?php echo $browsebotton; ?> <input type="file" name="images[]" id="fileInput" onchange="document.getElementById('fileName').value = this.value.split('\\').pop();">
                                        </div>
                                        <input type="text" id="fileName" class="form-control" placeholder="<?php echo $nofilechoosen; ?>" readonly>

                                        <input type="hidden" name="idtrf" id="idtrf" value="<?php echo $trfnumberfinal->getColumnVal("idtrfdetails"); ?>">
                                        <input type="submit" class="btn btn-gradient-success waves-effect waves-light" name="submit" value="<?php echo $uploadph; ?>" style="flex-shrink: 0;">
                                    </form><br>

                                    <!-- Display upload status -->
                                    <div id="uploadStatus"></div>
                                    <div class="gallery">
                                        <?php if (!empty($trfnumberfinal->getColumnVal("photofilename"))) { ?>
                                            <ul>
                                                <img src="uploadimages/<?php echo ($trfnumberfinal->getColumnVal("photofilename")); ?>" height="200" alt="" />
                                            </ul>
                                        <?php } ?>
                                    </div>
                                </div>

                                <!-- Gallery view of uploaded images -->

                                <!-- <br>
									
									<td id="cont_photoupload">
										
                                                <?php if (!empty($trfnumberfinal->getColumnVal("photofilename"))) { ?>
                                                    <img src="uploadimages/<?php echo ($trfnumberfinal->getColumnVal("photofilename")); ?>" height="200" alt=""/>
                                                
                                                <?php } ?>
                                            </td> -->

                                <form class="form-parsley" action="standardstep.php" method="post" id="form" name="myForm" novalidate>

                                    <div class="form-group row">
                                        <label for="validationTooltip01" class="col-sm-3 col-form-label text-right"><?php echo $typearticletitle; ?></label>
                                        <div class="col-sm-8">
                                            <select class="form-control" name="articletype" id="articletype_change" required="">
                                                <option value="" <?php if (!(strcmp("", ($trfnumberfinal->getColumnVal("idarticletype"))))) {
                                                                        echo "selected=\"selected\"";
                                                                    } ?>><?php echo $pleaseselect; ?></option>
                                                <?php
                                                if (!empty($rows)) {

                                                    foreach ($rows as $row) {
                                                        // Controllo se l'idarticletype è uguale a 4
                                                        if ($row['idarticletype'] == 4) {
                                                            // Mostra l'opzione solo se l'utente è admin o superuser
                                                            if (Auth::user()->hasRole('Admin') || Auth::user()->hasRole('Superuser')) {
                                                ?>
                                                                <option value="<?php echo $row['idarticletype']; ?>" <?php if (!(strcmp($row['idarticletype'], ($trfnumberfinal->getColumnVal("idarticletype"))))) {
                                                                                                                            echo "selected=\"selected\"";
                                                                                                                        } ?>>
                                                                    <?php
                                                                    echo ($_SESSION['langselect'] == 'it') ? $row['name_articletype'] : $row['name_articletypeeng'];
                                                                    ?>
                                                                </option>
                                                            <?php
                                                            }
                                                        } else {
                                                            // Mostra normalmente gli altri articletype
                                                            ?>
                                                            <option value="<?php echo $row['idarticletype']; ?>" <?php if (!(strcmp($row['idarticletype'], ($trfnumberfinal->getColumnVal("idarticletype"))))) {
                                                                                                                        echo "selected=\"selected\"";
                                                                                                                    } ?>>
                                                                <?php
                                                                echo ($_SESSION['langselect'] == 'it') ? $row['name_articletype'] : $row['name_articletypeeng'];
                                                                ?>
                                                            </option>
                                                <?php
                                                        }
                                                    }
                                                }
                                                ?>
                                            </select>

                                        </div>

                                    </div>



                                    <div class="form-group row">

                                        <label for="validationTooltip01" class="col-sm-3 col-form-label"><?php echo $descriptiontitle; ?></label>

                                        <div class="col-sm-8">

                                            <input type="text" class="form-control" id="validationTooltip01" name="description" placeholder="<?php echo $descriptiontitle; ?>" value="<?php if (isset($_GET["idtrf"])) {
                                                                                                                                                                                            echo $sdescription;
                                                                                                                                                                                        } ?>" required="">

                                        </div>

                                    </div>


                                    <div class="form-group row">
                                        <label for="validationTooltip01" class="col-sm-3 col-form-label text-right"><?php echo $modeltitle; ?></label>
                                        <div class="col-sm-8">

                                            <select class="form-control" name="model" id="model_change" required="">
                                                <option value="" <?php if (!(strcmp("", ($trfnumberfinal->getColumnVal("model"))))) {
                                                                        echo "selected=\"selected\"";
                                                                    } ?>><?php echo $pleaseselect; ?></option>
                                                <?php
                                                $modelrows = $obj->fetchModel($trfnumberfinal->getColumnVal("idarticletype"));
                                                if (!empty($modelrows)) {

                                                    foreach ($modelrows as $row) {

                                                        // echo $row['idmodelarticle'];

                                                        // echo $trfnumberfinal->getColumnVal("model");

                                                ?>
                                                        <option value="<?php echo $row['idmodelarticle']; ?>" <?php if (!(strcmp($row['idmodelarticle'], ($trfnumberfinal->getColumnVal("model"))))) {
                                                                                                                    echo "selected=\"selected\"";
                                                                                                                } ?>><?php echo $row['namemodelarticle']; ?></option>

                                                <?php
                                                    }
                                                }
                                                ?>

                                            </select>
                                        </div>
                                    </div>
                                    <!-- INPUT FOR Calzature e guanti -->
                                    <div id="cont_range" style="display:<?php echo (!is_object($trfnumberfinal) || !in_array($trfnumberfinal->getColumnVal("idarticletype"), array(3))) ? "inline" : "none" ?>;">
                                        <div class="form-group row">
                                            <label for="validationTooltip01" class="col-sm-3 col-form-label"><?php echo $rangemeasuretitle; ?></label>
                                            <div class="col-sm-4">
                                                <input type="number" min="1" max="60" class="form-control" id="rangemeasuremin" name="rangemeasuremin" <?php echo (!is_object($trfnumberfinal) || !in_array($trfnumberfinal->getColumnVal("idarticletype"), array(3))) ? "required" : "" ?> placeholder="<?php echo $rangemeasuremintitle; ?>" value="<?php if (isset($smeasuremin)) {
                                                                                                                                                                                                                                                                                                                                                            echo $smeasuremin;
                                                                                                                                                                                                                                                                                                                                                        } ?>">
                                            </div>
                                            <div class="col-sm-4">
                                                <input type="number" min="1" max="60" class="form-control" id="rangemeasuremax" name="rangemeasuremax" <?php echo (!is_object($trfnumberfinal) || !in_array($trfnumberfinal->getColumnVal("idarticletype"), array(3))) ? "required" : "" ?> placeholder="<?php echo $rangemeasuremaxtitle; ?>" value="<?php if (isset($smeasuremax)) {
                                                                                                                                                                                                                                                                                                                                                            echo $smeasuremax;
                                                                                                                                                                                                                                                                                                                                                        } ?>">
                                            </div>
                                        </div>
                                    </div>
                                    <!--  INPUT FOR Semimaschere -->
                                    <div id="cont_dropdown" style="display:<?php echo (is_object($trfnumberfinal) && in_array($trfnumberfinal->getColumnVal("idarticletype"), array(3))) ? "inline" : "none"; ?>;">
                                        <div class="form-group row">
                                            <label for="validationTooltip01" class="col-sm-3 col-form-label"><?php echo $rangemeasuretitle; ?></label>
                                            <div class="col-sm-4">
                                                <input type="text" class="form-control" id="rangemeasuremintext" name="rangemeasuremintext" <?php echo (is_object($trfnumberfinal) && in_array($trfnumberfinal->getColumnVal("idarticletype"), array(3))) ? "required" : ""; ?> placeholder="<?php echo $rangemeasuremintitle; ?>" value="<?php if (isset($smeasuremin)) {
                                                                                                                                                                                                                                                                                                                                                echo $smeasuremin;
                                                                                                                                                                                                                                                                                                                                            } ?>">
                                            </div>
                                            <div class="col-sm-4">
                                                <input type="text" class="form-control" id="rangemeasuremaxtext" name="rangemeasuremaxtext" <?php echo (is_object($trfnumberfinal) && in_array($trfnumberfinal->getColumnVal("idarticletype"), array(3))) ? "required" : ""; ?> placeholder="<?php echo $rangemeasuremaxtitle; ?>" value="<?php if (isset($smeasuremax)) {
                                                                                                                                                                                                                                                                                                                                                echo $smeasuremax;
                                                                                                                                                                                                                                                                                                                                            } ?>">
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group row">
                                        <label for="validationTooltip01" class="col-sm-3 col-form-label " for="animals"><?php echo $articlecharacteristictitle; ?></label>

                                        <div class="col-sm-8">

                                            <select class="form-control" multiple name="articlecharacteristic[]" id="charact_result" required data-parsley-errors-container="#cont_char_error">

                                                <?php
                                                $selectedValue = explode(",", $trfnumberfinal->getColumnVal("idarticle_characteristics"));
                                                $chrows = $obj->fetchCharact($trfnumberfinal->getColumnVal("idarticletype"));

                                                if (!empty($chrows)) {

                                                    foreach ($chrows as $row) {

                                                ?>
                                                        <option value="<?php echo $row['idarticlecharacteristic']; ?>" <?php if (in_array($row['idarticlecharacteristic'], $selectedValue)) {
                                                                                                                            echo "selected=\"selected\"";
                                                                                                                        } ?>><?php echo $row['name_articlecharacteristic']; ?></option>

                                                <?php

                                                    }
                                                }

                                                ?>

                                            </select>
                                            <div id="cont_char_error"></div>
                                        </div>

                                    </div>




                                    <div class="form-group row">

                                        <label for="registeredmark" class="col-sm-3 col-form-label"><?php echo $registeredmarktitle; ?></label>

                                        <div class="col-sm-8">

                                            <input type="text" class="form-control mandatory" id="registeredmark" name="registeredmark" required placeholder="<?php echo $registeredmarktitle; ?>" value="<?php if (isset($_GET["idtrf"])) {
                                                                                                                                                                                                                echo $sregisteredmark;
                                                                                                                                                                                                            } ?>">

                                        </div>

                                    </div>

                                    <?php if ($idcertn == '3' || $idcertn == '4' || $idcertn == '8') { ?>

                                        <div class="form-group row">
                                            <?php
                                            if ($idcertn == '4') {
                                                $titlefieldn = $previosurepnumbertitlem15am30s;
                                            } elseif ($idcertn == '8') {
                                                $titlefieldn = $previosurepnumbertitlem15dm30s;
                                            } elseif ($idcertn == '3') {
                                                $titlefieldn = $previosurepnumbertitlem15bm30s;
                                            }
                                            ?>
                                            <label for="previousreportnumber" class="col-sm-3 col-form-label"><?php echo $titlefieldn; ?></label>

                                            <div class="col-sm-8">

                                                <input type="text" class="form-control" id="previousreportnumber" name="previousreportnumber" required="" placeholder="<?php echo $titlefieldn; ?>" value="<?php if (isset($_GET["idtrf"])) {
                                                                                                                                                                                                                echo ($trfnumberfinal->getColumnVal("previousreportnumber"));
                                                                                                                                                                                                            } ?>">

                                            </div>

                                        </div>
                                    <?php } ?>
                                    <?php if ($idcertn == '4') { ?>
                                        <div class="form-group row">

                                            <label for="toextend" class="col-sm-3 col-form-label"><?php echo $previosurepnumbertitlem15am30s_ext; ?></label>

                                            <div class="col-sm-8">

                                                <input type="text" class="form-control mandatory" id="toextend" name="toextend" required="" placeholder="<?php echo $previosurepnumbertitlem15am30s_ext; ?>" value="<?php if (isset($_GET["idtrf"])) {
                                                                                                                                                                                                                        echo ($trfnumberfinal->getColumnVal("toextend"));
                                                                                                                                                                                                                    } ?>">

                                            </div>

                                        </div>


                                    <?php } ?>

                                    <?php if ($idcertn == '3') { ?>
                                        <div class="form-group row">

                                            <label for="revisionfor" class="col-sm-3 col-form-label"><?php echo $revisionwhy; ?></label>

                                            <div class="col-sm-8">

                                                <input type="text" class="form-control mandatory" id="revisionfor" name="revisionfor" required="" placeholder="<?php echo $revisionwhy; ?>" value="<?php if (isset($_GET["idtrf"])) {
                                                                                                                                                                                                        echo ($trfnumberfinal->getColumnVal("revisionfor"));
                                                                                                                                                                                                    } ?>">

                                            </div>

                                        </div>


                                    <?php } ?>

                                    <?php if ($idcertn == '8') { ?>
                                        <div class="form-group row">

                                            <label for="revisionfor" class="col-sm-3 col-form-label"><?php echo $renewdatetitle;

                                                                                                        ?></label>

                                            <div class="col-sm-8">

                                                <input type="date" class="form-control mandatory" id="renewdate" name="renewdate" required="" placeholder="<?php echo $renewdatetitle; ?>" value="<?php if (isset($_GET["idtrf"])) {
                                                                                                                                                                                                        echo ($trfnumberfinal->getColumnVal("renewdate"));
                                                                                                                                                                                                    } ?>">

                                            </div>

                                        </div>


                                    <?php } ?>

                                    <input type="hidden" name="idtrf" id="idtrf" value="<?php echo ($trfnumberfinal->getColumnVal("idtrfdetails")); ?>">
                                    <input type="hidden" name="formupdtrfdetails" id="formupdtrfdetails" value="Y">
                                    <br><br>
                                    <button class="btn btn-gradient-success waves-effect waves-light" type="submit"><?php echo $nextsteptitle; ?></button>

                                </form>
                            </div><!--end card-body-->
                        </div><!--end card-->
                        <script>
                            var idCertn = "<?php echo $idcertn; ?>";
                        </script>
                        <script>
                            var idCertn = "<?php echo $idcertn; ?>";
                        </script>
                        <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                const form = document.getElementById('form');
                                const renewDateInput = document.getElementById('renewdate');

                                // Esegui questo blocco solo se idCertn è '8'
                                if (idCertn === '8') {
                                    form.addEventListener('submit', function(e) {
                                        e.preventDefault(); // Previene il submit del form finché non passa la validazione
                                        validateRenewDate();
                                    });
                                }

                                function validateRenewDate() {
                                    const renewDateValue = renewDateInput.value;
                                    const today = new Date();
                                    const renewDate = new Date(renewDateValue);
                                    const fiveYearsAgo = new Date(today.getFullYear(), today.getMonth(), today.getDate());

                                    if (renewDate < fiveYearsAgo) {
                                        // Se la data di rinnovo è più vecchia dalla data attuale
                                        Swal.fire({
                                            title: 'Attenzione!',
                                            text: 'Il certificato risulta già scaduto. Non puoi procedere con un rinnovo del certificato ma dovrai chiedere un nuovo certificato.',
                                            icon: 'warning',
                                            showCancelButton: true,
                                            confirmButtonText: 'Modifica data',
                                            cancelButtonText: 'Inserisci una nuova richiesta',
                                        }).then((result) => {
                                            if (result.isConfirmed) {
                                                // Se l'utente sceglie "Modifica data", permetti di modificare la data
                                            } else {
                                                // Se l'utente sceglie "Inserisci una nuova richiesta", reindirizza a dashboard.php
                                                window.location.href = 'dashboard.php';
                                            }
                                        });
                                    } else {
                                        // Se la data è valida, procedi con il submit del form
                                        form.submit();
                                    }
                                }
                            });
                        </script>


                    </div><!--end col-->
                </div>
                <!-- end page title end breadcrumb -->

            </div><!-- container -->
            <!-- footer start -->
            <?php include('include/footer.php'); ?>
            </footer><!--end footer-->
        </div>
        <!-- end page content -->
    </div>
    <!-- end page-wrapper -->




    <!-- jQuery  -->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/jquery-ui.min.js"></script>
    <script src="assets/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/metismenu.min.js"></script>
    <script src="assets/js/waves.js"></script>
    <script src="assets/js/feather.min.js"></script>
    <script src="assets/js/jquery.slimscroll.min.js"></script>
    <script src="assets/js/jquery-ui.min.js"></script>


    <!-- Parsley js -->
    <script src="../plugins/parsleyjs/parsley.min.js"></script>
    <script src="assets/pages/jquery.validation.init.js"></script>
    <!-- App js -->
    <script src="assets/js/jquery.core.js"></script>
    <script src="assets/js/app.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#charact_result').select2();
        });
        // Use the plugin once the DOM has been loaded.
    </script>
    <script>
        // country dependent ajax
        $(document).on("change", "#articletype_change", function(e) {
            e.preventDefault();

            var articletype = $("#articletype_change").val();

            $.ajax({
                type: "POST",
                url: "ddown/modelart.php",
                dataType: "json",
                data: "idarticletype=" + articletype,
                success: function(response) {
                    var modelBody = "";
                    var nameModelVar = "<?php echo ($_SESSION['langselect'] == 'it') ? 'namemodelarticle' : 'namemodelarticle_eng'; ?>";
                    modelBody = "<option value=\"\" selected=\"selected\"><?php echo $pleaseselect; ?></option>";
                    for (var key in response) {
                        var modelName = response[key][nameModelVar];
                        modelBody += "<option value=" + response[key]['idmodelarticle'] + ">" + modelName + "</option>";
                    }
                    $("#model_change").html(modelBody);
                    /* ADD REQUIRED ATTR */
                    // $("#model_change").attr("required", "required");
                }
            });
            /* TOGGLE RANGE INPUT */
            if (articletype == 3) {
                $('#cont_range').css('display', 'none');
                $('#cont_dropdown').css('display', 'inline');
                /* ADD REQUIRED ATTR */
                $("#rangemeasuremin2").attr("required", "required");
                /* REMOVE REQUIRED ATTR */
                $("#rangemeasuremin,#rangemeasuremax").removeAttr("required");
                $('#validationTooltip01').val('');
            } else if (articletype == 1 || articletype == 2) {
                $('#cont_range').css('display', 'inline');
                $('#cont_dropdown').css('display', 'none');

                /* REMOVE REQUIRED ATTR */
                $("#rangemeasuremin2").removeAttr("required");
                /* ADD REQUIRED ATTR */
                $("#rangemeasuremin,#rangemeasuremax").attr("required", "required");
            } else {
                /* DEFAULT */
                $('#cont_range').css('display', 'inline');
                $('#cont_dropdown').css('display', 'none');

                /* REMOVE REQUIRED ATTR */
                $("#rangemeasuremin2").removeAttr("required");
                /* ADD REQUIRED ATTR */
                $("#rangemeasuremin,#rangemeasuremax").attr("required", "required");
            }
        });
        // state dependent ajax
        $(document).on("change", "#articletype_change", function(e) {
            e.preventDefault();

            var charact = $("#articletype_change").val();

            $.ajax({
                type: "POST",
                url: "ddown/articlecharact.php",
                dataType: "json",
                data: "idarticletype=" + charact,
                success: function(response)

                {
                    $('#charact_result').html('').select2();
                    //var charactBody = "";
                    //	charactBody = "<option>-- Seleziona --</option>"
                    for (var key in response) {
                        var characteristicNameVar = "<?php echo ($_SESSION['langselect'] == 'it') ? 'name_articlecharacteristic' : 'name_articlecharacteristic_eng'; ?>";
                        var newOption = new Option(response[key][characteristicNameVar], response[key]['idarticlecharacteristic'], false, false);

                        $('#charact_result').append(newOption).trigger('change');
                        //charactBody += "<option value="+ response[key]['idarticlecharacteristic'] +">"+ response[key]['name_articlecharacteristic'] +"</option>";
                        //$("#charact_result").html(charactBody);
                    }
                }


            });
        });
    </script>
    <script>
        // country dependent ajax
        /* $(document).on("change","#articletype_change", function(e){
	e.preventDefault();
		
	var articletype = $("#articletype_change").val();	
		
	$.ajax({
        type: "POST",
        url: "ddown/modelart.php",
		dataType: "json",
        data: "idarticletype="+articletype,
        success: function(response)
        {
			var modelBody = "";
			modelBody = "<option>-- Seleziona --</option>"
			for(var key in response)
			{
				modelBody += "<option value="+ response[key]['idmodelarticle'] +">"+ response[key]['namemodelarticle'] +"</option>";
				$("#model_change").html(modelBody);
			}		
        }
    });
 }); */
        // state dependent ajax
        //  $(document).on("change","#articletype_change", function(e){
        // 	e.preventDefault();

        // 	var charact = $("#articletype_change").val();	

        // 	$.ajax({
        //         type: "POST",
        //         url: "ddown/articlecharact.php",
        // 		dataType: "json",
        //         data: "idarticletype="+charact,
        //         success: function(response)

        // 		{
        //       $('#charact_result').html('').select2();
        // 			//var charactBody = "";
        // 			//charactBody = "<option>-- Seleziona --</option>"
        // 			for(var key in response)
        // 			{
        //                 var newOption = new Option(response[key]['name_articlecharacteristic'], response[key]['idarticlecharacteristic'], false, false);
        //             $('#charact_result').append(newOption).trigger('change');
        // 			//	charactBody += "<option value="+ response[key]['idarticlecharacteristic'] +">"+ response[key]['name_articlecharacteristic'] +"</option>";
        // 				//$("#charact_result").html(charactBody);
        // 			}		
        //         }


        //     });
        //  });
    </script>
    <script>
        $(document).ready(function() {
            // File upload via Ajax
            $("#uploadForm").on('submit', function(e) {
                e.preventDefault();
                $.ajax({
                    type: 'POST',
                    url: 'upload.php',
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function() {
                        /* HIDE CURRENT IMAGE */
                        $('.gallery').html('');
                        /* SHOW LOADING IMAGE */
                        $('#uploadStatus').html('<img src="../images/uploading.gif"/>');
                    },
                    error: function() {
                        $('#uploadStatus').html('<span style="color:#EA4335;">Images upload failed, please try again.<span>');
                    },
                    success: function(data) {
                        $('#uploadForm')[0].reset();
                        $('#uploadStatus').html('<span style="color:#28A74B;">Images uploaded successfully.<span>');
                        $('.gallery').html(data);

                        // $('#cont_photoupload').html(data);
                    }
                });
            });

            // File type validation
            $("#fileInput").change(function() {
                var fileLength = this.files.length;
                var match = ["image/jpeg", "image/png", "image/jpg", "image/gif", "image/bmp"];
                var i;
                for (i = 0; i < fileLength; i++) {
                    var file = this.files[i];
                    var imagefile = file.type.toLowerCase(); // Converti il tipo di file in minuscolo per ignorare le differenze di maiuscole e minuscole
                    if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]) || (imagefile == match[3]) || (imagefile == match[4]))) {
                        alert('Please select a valid image file (JPEG/JPG/PNG/GIF/BMP).');
                        $("#fileInput").val('');
                        return false;
                    }
                }
            });

        });
    </script>
    <script>
        $(document).ready(function() {
            $(".upload-image").click(function() {
                $(".form-horizontal").ajaxForm({
                    target: '.preview'
                }).submit();
            });
            $('#form').parsley();
        });
    </script>

</body>

</html>