/**
 * Updates a project in the db by deleting it (if it exists) and then replacing it
 *
 * @param $p the project to update
 */
function update_dbProjects($p)
{
    if (!$p instanceof Project) {
        error_log('Invalid argument for project->replace_project function call');
        die("Invalid argument for project->replace_project function call");
    }
    delete_dbProjects($p);
    insert_dbProjects($p);
    return true;
}
function testSelectProject()
{
    $newProject = new Project(PROJID, "03-12-14", "Main Building", "UnloadDelivery", 10, 13, 15, "", "notes");
    echo 'will test select_dbProject </br>';
    $result = insert_dbProjects($newProject);
    echo 'result is ' . $result;
    if ($result) {
        echo "add_person inserted </br>";
    } else {
        echo "add_person not inserted</br>";
    }
    $p = select_dbProjects(PROJID);
    if ($p == null) {
        echo 'Retrieve failed</br>';
    } else {
        checkEquals($p->get_id(), PROJID);
        checkEquals($p->get_name(), "UnloadDelivery");
    }
    $res = delete_dbProjects($newProject);
    if ($res == null) {
        echo 'Retrieve failed</br>';
    }
}
/**
 * process_form sanitizes data, concatenates needed data, and enters it all into a database
 */
function process_form($id)
{
    //echo($_POST['first_name']);
    //step one: sanitize data by replacing HTML entities and escaping the ' character
    if (substr($_POST['date'], 0, 2) == 20) {
        $eurodate = explode('-', $_POST['date']);
        $eurodate[0] = substr($eurodate[0], 2, 3);
        $swapdate = [$eurodate[1], $eurodate[2], $eurodate[0]];
        $amerdate = implode('/', $swapdate);
        $mm_dd_yy = $amerdate;
    } else {
        $mm_dd_yy = $_POST['date'];
    }
    error_log("In process form this is " . $mm_dd_yy);
    $address = $_POST['address'];
    //trim(str_replace('\\\'', '\'', htmlentities($_POST['address'])));
    $name = $_POST['name'];
    //trim(htmlentities($_POST['name']));
    $type = $_POST['project_type'];
    $start_time = $_POST['start_time'];
    //ereg_replace("[^0-9]", "", $_POST['start_time']);
    $end_time = $_POST['end_time'];
    //ereg_replace("[^0-9]", "", $_POST['end_time']);
    //$dayOfWeek = trim(htmlentities($_POST['dayOfWeek']));
    $vacancies = $_POST['vacancies'];
    //ereg_replace("[^0-9]", "", $_POST['vacancies']);
    //$persons = trim(htmlentities($_POST['persons']));_log("In process form this is ".$mm_dd_yy);
    $age = $_POST['age'];
    $id = $_POST['old_id'];
    //trim(htmlentities($_POST['old_id']));
    $project_description = $_POST['notes'];
    //trim(htmlentities($_POST['notes']));
    $path = strrev(substr(strrev($_SERVER['SCRIPT_NAME']), strpos(strrev($_SERVER['SCRIPT_NAME']), '/')));
    //step two: try to make the deletion, password change, addition, or change
    if ($_POST['deleteMe'] == "DELETE") {
        $result = select_dbProjects($id);
        if (!$result) {
            echo '<p>Unable to delete. ' . $mm_dd_yy . ' is not in the database. <br>Please report this error to the House Manager.';
        } else {
            //What if they're the last remaining manager account?
            if (strpos($type, 'manager') !== false) {
                //They're a manager, we need to check that they can be deleted
                $managers = getall_type('manager');
                if (!$managers || mysql_num_rows($managers) <= 1) {
                    echo '<p class="error">You cannot remove the last remaining manager from the database.</p>';
                } else {
                    $result = delete_dbProjects($id);
                    echo "<p>You have successfully removed " . mm_dd_yy . " from the database.</p>";
                    if ($id == $_SESSION['_id']) {
                        session_unset();
                        session_destroy();
                    }
                }
            } else {
                $result = delete_dbProjects($id);
                echo "<p>You have successfully removed " . $mm_dd_yy . " from the database.</p>";
                if ($id == $_SESSION['_id']) {
                    session_unset();
                    session_destroy();
                }
            }
        }
    }
    // try to add a new project to the database
    //else {
    if ($_POST['old_id'] == 'new') {
        $id = $mm_dd_yy;
        //check if there's already an entry
        $dup = select_dbProjects($id);
        if ($dup) {
            echo '<p class="error">Unable to add ' . $mm_dd_yy . ' to the database. <br>Another project with the same name is already there.';
        } else {
            $newproject = new Project($mm_dd_yy, $address, $type, $name, $start_time, $end_time, $vacancies, $persons, $age, $project_description);
            $result = insert_dbProjects($newproject);
            $db_date_format = str_replace("/", "-", $mm_dd_yy);
            $update = update_dbDates_projects($db_date_format);
            if (!$update) {
                delete_dbProjects($newproject);
                error_log("Project has not been added");
                echo "<p class='error'>The week of " . $mm_dd_yy . " must be added to the weekly calendar first. Select the Project Calendar tab and then choose Manage Weeks";
            } else {
                if ($_SESSION['access_level'] == 0) {
                    echo "<p>Your application has been successfully submitted.<br>  The House Manager will contact you soon.  Thank you!";
                } else {
                    echo "<p>You have successfully added " . $newproject->get_id() . " to the database.</p>";
                }
            }
        }
    } else {
        $id = $_POST['old_id'];
        $result = delete_dbProjects($id);
        if (!$result) {
            echo '<p class="error">Unable to update ' . $mm_dd_yy . '. <br>Please report this error to the House Manager.';
        } else {
            $newproject = new Project($mm_dd_yy, $address, $name, $start_time, $end_time, $vacancies, $persons, $project_description);
            echo '<p>You have successfully edited <a href="' . $path . 'projectEdit.php?id=' . $id . '"><b>' . $mm_dd_yy . ' </b></a> in the database.</p>';
        }
        add_log_entry('<a href=\\"projectEdit.php?id=' . $id . '\\">' . $mm_dd_yy . ' </a>\'s Project Edit Form has been changed.');
    }
}