<?php

    function generateApi($length = 16) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    function action($db = null){
        global $AREA_TYPE;
        global $DIFFICULTY;
        global $SCENARIO;
        global $DUNGEON;
        global $ELEMENTAL_RIFT_DUNGEON;
        global $LABYRINTH_STAGES;
        global $UID;

        $response = null;

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

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

        if (filter_input(INPUT_POST, "pass")){
            $pass = sha1(filter_input(INPUT_POST, 'pass'));
            $currentPass = sha1(filter_input(INPUT_POST, 'currentPass'));
            // TODO: Validate current
            $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 -2;
            }
        }

        if (filter_input(INPUT_POST, "api")){
            $api = generateApi();
            $s = $db->prepare('UPDATE player SET api_key = :api WHERE uid = :uid;');
            $s->bindValue(':uid', $player);
            $s->bindValue(':api', $api);
            if(!$s->execute()){
                return -3;
            }
            $response = $api;
        }

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