<?php
require_once "../base.php";
session_start();
if(!isset($_SESSION["bootstrapAdmin"])){
    if(!isset($_SESSION["userId"]))header("Location: /storage/login.php");
    if(!isAdmin($_SESSION["userId"])){
        http_response_code(403);
        print("Forbidden, you don't have access to this resource.");
        exit;
    }
}
head("Add person");
nav();
?>
<div>
<h1>People</h1>
<?php if(isset($_SESSION["bootstrapAdmin"])):?>
<p>Creating your person identifier. This will be used to identify you as a physical person in the system.</p>
<?php endif;
require "../db.php";
if($_SERVER["REQUEST_METHOD"]==="POST"){
    $name = htmlspecialchars($_POST['name']);
    $surname = htmlspecialchars($_POST['surname']);
    if(isset($_POST["existingAddress"])){
        $stmt=$pdo->prepare("INSERT INTO people (name,surname,address) VALUES (?,?,?)");
        $stmt->execute([$name,$surname,htmlspecialchars($_POST['address'])]);
    } else {
        $country = htmlspecialchars($_POST["country"]);
        $city = htmlspecialchars($_POST["city"]);
        $street = htmlspecialchars($_POST["street"]);
        $block = htmlspecialchars($_POST["block"]);
        $flat = htmlspecialchars($_POST["flat"])!==''?htmlspecialchars($_POST["flat"]):null;
        $postCode = htmlspecialchars($_POST["postCode"]);
        $pdo->beginTransaction();
        $stmt=$pdo->prepare("SELECT id FROM address WHERE country=? AND city=? AND street=? AND block=? AND flat=? AND postCode=?");
        $stmt->execute([$country,$city,$street,$block,$flat,$postCode]);
        if($stmt->rowCount()==0){
            $stmt=$pdo->prepare("INSERT INTO address (country, city, street, block, flat, postCode) VALUES (?,?,?,?,?,?)");
            $stmt->execute([$country,$city,$street,$block,$flat,$postCode]);
            $stmt=$pdo->prepare("INSERT INTO people (name,surname,address) VALUES (?,?,LAST_INSERT_ID())");
            $stmt->execute([$name,$surname]);
        } else {
            $id = $stmt->fetch()["id"];
            $stmt=$pdo->prepare("INSERT INTO people (name,surname,address) VALUES (?,?,?)");
            $stmt->execute([$name,$surname,$id]);
        }
	$pdo->commit();

	if(isset($_SESSION["bootstrapAdmin"])){
		header("Location: /storage/admin/add.php");
	}
    }
}
?>
<form method="POST">
<table class="table table-striped table-sm">
    <thead>
        <tr>
            <td>name</td>
            <td>surname</td>
            <td>address</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="text" name="name"></td>
            <td><input type="text" name="surname"></td>
	    <td>
		<?php 
                $stmt2=$pdo->prepare("SELECT * FROM address");
		$stmt2->execute([]);
		if($stmt2->rowCount()>0):
		?>
		<label><input type="checkbox" name="existingAddress" id="existingAddress" onInput="switchAddressInputType()">Existing</label>
                <select name="address" style="display: none" id="addressSelect">
			<?php 
                        while($row2=$stmt2->fetch()): ?>
                            <option value="<?= $row2['id'] ?>"><?= $row2['street'].' '.$row2["block"].(isset($row2["flat"])?'/'.$row2["flat"]:"").' '.$row2["postCode"].' '.$row2["country"]?></option>
                        <?php endwhile; ?>
		</select>
		<?php endif; ?>
                <div id="addressInput">
                    <input type="text" name="country" placeholder="country">
                    <input type="text" name="city" placeholder="city">
                    <input type="text" name="street" placeholder="street">
                    <input type="text" name="block" placeholder="block">
                    <input type="number" name="flat" placeholder="flat">
                    <input type="text" name="postCode" placeholder="00-000">
                </div>
            </td>
        </tr>
    </tbody>
</table>
<input type="submit" value="Add" class="btn btn-success">
<?php
if(isset($_SESSION["bootstrapAdmin"])){
    $stmt=$pdo->prepare("SELECT id FROM people LIMIT 1");
    $stmt->execute([]);
    if($stmt->rowCount()>0){
        print("<a href=\"/storage/admin/add.php\" class=\"btn btn-primary\">Skip</a>");
    }
}
?>
</form>
</div>
<script>
    function switchAddressInputType() {
        if(document.getElementById("existingAddress").checked){
            document.getElementById("addressSelect").style.display = "inline";
            document.getElementById("addressInput").style.display = "none";
        } else {
            document.getElementById("addressSelect").style.display = "none";
            document.getElementById("addressInput").style.display = "block";
        }
    }
</script>
<?php
footer();
?>
