<?php

    /**
     * File for the profile edit action.
     *
     * Implements an action function to be called from the {@see Controller}.
     * 
     * @category Action
     */

    /**
     * Executes the profile update.
     *
     * Reads the POST parameters looking for the following KEYS:
     *  mail
     *  pass + currentPass
     *  api
     * Then it updates the selected info with the prameter vlue. Multiple
     * itemas can be updated at the same time.
     * 
     * @param resource $db Database connection. 
     * @return int|string 0 on success, negative values on error. If the API
     * key has been updated, the new key.
     * @category Action
     */
    function action($db = null){

        $response = null;

        $player = filter_input(INPUT_POST, 'uid');

        if (filter_input(INPUT_POST, "mail")){
            $mail = filter_input(INPUT_POST, 'mail');
            if (!filter_var($mail, FILTER_VALIDATE_EMAIL)){
                return -1;
            }
            $s = $db->prepare('UPDATE player SET mail = :mail WHERE uid = :uid;');
            $s->bindValue(':uid', $player);
            $s->bindValue(':mail', $mail);
            if(!$s->execute()){
                return -2;
            }
        }

        if (filter_input(INPUT_POST, "pass")){
            $pass = sha1(filter_input(INPUT_POST, 'pass'));
            $currentPass = sha1(filter_input(INPUT_POST, 'currentPass'));
            $s = $db->prepare('SELECT COUNT(uid) AS count FROM player WHERE uid = :uid AND password = :currentPass;');
            $s->bindValue(':uid', $player);
            $s->bindValue(':currentPass', $currentPass);
            $q = $s->execute();
            $r = $q->fetchArray(SQLITE3_ASSOC);
            if ($r["count"] != 1){
                return -3;
            }
            $s = $db->prepare('UPDATE player SET password = :pass WHERE uid = :uid AND password = :currentPass;');
            $s->bindValue(':uid', $player);
            $s->bindValue(':pass', $mail);
            $s->bindValue(':currentPass', $currentPass);
            if(!$s->execute()){
                return -4;
            }
        }

        if (filter_input(INPUT_POST, "api")){
            $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $charactersLength = 16;
            $api = '';
            for ($i = 0; $i < $length; $i++) {
                $api .= $characters[rand(0, $charactersLength - 1)];
            }
            $s = $db->prepare('UPDATE player SET api_key = :api WHERE uid = :uid;');
            $s->bindValue(':uid', $player);
            $s->bindValue(':api', $api);
            if(!$s->execute()){
                return -5;
            }
            $response = $api;
        }

        if ($response == null){
            return 0;
        }
        else{
            return $response;
        }
    }
?>
