<?php
namespace Gateway;
use Connection;

class SourceGateway {

    private Connection $co;

    public function __construct(Connection $co)
    {
        $this -> co = $co;
    }

    public function create(sourceEntity $s) : bool
    {
        $query = "
            INSERT INTO Source
            VALUES(:id_source, :title, :date)
        ";

        return $this -> co -> executeQuery($query, [
            "id_source" => array($s->getIdSource(), PDO::PARAM_INT),
            "title" => array($s->getTitle(), PDO::PARAM_STR),
            "date" => array($s->getDate(), PDO::PARAM_STR)
        ]);
    }

    public function findById(int $id) : array
    {
        $query = "SELECT * FROM Source WHERE id_source = :id";

        $this -> co -> executeQuery($query, array("id_source" => array($id, PDO::PARAM_INT)));
        return $res = $this -> co -> getResults();
    }

    public function findByTitle(string $t) : array
    {
        $query = "SELECT * FROM Source WHERE title = :t";

        $this -> co -> executeQuery($query, ["title" => array($t, PDO::PARAM_STR)]);
        return $res = $this -> co -> getResults();

        // if ($res)
        //     return new sourceEntity(
        //         $res["id_source"],
        //         $res["title"],
        //         $res["date"]
        //     );
        // return null;
    }

    public function findByDate(string $d) : array
    {
        $query = "SELECT * FROM Source WHERE date = :d";

        $this -> co -> executeQuery($query, ["date" => array($d, PDO::PARAM_STR)]);
        $res = $this -> co -> getResults();

        if ($res)
            return new sourceEntity(
                $res["id_source"],
                $res["title"],
                $res["date"]
            );
        return null;
    }

    public function findAll() : array
    {
        $query = "SELECT * FROM Source";

        $this -> co -> executeQuery($query);
        $res = $this -> co -> getResults();

        $sources = [];

        foreach ($res as $source) {
            $sources[] = new sourceEntity(
                $source["id_source"],
                $source["title"],
                $source["date"]
            );
        }
        return $sources;
    }

    public function delete(int $id) : bool
    {
        $query = "DELETE FROM Source WHERE id_source = :id_s";

        $this -> co -> executeQuery($query, ["id_s" => array($id, PDO::PARAM_INT)]);
    }

    public function update(sourceEntity $s) : bool
    {
        $query = "
            UPDATE Source 
            SET title = :t, date = :d 
            WHERE id_source = :id_s
        ";
        return $this->co->executeQuery($query, [
            "id_s" => array($s -> getIdSource(), PDO::PARAM_INT),
            "t" => array($s -> getTitle(), PDO::PARAM_STR),
            "d" => array($s -> getDate(), PDO::PARAM_STR)
        ]);
    }

}
