<?php

/* 
   Purpose: Demo6 - CRUD Operations
   Author: LV
   Date: October 2015
   
   Uses: d6Sql.php
*/
require_once "recipesql.php";
// if $_POST has a filmpk element, call the update method
if (isset($_POST['recipeid'])) {
    updateRecipe($_POST['recipename'], $_POST['dateadded'], $_POST['instructions'], (int) $_POST['categoryid'], (int) $_POST['cooktime'], $_POST['timeofday'], $_POST['timeofyear'], $_POST['userid'], $_POST['allergieid']);
} else {
    addRecipe($_POST['recipename'], $_POST['dateadded'], $_POST['instructions'], (int) $_POST['categoryid'], (int) $_POST['cooktime'], $_POST['timeofday'], $_POST['timeofyear'], $_POST['userid'], $_POST['allergieid']);
}
header("Location: ../home/home.php");
exit;
//if form submitted
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    //connect to db
    $conn = connectToDb($servername, $username, $password, $dbname);
    //clean db of old recipe
    cleanDbTables($recipeId, $conn);
    $userId = getAuthorId($conn, $_SESSION["username"]);
    //if friend does not have account
    if (!checkPrivacy($conn)) {
        exit("Sorry, your friend(s) is not a registered user.");
    }
    $oldRecipeId = $recipeId;
    $recipeName = getRecipeName($conn);
    $allSteps = getAllSteps($conn);
    $privacy = getPrivacy();
    updateRecipe($conn, $recipeName, $author, $allSteps, $privacy, $recipeId);
    //fixFlag($conn, $oldRecipeId);
    //if error in inserting recipe into db
    if ($recipeId < 0) {
        exit("Sorry, could not access database when adding recipe. Please try again.");
    }
    $photoPath = NULL;
    //check if image uploaded here
    if (checkImageUploaded()) {
        $photo = getImageTmpName();
        $photoPath = getImagePath($recipeId);
        if (is_dir("images/" . $recipeId)) {
            $imagePth = getImageNameFromDB($conn, $recipeId);
            unlink($imagePth);
            rmdir("images/" . $recipeId);
        }