<?php

use Morpheus\Util\Team;

$characters = $conn->fetchAll('select Name 
    from Character
    where CtlCode = 0
');

$patents = $conn->fetchAll('select * 
    from mw_patents
    where active = 1
    order by sequence
');

foreach ($characters as $character) {
    foreach ($patents as $patent) {
        if (!empty($patent['command'])) {
            $exists = $conn->fetchAssoc($patent['command'], ['name' => $character['Name']]);
        } else {
            $where = '';
            if (!empty($patent['levels']) && $patent['levels'] > 0) {
                $where .= ' and cLevel >= ' . $patent['levels'];
            }

            if (!empty($patent['resets']) && $patent['resets'] > 0) {
                $where .= ' and ' . config('columns.resets') . ' >= ' . $patent['resets'];
            }

            if (!empty($patent['master_resets']) && $patent['master_resets'] > 0) {
                $where .= ' and ' . config('columns.master_resets') . ' >= ' . $patent['master_resets'];
            }

            if (!empty($patent['master_levels']) && $patent['master_levels'] > 0) {
                $table = Team::is('igcn') ? 'Character' : 'MasterSkillTree';
                $level = Team::is('igcn') ? 'mLevel' : 'MasterLevel';
                $where .= ' and exists (select 1 from ' . $table . ' where Name = c.Name and ' . $level . ' >= ' . $patent['master_levels'] . ')';
            }

            $exists = $conn->fetchAssoc('select 1 
                from Character c
                where c.Name = ?
            ' . $where, [$character['Name']]);
        }

        if ($exists) {
            $conn->update('Character', [
                'PatentId' => $patent['id']
            ], [
                'Name' => $character['Name']
            ]);
        } else {
            break;
        }
    }
}