<?php

namespace Gateway;
use Connection;
use PDO;


class CharacterGateway extends Gateway
{

    public function create(int $id_character, string $name , string $img_char) : bool
    {
        $query = "
            INSERT INTO caracter
            VALUES(:id_caracter, :caracter, :id_img)
        ";

        return $this -> co -> executeQuery($query, [
            'id_caracter' => array($id_character, PDO::PARAM_INT),
            'caracter' => array($name, PDO::PARAM_STR),
            'id_img' => array($img_char, PDO::PARAM_INT)
        ]);

    }

    public function findById(int $id) : array
    {
        $query = "SELECT * FROM caracter WHERE id_caracter = :id_c";
        $this -> co -> executeQuery($query, ["id_c" => array($id, PDO::PARAM_INT)]);
        return $this -> co -> getResults();
    }

    public function findByName(string $name) : array
    {
        $query = "SELECT * FROM caracter WHERE caracter = :n";
        $this -> co -> executeQuery($query, ["n" => array($name, PDO::PARAM_STR)]);
        return $this -> co -> getResults();
    }

    public function findAll() : array
    {
        $query = "SELECT * FROM caracter ORDER BY caracter ASC";
        $this -> co -> executeQuery($query);
        return $this -> co -> getResults();
    }

    public function delete(int $id) : bool
    {
        $query = "DELETE FROM caracter WHERE id_caracter = :id_c";
        return $this -> co -> executeQuery($query, ["id_c" => array($id, PDO::PARAM_INT)]);
    }

    public function update(int $id_char, string $name, string $img_char) : bool
    {
        $query = "
            UPDATE caracter
            SET caracter = :n, id_img = :i 
            WHERE id_caracter = :id_c
        ";

        return $this -> co -> executeQuery($query, [
            "id_c" => array($id_char, PDO::PARAM_INT),
            "caracter" => array($name, PDO::PARAM_STR),
            "i" => array($img_char, PDO::PARAM_INT)
        ]);
    }

    public function getLastId():int{
        $query = "SELECT id_caracter FROM Caracter;";
        $this -> co -> executeQuery($query);
        $res = $this -> co -> getResults();
        foreach($res as $r){
            $tab[] = $r["id_caracter"];
        }
        $id = 1;
        while(in_array($id,$tab))
        {
            $id=$id+1;
        }
        return $id;
    }


}