<?php
require_once '../models/db.php';

class Dataform
{

    /** @var string */
    protected $data_name;
    /** @var string */
    protected $start_time;
    /** @var string */
    protected $finish_time;
    /** @var bool */
    protected $priority;
    /** @var string */
    protected $periodicity;
    /** @var string */
    protected $file_type;
    /** @var string */
    protected $tmpname;
    /** @var array<Tv> */
    protected $choosed_tvs;


    /** @var string|null */
    protected $error_name = null;
    /** @var string|null */
    protected $error_start = null;
    /** @var string|null */
    protected $error_finish = null;
    /** @var string|null */
    protected $error_priority = null;
    /** @var string|null */
    protected $error_periodicity = null;


    /** @var bool  */
    private $is_submitted = false;
    /** @var bool */
    private $is_valid = false;

    private $conn;



    public function __construct($POST_DATA, $datatype, $FILES_DATA = null)
    {
        // Initialize DB connection
        $db = DB::getInstance();
        $this->conn = $db->getConnection();

        if (!is_null($POST_DATA)) {

            $this->choosed_tvs = [];
            $this->getChoosedTvs($POST_DATA);
            $this->file_type = $datatype;
            if($this->file_type == "Szöveg"){

                $filename = date("Y.m.d_H:i:s");
                $fname = $filename;
                $fname .= ".txt";
                $this->data_name = $fname;

            }else if($this->file_type == "Videó") {

                if (isset($FILES_DATA['file'])) {
                    $this->data_name = $FILES_DATA['file']['name'] ?? null;
                    $this->tmpname = $FILES_DATA['file']['tmp_name'] ?? null;
                }

            }else if($this->file_type == "Kép"){

                if (isset($FILES_DATA['file'])) {
                    foreach($FILES_DATA['file']['name'] as $file){
                        $name_array[] = $file;
                    }
                    $this->data_name = $name_array ?? null;
                    foreach($FILES_DATA['file']['tmp_name'] as $file){
                        $tmp_array[] = $file;
                    }
                    $this->tmpname = $tmp_array ?? null;
                }
            }

            $this->start_time = $POST_DATA['starttime'] ?? null;
            $this->finish_time = $POST_DATA['finishtime'] ?? null;
            $this->priority = $POST_DATA['priority'] ?? null;

            $this->periodicity = $POST_DATA['periodicity'] ?? "";

            $this->is_submitted = isset($POST_DATA['submit']);
        }
    }


    public function validate()
    {
        $this->error_name = $this->validateName() ? null : 'A fájlnév megadása kötelező!';
        $this->error_start = $this->validateStart() ? null : 'A kezdő időpont megadása kötelező!';
        $this->error_finish = $this->validateFinish() ? null : 'A vég időpont megadása kötelező!';
        $this->error_priority = $this->validatePriority() ? null : 'A prioritás mező kitöltése hibás!';
        $this->error_periodicity = $this->validatePeriodicity() ? null : 'A periodikusság mezők kitöltése hibás!';
        $this->is_valid = is_null($this->error_name) && is_null($this->error_start) && is_null($this->error_finish) &&
            is_null($this->error_priority) && is_null($this->error_periodicity);
    }



    /** Name validacio vizsgalata
     * @return bool
     */
    private function validateName()
    {
        if(is_array($this->data_name)){
            $bool = false;
            foreach ($this->data_name as $name){
                if(strlen($name) > 4){
                    $bool = true;
                }else{
                    $bool = false;
                }
            }
            return $bool;
        }
        return strlen($this->data_name) > 4;
    }

    /** Kezdodatum validaciojanak vizsgalata: nem tul nagy, aktualis datumnal nagyobb, rendesen ki van toltve
     * @return bool
     */
    private function validateStart()
    {
        $bigdate = "2100-01-01T01:00:00";
        if(strlen($this->start_time) > 0 && isset($this->start_time) && date("Y.m.d H:i:s") < date("Y.m.d H:i:s", strtotime($this->start_time))
            && date("Y.m.d H:i:s", strtotime($bigdate)) > date("Y.m.d H:i:s", strtotime($this->start_time))){
            return true;
        }
        return false;
    }

