<!DOCTYPE html>
<html>
<head>
    <title>Mietanfrage</title>
    <meta charset="utf8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./js/canvas.js"></script>
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <link rel="stylesheet" href="./css/custom.css">
    <link rel="stylesheet" href="./css/style_confirmation.css">
</head>
<body>
    <header class="w3-container">
        <h2>Rückmeldung Mietanfrage</h2>
    </header>
    <main>
        <aside class="w3-container w3-center w3-col l3">
            <canvas id="canvas" width="300px" height="300px" class="confirmation-symbol" aria-label="Symbol, das die Reservation bestätigt oder ablehnt"></canvas>
        </aside>
        <section class="w3-container w3-col l9 confirmation-container">

<!-- generated details --> 
<?php
/* validates parameters received via POST. checks if all are set and they are valid. */
function validateParameters() {
    global $failure_text; // define global variable

    /* VALIDATE RENTAL ARTICLE NUMBER */
    if (!isset($_POST['rental_article_nr'])) { // check if rental art nr is present.
        $failure_text = "Parameter 'rental_art_nr' is required."; return false;
    }
    $rental_art_nr = trim($_POST['rental_article_nr']);
    if(ctype_alpha($rental_art_nr[0]) == false){ // check if first character is a letter. all article numbers start with a letter.
        $failure_text = "Parameter 'rental_art_nr' has to start with a letter."; return false;
    }

    /* VALIDATE START DATE */
    if (!isset($_POST['start_date'])) { // check if start date is present
        $failure_text = "Parameter 'start_date' is required."; return false;
    }     
    $start_date = trim($_POST['start_date']);  // string arrives like "yyyy-mm-dd"
    $start_date_array = explode('-', $start_date);
    if (!checkdate($start_date_array[1], $start_date_array[2], $start_date_array[0])) { // check if start date is a valid date
        $failure_text = "Parameter 'start_date' is not valid."; return false;
    }

    /* VALIDATE END DATE */
    if (!isset($_POST['end_date'])) { // check if end date is present
        $failure_text = "Parameter 'end_date' is required."; return false;
    }
    $end_date = trim($_POST['end_date']);  // string arrives like "yyyy-mm-dd"
    $end_date_array = explode('-', $end_date);
    if (!checkdate($end_date_array[1], $end_date_array[2], $end_date_array[0])) { // check if end date is a valid date
        $failure_text = "Parameter 'end_date' is not valid."; return false;
    }

    /* VALIDATE START DATE IS BEFORE END DATE */
    if (strtotime($end_date) < strtotime($start_date)) {  // check if start date is before end date. same date is accepted.
        $failure_text = "'start_date' must be before 'end_date'."; return false;
    }

    /* VALIDATE START DATE IS AFTER TODAY */
    if (strtotime($start_date) < strtotime('today 00:00')) {  // check if start date in the past. today is ok.
        $failure_text = "'start_date' cannot be in the past."; return false;
    }
    
    /* VALIDATE CUSTOMER NUMBER */
    if (!isset($_POST['customer_nr'])) { // check if customer number is present
        $failure_text = "Parameter 'customer_nr' is required."; return false;
    }
    $customer_nr = intval($_POST['customer_nr']);
    if($customer_nr == 0){ // check if customer number is a number
        $failure_text = "Parameter 'customer_nr' is not a valid number."; return false;
    }

    return true;
}

/* builds html content of the grid-element "confirmation details" a successful response */
function buildSuccessfulConfirmationDetailsSection($start_date, $end_date, $order_num, $customer_num, $material_num, $material_name, $material_desc) {
    echo "<confirmation-details-1><b>Bestellnummer: </b>".$order_num."</confirmation-details-1>";
    echo "<confirmation-details-2><b>Gemietet von: </b>".$start_date." <b>   bis   </b> ".$end_date."</confirmation-details-2>";
    echo "<confirmation-details-3><b>Material: </b>".$material_num." <b> - </b> ".$material_name;
    if($material_desc != null){
        echo "<br><b>Beschreibung: </b>".$material_desc."</confirmation-details-3>";
    } else{
        echo "</confirmation-details-3>";
    }
}

/* builds html content of the grid-element "confirmation details" a failed (unsuccessful) response */
function buildFailedConfirmationDetailsSection($text) {
    echo "<confirmation-details-1>".$text."</confirmation-details-1>";
}

