<?php

namespace controllers;

use \Exception;
use \PDOException;
use models\ModelPlayer;

class ControllerUserPlayers
{
    private $mdPlayer;

    private $twig;
    private $vues;

    function __construct()
    {
        global $vues, $twig;
        session_start();
        $this->mdPlayer = new ModelPlayer();
        try {
            if($_SESSION["idPlayerConnected"] != null){
                $this->twig =$twig;
                $this->vues = $vues;
            }
            else {
                header("Location:/loginPlayer");
            }
        } catch (PDOException $e) {
            // Gérez les erreurs PDO ici
        } catch (Exception $e2) {
            // Gérez d'autres erreurs ici
        }
    }

    function delete($param) {
        $this->mdPlayer->deletePlayerByID($param["id"]);
        $_SESSION["idPlayerConnected"]=null;
        header("Location:/");
    }

    public function add($param) {
        $nickname = $_POST['nickname'];
        $password = $_POST['password'];

        $Player = [
            'nickname' => $nickname,
            'password' => $password,
        ];

        var_dump($Player);

        $this->mdPlayer->addPlayer($Player);

        header("Location:/loginPlayer");
    }

    function updatemodal($param) {
        
        $player = $this->mdPlayer->getPlayerByID($param["id"]);
        echo $this->twig->render($this->vues["userPlayerModal"], [
            'player' => $player,
        ]);
    }

    function update($param) {
        $id = $_POST['id'];
        $password = $_POST['password'];
        if (!isset($password) || empty($password) || !isset($id) || empty($id) || !is_numeric($id) || $id < 0 || empty(trim($password)) || empty(trim($id))) {
            $_SESSION["error"] = "Veuillez remplir tous les champs correctement";
            var_dump($id,$password);
            header("Location:/userStatus");
        } else {
            $this->mdPlayer->updatePlayerPassword($id,$password);
            header("Location:/userStatus");
        }
    }
}