<?php

require_once "models/db.php";
require_once "models/Recipe.php";
$recipe = new Recipe();
if ($_POST) {
    $recipe->copyFromRow($_POST);
    if ($recipe->validate()) {
        $recipe->save($dbh);
        echo "save successfully";
        die;
    }
}
// default route, show page for adding
require_once "views/view_recipe.php";
$ing = Ingredient::findAll($dbh);
// Route 1: user comes here to add a new recipe, show them a blank form
$add = true;
// Route 2: user comes here to edit a specific recipe
//   (you'll need to grab that id from the query string)
if (isset($_GET['id'])) {
    $add = false;
    $recipes->find($_GET['id'], $dbh);
}
// Route 3a: user entered a new recipe details and is trying to save it
//   create an object, set values, validate and save, just like in the lab
//   if all is well, send to ShowRecipe to see the added recipe
//   otherwise, back to the edit view with errors!
if ($_POST && !$_GET) {
    $recipes->copyFromRow($_POST);
    if ($recipes->validate()) {
        $recipes->save($dbh);
        header('Location: RecipeList.php?id=' . $recipes->id);
    }
}
// Route 3b: user updated an existing recipe details and is trying to save it
//   create an object, inflate to the proper id, update values, validate and save
//   if all is well, send to ShowRecipe to see the added recipe
//   otherwise, back to the edit view with errors!
if ($_POST && $_GET) {
    $recipes->copyFromRow($_POST);
    if ($recipes->validate()) {
        $recipes->save($dbh);
        header('Location: RecipeList.php?id=' . $recipes->id);
    }
}