<?php

class Runs extends Page {

    function setMenu()
    {
        // $this->menu_text = 'Läufe';
        // $this->menu_image = 'fas fa-running';
        // $this->menu_priority = 3;
    }

    function overview()
    {
        $run = new Run();
        $rid = $this->params[0];
        if(!$run->exists($rid))
            return partial('error.html', ['errorMessage' => 'Dieser Lauf existiert nicht']);
        $run->load($rid);
        $t = new Tournament();
        $t->load($run->data['tournament']);

        $res = new Result();
        $results = $res->getDataOfRun($rid);


        $this->set('admin',$t->amIAdmin());
        $this->set('tournament', $t->data);
        $this->set('tournament_id', $run->data['tournament']);
        $this->set('results', $results);
        $this->set('run', $run->data);
        $this->set('run_id', $rid);
        $this->set('template', 'run.html');
    }

    function addresults()
    {
        $rid = $this->params[0];
        $run = new Run();
        if(!$run->exists($rid))
            return partial('error.html', ['errorMessage' => 'Dieser Lauf existiert nicht']);
        $run->load($rid);
        $t = new Tournament();
        $tid = $run->data['tournament'];
        $t->load($tid);
        if(!$t->amIAdmin() && !$t->isMyEvent($tid))
            return partial('error.html', ['errorMessage' => 'Du bist in diesem Turnier nicht angemeldet']);
        else
        {
            $this->set('tournament', $t->data);
            $this->set('tournament_id', $tid);
            $this->set('run', $run->data);
            $this->set('run_id', $rid);
            $this->set('template', 'edit_result.html');
        }
    }

    function validateresults()
    {
        $rid = $_REQUEST['run_id'];
        $run = new Run();
        if(!$run->exists($rid))
            return partial('error.html', ['errorMessage' => 'Dieser Lauf existiert nicht']);
        $run->load($rid);
        $t = new Tournament();
        $tid = $run->data['tournament'];
        $t->load($tid);
        $res = new Result();
        if($_REQUEST['result_id'])
        {
            if(!$res->exists($_REQUEST['result_id']))
                return partial('error.html', ['errorMessage' => 'Dieses Ergebnis existiert nicht']);
            $res->load($_REQUEST['result_id']);
            if(!$res->data['run']==$rid)
                return partial('error.html', ['errorMessage' => 'Dieses Ergebnis gehört nicht zu diesem Lauf']);
        }
        else
            $res->id = gen_ulid();
        if(!$t->amIAdmin() && !$t->isMyEvent($tid))
            return partial('error.html', ['errorMessage' => 'Du bist in diesem Turnier nicht angemeldet']);
        else
        {
            $dogid = $_REQUEST['dog'];
            if(!$dogid || $dogid=='false')
                return partial('error.html', ['errorMessage' => 'Du musst einen Hund auswählen']);
            $dog = new Dog();
            if(!$dog->exists($dogid))
                return partial('error.html', ['errorMessage' => 'Dieser Hund existiert nicht']);
            else if(!$dog->isMyDog($dogid))
                return partial('error.html', ['errorMessage' => 'Dieser Hund gehört nicht dir']);

            $res->dog = $dogid;
            $res->disqualified = $_REQUEST['disqualified'];
            $res->refusals = $_REQUEST['refusals'];
            $res->timefaults = $_REQUEST['time_faults'];
            $res->runtime = $_REQUEST['time'];
            $res->penalties = $_REQUEST['penalties'];
            $res->speed = $_REQUEST['time_speed'];
            $res->rating = $_REQUEST['bewertung'];
            $res->points = $_REQUEST['points'];
            $res->ranking = $_REQUEST['rank'];
            $res->public = $_REQUEST['public'];
            $res->tournament = $tid;
            $res->run = $rid;
            $res->user = $_SESSION['user']->id;

            if($_FILES['photos'])
            {
                foreach($_FILES['photos']['tmp_name'] as $key => $tmp_name)
                {
                    try{
                        $url = pictShareFormValidateAndUpload($_FILES['photos'],$key);
                        $res->data['photos'][] = $url;
                    }
                    catch(Exception $e)
                    {
                        return partial('error.html', ['errorMessage' => 'Fehler beim Upload des Fotos: '.$e->getMessage()]);
                    }

                }

                //filter out unique values so we don't have double entries
                $res->data['photos'] = array_unique($res->data['photos']);
            }

            try{
                $resid = $res->save();

                if(!in_array($resid, $run->data['results']))
                {
                    $run->data['results'][] = $resid;
                    $run->save();
                }
            }
            catch(Exception $e)
            {
                return partial('error.html', ['errorMessage' => 'Fehler beim Speichern des Ergebnisses: '.$e->getMessage()]);
            }

            $this->redirect('/runs/overview/'.$rid);
        }
    }