    /** Vegdatum validaciojanak vizsgalata: nem tul nagy, kezdeti datumnal nagyobb, rendesen ki van toltve
     * @return bool
     */
    private function validateFinish()
    {
        $bigdate = "2100-01-01T01:00:00";
        if(strlen($this->finish_time) > 0 && isset($this->finish_time)){
            if($this->finish_time > $this->start_time && date("Y.m.d H:i:s", strtotime($bigdate)) > date("Y.m.d H:i:s", strtotime($this->finish_time))){
                return true;
            }
        }
        return false;
    }

    private function validatePriority()
    {
        if (!is_null($this->priority) && ($this->priority == "on" || $this->priority == "off")) {
            return true;
        }
        return false;
    }

    private function validatePeriodicity(){
        return true;
    }


    /**
     * @param $datas
     * @return bool Succes
     */
    public function upload($datas)
    {
        try {
             if($this->isValidActivity()){
                if($this->file_type == "Szöveg") {
                    $data = htmlspecialchars($_POST['txtfile']);
                    $length = strlen($data);
                    if($length == 0) {
                        die("Nem írt semmit a szövegdobozba, így nem lett fájl elmentve!");
                    }else if($length > 2000){
                        die("A karakterszám túl nagy, így nem lett fájl elmentve!");
                    }
                    file_put_contents("../uploads/$this->data_name", $data, FILE_APPEND);
                }else if($this->file_type == "Videó"){
                    $tar_filename = "../uploads/$this->data_name";
                    if(file_exists($tar_filename)){
                        die("A fájl már létezik, a feltöltés nem sikerült!");
                    }
                    move_uploaded_file($this->tmpname, $tar_filename);
                }
                if($this->file_type == "Szöveg" || $this->file_type == "Videó"){

                    $prior = 0;
                    if($this->priority == "on"){
                        $prior = 1;
                    }
                    $statement = $this->conn->prepare('INSERT INTO adatok (fajl_id, mettol, meddig, prioritas, periodikussag) 
                        VALUES (:fajl_id, :mettol, :meddig, :prioritas, :periodikussag)');
                    $statement->bindParam(':fajl_id', $this->data_name);
                    $stime =date("Y-m-d H:i:s", strtotime($this->start_time));
                    $statement->bindParam(':mettol', $stime);
                    $ftime = date("Y-m-d H:i:s", strtotime($this->finish_time));
                    $statement->bindParam(':meddig', $ftime);
                    $statement->bindParam(':prioritas', $prior);
                    $statement->bindParam(':periodikussag', $this->periodicity);
                    $statement->execute();

                    $statement2 = $this->conn->prepare('INSERT INTO felhasznaloi_fajlok (user_shib, adat_id) VALUES (:u_id, :d_id)');

                    $myusername = substr($_SERVER['eppn'], 0, strpos($_SERVER['eppn'], '@'));
                    $statement2->bindParam(':u_id', $myusername);
                    $statement2->bindParam(':d_id', $this->data_name);
                    $statement2->execute();
                $this->tvSaver($this->data_name);

                    return true;
                }

                else if($this->file_type == "Kép"){
                    $countfiles = count($this->data_name);
                    for($i=0; $i<$countfiles; $i++){
                        $f_name = $this->data_name[$i];
                        $tar_filename = "../uploads/$f_name";
                        if(file_exists($tar_filename)){
                            echo "A fájl már létezik ('.$f_name.'), a feltöltés nem sikerült! :(";
                        }else{
                            move_uploaded_file($this->tmpname[$i], $tar_filename);

                            $prior = 0;
                            if($this->priority == "on"){
                                $prior = 1;
                            }

                            $statement = $this->conn->prepare('INSERT INTO adatok (fajl_id, mettol, meddig, prioritas, periodikussag)
                        VALUES (:fajl_id, :mettol, :meddig, :prioritas, :periodikussag)');
                            $statement->bindParam(':fajl_id', $f_name);
                            $stime =date("Y-m-d H:i:s", strtotime($this->start_time));
                            $statement->bindParam(':mettol', $stime);
                            $ftime = date("Y-m-d H:i:s", strtotime($this->finish_time));
                            $statement->bindParam(':meddig', $ftime);
                            $statement->bindParam(':prioritas', $prior);
                            $statement->bindParam(':periodikussag', $this->periodicity);
                            $statement->execute();

                            $statement2 = $this->conn->prepare('INSERT INTO felhasznaloi_fajlok (user_shib, adat_id) VALUES (:u_id, :d_id)');

                            $myusername = substr($_SERVER['eppn'], 0, strpos($_SERVER['eppn'], '@'));
                            $statement2->bindParam(':u_id', $myusername);
                            $statement2->bindParam(':d_id', $f_name);
                            $statement2->execute();

                        $this->tvSaver($f_name);
                        }
                    }
                    return true;
                }
            }
            else{
                echo "Önnek nincs joga adatok feltöltésére!";
            }
        }catch (PDOException $exception){
            return false;
        }

    }

    /** Leellenorzi az adott felhasználó jogosult-e adatfeltöltésre
     * @return bool
     */
    public function isValidActivity(){

        $myusername = substr($_SERVER['eppn'], 0, strpos($_SERVER['eppn'], '@'));
        $user_act = User::getActivity($myusername);
        $good_act = 'share';
        return(strpos($user_act, $good_act) !== false);

    }

    /** ADAT-TV párok kimentéséhez a DB-be
     * @param $POST_DATA
     */

    public function getChoosedTvs($POST_DATA){

        if(count($this->choosed_tvs) == 0){
            $myusername = substr($_SERVER['eppn'], 0, strpos($_SERVER['eppn'], '@'));
            $my_user = User::find($myusername);
            $all_tvs = new Tvlist($my_user->getAccesID());
            $list = $all_tvs->getTvlist();

            for($i = 0; $i < count($list); $i++){
                if(isset($POST_DATA[$list[$i]->getID()])){
                    array_push($this->choosed_tvs, $POST_DATA[$list[$i]->getID()]);
                }
            }
        }

    }

    /**
     * Elmenti a DB megfelelő táblájába a tv-rajta megosztott fájl párosokat
     * @param $data_name
     */
    public function tvSaver($data_name){

        foreach ($this->choosed_tvs as $tv){
            $stmt = $this->conn->prepare('INSERT INTO tv_adat (tv_id, fajl_id) VALUES (:t_id, :f_id)');
            $stmt->bindParam('t_id', $tv);
            $stmt->bindParam('f_id', $data_name);
            $stmt->execute();
        }
    }


    /**
     * GETTERS
     */

    public function isSubmitted()
    {
        return $this->is_submitted;
    }

    public function isValid()
    {
        return $this->is_valid;
    }

    public function getNameValue()
    {
        return $this->data_name;
    }

    public function getNameError()
    {
        return $this->error_name;
    }

    public function getStartValue()
    {
        return $this->start_time;
    }

    public function getStartError()
    {
        return $this->error_start;
    }

    public function getFinishValue()
    {
        return $this->finish_time;
    }

    public function getFinishError()
    {
        return $this->error_finish;
    }

    public function getPriorityValue()
    {
        return $this->priority == 'on' ? 'on' : 'off';
    }

    public function getPriorityError()
    {
        return $this->error_priority;
    }

    public function getPeriodicityValue()
    {
        return $this->periodicity;
    }

    public function getPeriodicityError()
    {
        return $this->error_periodicity;
    }

}