/* main PHP */
// initialize variables
$failure_text = "Unbekannter Fehler";
$material_name = "";
$material_desc = "";
$order_nr = 0;
// get cookie with order nr, otherwise set it to 0
if(isset($_COOKIE['OrderNr'])){
    $order_nr = $_COOKIE['OrderNr'];
}

$rentalSuccess = false;
// start validation of parameters
if(validateParameters()){
    // open SQL connection
    $conn = mysqli_connect("localhost", "root", "", "rental_system");
    if (!$conn) { 
        $failure_text = "Datenbankverbindung fehlgeschlagen.";
    } else {
        do{ // do once loop to be able to make breaks everywhere
            $rental_art_nr = trim($_POST['rental_article_nr']);
            $start_date = trim($_POST['start_date']);
            $end_date = trim($_POST['end_date']);
            $customer_nr = trim(intval($_POST['customer_nr']));

            // check if rental article number exists in article database
            $query = "SELECT * FROM articles WHERE article_number = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 's', $rental_art_nr);
            mysqli_stmt_execute($stmt);
            $res = mysqli_stmt_get_result($stmt);
            if($res){
                $row = mysqli_fetch_assoc($res);  //expecting only one row since article_number is unique in SQL
                if($row == null){  // row == null means there is no material with this number in the database
                    $failure_text = "Materialnummer existiert nicht in Datenbank.";
                    break;
                }
                $material_name = $row['article_name'];
                $material_desc = $row['html_description'];
            } else{
                $failure_text = "Abfrage der Materialnummer fehlgeschlagen.";
                break;
            }

            // check if the material is not yet rented out in the selected time range
            $query = "SELECT * FROM rental_entries WHERE article_number = ? AND start_day <= ? AND end_day >= ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'sss', $rental_art_nr, $end_date, $start_date);
            mysqli_stmt_execute($stmt);
            $res = mysqli_stmt_get_result($stmt);
            if($res){
                $row = mysqli_fetch_assoc($res);
                if($row != null){  // row == null means the material is not rented out in this time range
                    $failure_text = "Material ist bereits vermietet von ".$row['start_day']." bis ".$row['end_day'].".";
                    break;
                }
            } else{
                $failure_text = "Abfrage der vermieteten Artikel fehlgeschlagen.";
                break;
            }

            // if no order number exists yet => create one
            if($order_nr == 0){
                $order_nr = $customer_nr.".".date("YmdHis");  // Create unique order number with customer number and current time (full date + time up to seconds)
                setcookie("OrderNr", $order_nr, time() + 3600);  // valid for 1hr.
            }

            // enter the rental
            $query = "INSERT INTO rental_entries (rental_id, article_number, start_day, end_day, order_number, customer_number) VALUES (NULL, ?, ?, ?, ?, ?);";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'ssssi', $rental_art_nr, $start_date, $end_date, $order_nr, $customer_nr);
            $res = mysqli_stmt_execute($stmt);
            if($res){
                $rentalSuccess = true;
            } else{
                $failure_text = "Eintragen der Mietanfrage fehlgeschlagen. SQL query was:\n".$query;
                break;
            }

        }while(0);

        mysqli_close($conn);  // close database connection if it was connected
    }
}

/* final check for success, generate according defauls section */
if($rentalSuccess){
    echo "<script>drawCheckmark('canvas', 250, 250);</script>";
    echo "<confirmation-header><h3 class=\"success\">Mietanfrage erfolgreich erfasst</h3></confirmation-header>";
    buildSuccessfulConfirmationDetailsSection($start_date, $end_date, $order_nr, $customer_nr, $rental_art_nr, $material_name, $material_desc);
} else{
    echo "<script>drawCross('canvas', 250, 250);</script>";
    echo "<confirmation-header><h3 class=\"failure\">Mietanfrage konnte nicht erfasst werden</h3></confirmation-header>";
    buildFailedConfirmationDetailsSection($failure_text);
}

?>
            <!-- Footer with return link -->
            <confirmation-footer>
                <button class="w3-button" onclick="window.location.href='./rental.html';">
                    Zurück zum Formular
                </button>
            </confirmation-footer>
        </section>
    </main> 
</body>
</html>