    function add()
    {
        $tournament = $this->params[0];
        $t = new Tournament();
        if(!$t->exists($tournament))
            return partial('error.html', ['errorMessage' => 'Dieses Turnier existiert nicht']);
        $t->load($tournament);
        if(!$t->amIAdmin($tournament))
            return partial('error.html', ['errorMessage' => 'Du bist kein Admin dieses Turniers']);
        else
        {
            $this->set('tournament', $t->data);
            $this->set('tournament_id', $tournament);
            $this->set('template', 'edit_run.html');
        }
    }

    function edit()
    {
        $rid = $this->params[0];
        $r = new Run();
        $t = new Tournament();
        if(!$r->exists($rid))
            return partial('error.html', ['errorMessage' => 'Dieser Run existiert nicht']);
        $r->load($rid);
        $tournament = $r->data['tournament'];
        $t->load($tournament);
        if(!$t->amIAdmin($tournament))
            return partial('error.html', ['errorMessage' => 'Du bist kein Admin dieses Turniers']);
        else
        {
            $this->set('tournament', $t->data);
            $this->set('tournament_id', $tournament);
            $this->set('run_id',$rid);
            $this->set('run',$r->data);
            $this->set('template', 'edit_run.html');
        }
    }

    function validate()
    {
        
        if($_REQUEST['submit'])
        {
            $t = new Tournament();
            
            if(!$t->exists($_REQUEST['tournament_id']))
                return partial('error.html', ['errorMessage' => 'Dieses Turnier existiert nicht']);
            $t->load($_REQUEST['tournament_id']);
            
            if(!$t->amIAdmin($_REQUEST['tournament_id']))
                return partial('error.html', ['errorMessage' => 'Du bist kein Admin dieses Turniers']);
                
            $run = new Run();
            if($_REQUEST['run_id'])
            {
                if(!$run->exists($_REQUEST['run_id']))
                    return partial('error.html', ['errorMessage' => 'Dieser Lauf existiert nicht']);
                $run->load($_REQUEST['run_id']);
                if(!$run->data['tournament']==$t->id)
                    return partial('error.html', ['errorMessage' => 'Dieser Lauf gehört nicht zu diesem Turnier']);
            }
            else
                $run->id = gen_ulid();

            
    
            $run->data['tournament'] = $_REQUEST['tournament_id'];
            $run->data['name'] = trim($_REQUEST['name']);
            $run->data['category'] = $_REQUEST['category'];
            $run->data['length'] = $_REQUEST['length'];
            $run->data['time_standard'] = $_REQUEST['time_standard'];
            $run->data['time_max'] = $_REQUEST['time_max'];
            $run->data['referee'] = $_REQUEST['referee'];

            try{
                $runid = $run->save();
            }
            catch(Exception $e)
            {
                return partial('error.html', ['errorMessage' => 'Fehler beim Speichern des Laufs: '.$e->getMessage()]);
            }

            if(!in_array($runid, $t->data['runs']))
            {
                $t->data['runs'][] = $runid;
                $t->save();
            }

            if($_REQUEST['submit']=='forward')
            {
                $this->redirect('/runs/addresults/'.$runid);
            }
            else
                $this->redirect('/tournaments/event/'.$t->id);
        }
        else return partial('error.html', ['errorMessage' => 'Fehler beim Speichern des Laufs']);
    }

    function maySeeThisPage() {
        if($_SESSION['user']) //wenn eingeloggt, kein problem
            return true;
        else return false;
    }
}