<?php
session_start();

if (!isset($_SESSION['phone'])) {
    header('Location: index.php?error&num='.urlencode($_REQUEST['phone']));
    die();
}

function suche_kunde($number) {
        if (! $number) {
            return NULL;
        }
        $kundenliste = json_decode(file_get_contents('../kunden.json'), TRUE);
        foreach ($kundenliste as $k) {
                foreach ($k['kontakt'] as $kon) {
                        if ($kon['wert'] == $number) {
                                return $k;
                        }
                }
        }
}

$kunde = suche_kunde($_SESSION['phone']);
if ($kunde) {
    $_SESSION['kundennr'] = $kunde['id'];
} else {
    unset($_SESSION['kundennr']);
}

$content = '';
if (isset($_REQUEST['error'])) {
    $content .= '<div class="panel panel-danger">
    <div class="panel-heading">Fehler</div>
    <div class="panel-body">Bitte geben Sie Ihren Namen an.</div>
    </div>';
}

$headline = 'Adresse eingeben';
if ($kunde) {
    $content .= '
        <p>Wir haben Ihre Telefonnummer erkannt und diese Felder schon einmal vorausgefüllt. Bitte prüfen Sie die Angaben und ändern Sie die Inhalte bei Bedarf.</p>
    ';
} else { 
    $content .= '
        <p>Bitte geben Sie in diesem Schritt Ihre Daten ein.</p>
    ';
}
if (!$kunde) {
    $kunde = array('nachname' => '', 'vorname' => '', 'strasse' => '', 'plz' => '', 'ort' => '');
}

$content .= '
    <form class="form" action="save.php" method="post">
    <input type="hidden" name="form" value="address">
    <div class="form-group form-group-lg row">
        <div class="col-sm-6"><input class="form-control" id="fname" name="fname" type="text" placeholder="Vorname" autocomplete="given-name" value="'.$kunde['vorname'].'"></div>
        <div class="col-sm-6"><input class="form-control" id="lname" name="lname" type="text" placeholder="Nachname" autocomplete="family-name" value="'.$kunde['nachname'].'"></div>
    </div>
    <div class="form-group form-group-lg row">
        <div class="col-sm-12"><input class="form-control" id="address" name="address" type="text" placeholder="Straße" autocomplete="street-address" value="'.$kunde['strasse'].'"></div>
    </div>
    <div class="form-group form-group-lg row">
        <div class="col-sm-4"><input class="form-control" id="zip" name="zip" type="text" placeholder="PLZ" autocomplete="postal-code" value="'.$kunde['plz'].'"></div>
        <div class="col-sm-8"><input class="form-control" id="city" name="city" type="text" placeholder="Ort" autocomplete="locality" value="'.$kunde['ort'].'"></div>
    </div>
      <div class="form-group form-group-lg">
        <div><input class="btn btn-primary btn-lg" type="submit" value="Weiter &gt;"></div>
    </div>
    </form>

';


include("template.php");