<?php
namespace infozone\ads\event;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class listener implements EventSubscriberInterface
{
    protected $db;
    protected $template;
    protected $config;
    protected $user;
    protected $root_path;
    protected $php_ext;

    public function __construct($db, $template, $config, $user, $root_path, $php_ext)
    {
        $this->db = $db;
        $this->template = $template;
        $this->config = $config;
        $this->user = $user;
        $this->root_path = $root_path;
        $this->php_ext = $php_ext;
    }

    public static function getSubscribedEvents()
    {
        return [
            'core.page_header' => 'inject_ads',
        ];
    }

    public function inject_ads($event)
    {
        // Load all enabled slots (or all slots if not configured yet)
        $sql = 'SELECT slot_key, type, image_path, link_url, html_code, enabled, start_at, end_at
                FROM ' . $this->db->get_table_prefix() . 'infozone_ad_slots';
        // If table does not exist yet (extension not migrated), fail silently.
        try {
            $result = $this->db->sql_query($sql);
        } catch (\Exception $e) {
            return;
        }

        $ads = [];
        $now = time();

        while ($row = $this->db->sql_fetchrow($result))
        {
            $active = (int)$row['enabled'] === 1;

            if (!empty($row['start_at']) && (int)$row['start_at'] > 0 && $now < (int)$row['start_at']) {
                $active = false;
            }
            if (!empty($row['end_at']) && (int)$row['end_at'] > 0 && $now > (int)$row['end_at']) {
                $active = false;
            }

            $html = '';
            if ($active) {
                if ($row['type'] === 'html' && !empty($row['html_code'])) {
                    $html = $row['html_code'];
                } else if ($row['type'] === 'image' && !empty($row['image_path'])) {
                    $img = htmlspecialchars($row['image_path']);
                    $href = !empty($row['link_url']) ? htmlspecialchars($row['link_url']) : '#';
                    $html = '<a class="iz-ad-link" href="' . $href . '" rel="nofollow sponsored" target="_blank"><img class="iz-ad-img" src="' . $img . '" alt="Advertisement"></a>';
                }
            }

            $ads[$row['slot_key']] = $html;
        }
        $this->db->sql_freeresult($result);

        $this->template->assign_var('IZ_ADS', $ads);
        $this->template->assign_var('IZ_ADVERTISE_URL', append_sid("{$this->root_path}app.{$this->php_ext}/advertise"));
    }
}
