<?php
    /**
     * File for the run team saving action.
     *
     * Implements an action function to be called from the {@see Controller}.
     * 
     * @category Action
     */

    /**
     * Saves a run party as a team.
     *
     * Reads the POST parameters looking for the following KEYS:
     *  uid
     *  run
     *  name
     *  description
     * Validates the data and creates the team in the database.
     * 
     * @param resource $db Database connection. 
     * @return int 0 on success, negative values on error.
     * @category Action
     */
    function action($db = null){
        $player = filter_input(INPUT_POST, 'uid');
        $run = filter_input(INPUT_POST, 'run');
        $name = filter_input(INPUT_POST, 'name');
        $description = filter_input(INPUT_POST, 'description');
        if ($name == null || strlen($name) == 0){
            return -1;
        }
        $s = "SELECT CASE WHEN MAX(id) IS NULL THEN 1 ELSE MAX(id) + 1 END AS id FROM team;";
        $q = $db->query($s);
        $r = $q->fetchArray(SQLITE3_ASSOC);
        $team_id = $r["id"];
        $s = "SELECT run.area AS area, run.stage AS stage, run.difficulty AS difficulty, k_area.type AS area_type FROM run, k_area WHERE run.uid = '$player' AND run.id = '$run' AND k_area.id = run.area AND run.helper = 0;";
        $q = $db->query($s);
        $r = $q->fetchArray(SQLITE3_ASSOC);
        if (!$r){
            return -2;
        }
        $statement = $db->prepare('INSERT INTO team (uid, id, name, description, area_type, area, stage, difficulty) VALUES (:uid, :id, :name, :description, :area_type, :area, :stage, :difficulty);');
        $statement->bindValue(':uid', $player);
        $statement->bindValue(':id', $team_id);
        $statement->bindValue(':name', $name);
        $statement->bindValue(':description', $description);
        $statement->bindValue(':area_type', $r["area_type"]);
        $statement->bindValue(':area', $r["area"]);
        $statement->bindValue(':stage', $r["stage"]);
        $statement->bindValue(':difficulty', $r["difficulty"]);
        $res = $statement->execute();
        if (!$res){
            return -3;
        }
        $s = "SELECT unit FROM run_party WHERE run = $run AND unit IS NOT NULL;";
        $q = $db->query($s);
        while ($r = $q->fetchArray(SQLITE3_ASSOC)){
            $s = "INSERT INTO team_unit VALUES ('$team_id', '" . $r["unit"] . "');";
            $db->query($s);
        }
        return 0;
    }
?>

