<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele De Nobili
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin\Updates;

use Doctrine\DBAL\ParameterType;
use Updates\BaseUpdate;

/**
 * Update155
 *
 * Ripristina i permessi della dashboard che non erano mai stati inseriti nella procedura di installazione di Pongho.
 */
class Update155 extends BaseUpdate
{
    /**
     * {@inheritdoc}
     */
    public function commit()
    {
        $permit_keys = [
            'admin.dashboard.widget_visitsreport',
            'admin.dashboard.widget_locationsreport',
            'admin.dashboard.widget_keywordsreport',
            'admin.dashboard.widget_pageviewsreport',
            'admin.dashboard.widget_statsreport',
        ];

        $admin_role_id = 3;

        $key_field_name = $this->connection->quoteIdentifier('key');

        $permit_sth = $this->connection->prepare(
            $this->connection->createQueryBuilder()->select('*')
                ->from('pongho_permits', 'p')
                ->where('p.key = ?')
                ->getSQL()
        );

        $permit_role_sth = $this->connection->prepare(
            $this->connection->createQueryBuilder()->select('*')
                ->from('pongho_permits_roles', 'pr')
                ->where('pr.permit_id = ? AND pr.role_id = ' . $admin_role_id)
                ->getSQL()
        );

        foreach ($permit_keys as $permit_key) {
            $permit_sth->bindValue(1, $permit_key);
            $row = $permit_sth->executeQuery()->fetchAssociative();

            if (!$row) {
                $this->connection->insert(
                    'pongho_permits',
                    [
                        $key_field_name => $permit_key,
                        'is_enabled'    => true,
                    ],
                    [
                        $key_field_name => ParameterType::STRING,
                        'is_enabled'    => ParameterType::BOOLEAN,
                    ]
                );

                $permit_id = dbal_last_insert_id($this->connection, 'pongho_permits_id_seq');

                $permit_role_sth->bindValue(1, $permit_id);
                $row = $permit_role_sth->executeQuery()->fetchAssociative();

                if (!$row) {
                    $this->connection->insert(
                        'pongho_permits_roles',
                        [
                            'permit_id' => $permit_id,
                            'role_id'   => $admin_role_id,
                        ],
                        [
                            'permit_id' => ParameterType::INTEGER,
                            'role_id'   => ParameterType::INTEGER,
                        ]
                    );
                }
            }
        }
    }
}
