<?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;
	}
}
require "../db.php";
if($_SERVER["REQUEST_METHOD"]==="POST"){
    $displayName = htmlspecialchars($_POST['displayName']);
    $owner = htmlspecialchars($_POST['owner']);
    $serverId = htmlspecialchars($_POST['serverId']);
    if(isset($_POST["existingAddress"])){
        $stmt=$pdo->prepare("INSERT INTO warehouse (id,displayName,owner,address) VALUES (?,?,?,?)");
        $stmt->execute([$serverId,$displayName,$owner,htmlspecialchars($_POST['address'])]);
    } else {
        $country = htmlspecialchars($_POST["country"]);
        $city = htmlspecialchars($_POST["city"]);
        $street = htmlspecialchars($_POST["street"]);
        $block = htmlspecialchars($_POST["block"]);
        $flat = htmlspecialchars($_POST["flat"]);
        $postCode = htmlspecialchars($_POST["postCode"]);
        $pdo->beginTransaction();
        $stmt=$pdo->prepare("SELECT id,flat FROM address WHERE country=? AND city=? AND street=? AND block=? AND postCode=?");
        $stmt->execute([$country,$city,$street,$block,$postCode]);
        $row=$stmt->fetch();
        if($stmt->rowCount()==0 || $row['flat']!=$flat){
            $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 warehouse (id,displayName,owner,address) VALUES (?,?,?,LAST_INSERT_ID())");
            $stmt->execute([$serverId,$displayName,$owner]);
        } else {
            $id = $row["id"];
            $stmt=$pdo->prepare("INSERT INTO warehouse (id,displayName,owner,address) VALUES (?,?,?,?)");
            $stmt->execute([$serverId,$displayName,$owner,$id]);
        }
    	$pdo->commit();
    }
    if(isset($_SESSION["bootstrapAdmin"])){
	    header("Location: /storage/shelf/add.php");
	    exit;
    }
}
head("Add warehouse");
nav();
?>
<div>
<h1>Warehouses</h1>
<?php if(isset($_SESSION["bootstrapAdmin"])): ?>
<p>Creating your first warehouse. This is required for any operations to take place.</p>
<?php endif; ?>
<form method="POST">
<table class="table table-striped table-sm">
    <thead>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>owner</td>
            <td>address</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="text" name="serverId"></td>
            <td><input type="text" name="displayName"></td>
            <td>
                <select name="owner">
                    <?php
                        $stmtP=$pdo->prepare("SELECT id,name,surname FROM people");
                        $stmtP->execute([]);
                        while($rowP=$stmtP->fetch()): ?>
                            <option value="<?= $rowP['id'] ?>"><?= $rowP['name'].' '.$rowP['surname'] ?></option>
                        <?php endwhile; ?>
                </select>
            </td>
            <td>
                <label><input type="checkbox" name="existingAddress" id="existingAddress" onInput="switchAddressInputType()">Existing</label>
                <select name="address" style="display: none" id="addressSelect">
                    <?php 
                        $stmt2=$pdo->prepare("SELECT * FROM address");
                        $stmt2->execute([]);
                        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>
                <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>
<a class="btn btn-danger" href="list.php">Cancel</a>  <input type="submit" value="Add" class="btn btn-success">
</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();
?>
