<?php

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

class Tv
{
    /** @var string */
    protected $name;


    /**
     * Tv constructor
     * @param string $name

     */
    public function __construct($name)
    {
        $db = DB::getInstance();
        $this->conn = $db->getConnection();
        $this->name = $name;
    }

    /**
     * Find a tv in the DB by ID. The function returns the TV (as object) or null if ID not found
     * @param string $tvname
     * @return Tv|null
     */
    public static function find($tvname)
    {
        // Initialize DB connection
        $db = DB::getInstance();
        $conn = $db->getConnection();

        // Select all products from DB
        $stmt = $conn->prepare('SELECT tv_id FROM tv WHERE tv_id = :id');
        $stmt->bindParam(':id', $tvname);
        $stmt->execute();

        if ($row = $stmt->fetch(PDO::FETCH_COLUMN)) {
            return new Tv($row);
        } else {
            return null;
        }
    }


    /**
     * GETTER
     */
    public function getId(){
        return $this->name;
    }


    /**
     * Adott TV törlése
     */
    public function delete(){

        $stmt2 = $this->conn->prepare('DELETE FROM jogosultsag_tv WHERE tv_id = :id');
        $stmt2->bindParam(':id', $this->name);
        $stmt2->execute();

        $stmt2 = $this->conn->prepare('DELETE FROM tv_adat WHERE tv_id = :id');
        $stmt2->bindParam(':id', $this->name);
        $stmt2->execute();

        $stmt = $this->conn->prepare('DELETE FROM tv WHERE tv_id = :id');
        $stmt->bindParam(':id', $this->name);
        $stmt->execute();

    }

    /**
     * SETTER
     * @param string $new_name
     * @param string $jog_id
     */
    public function setTv($new_name, $jog_id){

        $stmt2 = $this->conn->prepare('UPDATE jogosultsag_tv SET tv_id= :id, jogosultsag_id: :j_id WHERE tv_id = :old_id');
        $stmt2->bindParam(':old_id', $this->name);
        $stmt2->bindParam(':id', $new_name);
        $stmt2->bindParam(':j_id', $jog_id);
        $stmt2->execute();

        $stmt = $this->conn->prepare('UPDATE tv SET tv_id = :id WHERE tv_id = :old_id');
        $stmt->bindParam(':old_id', $this->name);
        $stmt->bindParam(':id', $new_name);
        $stmt->execute();

        $this->name = $new_name;
    }


    /**Összes jogosultság ID-t visszaadja, ha aki épp használja az eszközt az Admin
     * @param $username
     * @return array
     */
    public function getAllActId($username){
        if(User::isAdmin($username)){
            $stmt = $this->conn->prepare('SELECT id FROM jogosultsagok');
            $stmt->execute();
            $all_id = $stmt->fetchAll(PDO::FETCH_COLUMN);
            return $all_id;
        }
    }
}