<?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 Application\Core\Model\Permit;
use Application\Core\Model\PermitRole;
use Application\Core\Model\Role;
use Application\Core\Model\Translation;
use Updates\BaseUpdate;

class Update92 extends BaseUpdate
{
    /**
     * {@inheritdoc}
     */
    public function commit()
    {
        $permits = [
            'visitsreport'    => 'Può vedere il pannello "Panoramica visitatori"',
            'locationsreport' => 'Può vedere il pannello "Visite per paese"',
            'keywordsreport'  => 'Può vedere il pannello "Traffico di ricerca organico"',
            'pageviewsreport' => 'Può vedere il pannello "Pagine visitate"',
            'statsreport'     => 'Può vedere il pannello "Statistiche di Pongho"',
        ];

        /** @var Role[] $roles */
        $roles = Role::all([
            'select'     => '`from`.*',
            'joins'      => 'INNER JOIN ' . PermitRole::tableName() . ' AS pr ON pr.role_id = `from`.id'
                         . ' INNER JOIN ' . Permit::tableName() . ' AS p ON p.id = pr.permit_id',
            'conditions' => [
                'p.key = :admin_permit',
                'admin_permit' => 'admin',
            ],
        ]);

        foreach ($permits as $key => $translation) {
            $key = 'admin.dashboard.widget_' . $key;
            $permit = Permit::findByKey($key);

            if (!$permit) {
                $permit = Permit::create([
                    'key'        => $key,
                    'is_enabled' => true,
                ]);
            }

            foreach ($roles as $role) {
                $pr = PermitRole::find($permit->id, $role->id);

                if (!$pr) {
                    PermitRole::create([
                        'permit_id' => $permit->id,
                        'role_id'   => $role->id,
                    ]);
                }
            }

            Translation::putTranslation('permit_' . $key, $translation, 'admin', 'it_IT');
        }

        Translation::putTranslation('permit_ns_admin.dashboard', 'Widget in bacheca', 'admin', 'it_IT');
    }
}
