<?php
class Like {
    private $conn;
    private const table_name = "gallery_like";

    public $id;
    public $gallery_id;
    public $user_id;
    public $created;

    public function __construct($db){
        $this->conn = $db;
    }

    function create() {
        $query = "INSERT INTO " . self::table_name . "
            SET gallery_id=:galleryId, user_id=:userId";
        
        // prepare query
        $stmt = $this->conn->prepare($query);
        
        $this->created=(new \DateTime())->format('Y-m-d H:i:s');
        
        // bind values
        $stmt->bindParam(":userId", $this->user_id);
        $stmt->bindParam(":galleryId", $this->gallery_id);
        
        // execute query
        if($stmt->execute()){
            return $this->conn->lastInsertId();
        }
        return false;
    }

	static function delete($db, $id) {
		$query = "DELETE FROM " . self::table_name . " WHERE id = :id";
		$stmt = $db->prepare($query);
		$stmt->bindParam(":id", $id);
		if($stmt->execute()){
            return true;
        }
        return false;
	}

	public static function createFromRow($row, $prefix = '') {
		if ($prefix) 
			$prefix = $prefix . '_';
		else
			$prefix = '';

		if (!$row[$prefix . 'id'])
			return null;

		$instance = new self(null);
		$instance->id = $row[$prefix . 'id'];
		$instance->gallery_id = $row[$prefix . 'gallery_id'];
		$instance->user_id = $row[$prefix . 'user_id'];
		$instance->created = $row[$prefix . 'created'];
		return $instance;
	}

	public static function get($db, $uid, $gid) {
		$q = "
			SELECT *
			FROM " . self::table_name . "
			WHERE
				user_id = :uid AND
				gallery_id = :gid
		";
		$stmt = $db->prepare($q);
        $stmt->bindParam(":uid", $uid);
        $stmt->bindParam(":gid", $gid);
		$stmt->execute();

		$row = $stmt->fetch(PDO::FETCH_ASSOC);
		if ($row)
			return self::createFromRow($row);
		return false;
	}

	public static function byUserAndId($db, $uid, $id) {
		$q = "
			SELECT *
			FROM " . self::table_name . "
			WHERE
				user_id = :uid AND
				id = :id
		";
		$stmt = $db->prepare($q);
        $stmt->bindParam(":uid", $uid);
        $stmt->bindParam(":id", $id);
		$stmt->execute();

		$row = $stmt->fetch(PDO::FETCH_ASSOC);
		if ($row)
			return self::createFromRow($row);
		return false;
	}


}