<?php

return [
    'SL-153', function() {
        SJB_DB::query('delete from `pages` where `uri` in ("/choose-user/")');
        return true;
    },
    'SL-154', function() {
        $success = (bool) SJB_DB::query('ALTER TABLE `payment_gateways` ADD `position` INT NULL DEFAULT NULL');
        $success &= (bool) SJB_DB::query('UPDATE `payment_gateways` SET `position` = 0 WHERE `id` = "stripe"');
        $success &= (bool) SJB_DB::query('UPDATE `payment_gateways` SET `position` = 1 WHERE `id` = "paypal_standard"');
        $success &= (bool) SJB_DB::query('UPDATE `payment_gateways` SET `position` = 2 WHERE `id` = "paypal_pro"');
        $success &= (bool) SJB_DB::query('UPDATE `payment_gateways` SET `position` = 3 WHERE `id` = "authnet_sim"');
        $success &= (bool) SJB_DB::query('UPDATE `payment_gateways` SET `position` = 4 WHERE `id` = "2checkout"');
        $success &= (bool) SJB_DB::query('UPDATE `payment_gateways` SET `position` = 5 WHERE `id` = "invoice"');
        return $success;
    },
    'SL-156', function() {
        $success = (bool) SJB_DB::query('ALTER TABLE `user_profile_fields` DROP `instructions`;');
        $success &= (bool) SJB_DB::query('ALTER TABLE `listing_complex_fields` DROP `instructions`;');
        $success &= (bool) SJB_DB::query('ALTER TABLE `listing_fields` DROP `instructions`;');
        $success &= (bool) SJB_DB::query('UPDATE `pages` SET `uri` = "/wysiwyg/", `function` = "wysiwyg" WHERE `uri` = "/kcfinder/"');
        return $success;
    },
    'SL-161', function() {
        $success = true;
        $cols = SJB_DB::query('SHOW COLUMNS FROM `listing_fields`');
        foreach ($cols as $col) {
            if ($col['Field'] == 'display_as_select_boxes') {
                $success &= (bool) SJB_DB::query('ALTER TABLE `listing_fields` DROP COLUMN `display_as_select_boxes`');
            }
        }
        $cols = SJB_DB::query('SHOW COLUMNS FROM `user_profile_fields`');
        foreach ($cols as $col) {
            if ($col['Field'] == 'display_as_select_boxes') {
                $success &= (bool) SJB_DB::query('ALTER TABLE `user_profile_fields` DROP COLUMN `display_as_select_boxes`');
            }
        }

        $success &= (bool) SJB_DB::query('INSERT INTO `pages` (`uri`, `pass_parameters_via_uri`, `module`, `function`, `template`, `title`, `access_type`, `parameters`, `keywords`, `description`, `ID`, `content`) VALUES (\'/custom-fields/\', NULL, \'miscellaneous\', \'custom_fields\', NULL, \'Custom Fields\', \'admin\', \'\', NULL, \'\', NULL, NULL);');
        $success &= (bool) SJB_DB::query('INSERT INTO `user_profile_fields` (`user_group_sid`, `order`, `id`, `caption`, `type`, `default_value`, `is_required`, `maxlength`, `width`, `height`, `second_width`, `second_height`, `template`, `level_1`, `level_2`, `level_3`, `level_4`, `parent_sid`, `hidden`, `display_as`, `choiceLimit`) VALUES
          (\'36\', \'0\', \'username\', \'Email\', \'unique_email\', NULL, \'1\', \'256\', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, \'0\', NULL, \'0\'),
          (\'36\', \'0\', \'password\', \'Password\', \'password\', NULL, \'1\', \'256\', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, \'0\', NULL, \'0\'),
          (\'41\', \'0\', \'username\', \'Email\', \'unique_email\', NULL, \'1\', \'256\', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, \'0\', NULL, \'0\'),
          (\'41\', \'0\', \'password\', \'Password\', \'password\', NULL, \'1\', \'256\', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, \'0\', NULL, \'0\')');

        $success &= (bool) SJB_DB::query('CREATE TABLE IF NOT EXISTS `user_profile_field_list` (
          `sid` int(10) unsigned NOT NULL AUTO_INCREMENT,
          `field_sid` int(10) unsigned DEFAULT NULL,
          `order` int(10) unsigned DEFAULT NULL,
          `value` varchar(255) DEFAULT NULL,
          PRIMARY KEY (`sid`),
          KEY `field_sid` (`field_sid`),
          KEY `order` (`order`),
          KEY `value` (`value`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;');

        $files = [
            'templates/Bootstrap/users/registration_fields.tpl',
            'templates/Flow/classifieds/input_form.tpl',
            'templates/Flow/classifieds/input_form_default.tpl',
            'templates/Flow/field_types/input/applicationSettings.tpl',
            'templates/Flow/field_types/input/password_in_row.tpl',
            'templates/Flow/users/edit_profile.tpl',
            'templates/Flow/users/registration_fields.tpl',
            'templates/Flow/users/registration_form.tpl',
            'templates/Simplicity/classifieds/input_form.tpl',
            'templates/Simplicity/classifieds/input_form_default.tpl',
            'templates/Simplicity/field_types/input/applicationSettings.tpl',
            'templates/Simplicity/field_types/input/password_in_row.tpl',
            'templates/Simplicity/users/edit_profile.tpl',
            'templates/Simplicity/users/registration_fields.tpl',
            'templates/Simplicity/users/registration_form.tpl',
        ];

        foreach ($files as $file) {
            @unlink(SJB_BASE_DIR . $file);
        }

        $order = 1;
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "username" and user_group_sid = 41', $order++);
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "FullName" and user_group_sid = 41', $order++);
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "password" and user_group_sid = 41', $order++);
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "CompanyName" and user_group_sid = 41', $order++);
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "WebSite" and user_group_sid = 41', $order++);
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "Phone" and user_group_sid = 41', $order++);
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "GooglePlace" and user_group_sid = 41', $order++);
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "Logo" and user_group_sid = 41', $order++);
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "CompanyDescription" and user_group_sid = 41', $order++);
        $order = 1;
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "FullName" and user_group_sid = 36', $order++);
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "username" and user_group_sid = 36', $order++);
        SJB_DB::query('update user_profile_fields set `order` = ?n where id = "password" and user_group_sid = 36', $order++);

        return $success && (bool) SJB_DB::query('delete from `pages` WHERE `uri` IN (?l)', [
            "/edit-list-item/",
            "/edit-user-profile-field/edit-list-item/",
            "/edit-user-profile-field/edit-list/",
            "/edit-listing-field/edit-list-item/",
            "/edit-listing-field/edit-submultilist/",
            '/edit-listing-field/edit-list/',
            '/edit-listing-field/edit-tree/',
            '/edit-user-profile-field/edit-tree/',
            '/edit-listing-field/edit-fields/edit-tree/',
            '/edit-user-group/',
            '/delete-user-group/',
            '/filters/',
            '/add-user-group/',
            '/user-groups/',
            '/user-product/'
        ]);
    },
    'SL-171', function() {
        $phrases = [
            'remove' => [
                'You do not have permissions to post Jobs. Please purchase a relevant product.',
                'You do not have permissions to post Resumes. Please purchase a relevant product.',
                'You&apos;ve reached the limit of number of listings allowed by your product',
                'Please choose new product',
                'The product you&apos;ve purchased does not allow to post listings. Please purchase another product',
            ],
            'add' => [
                [
                    'en' => 'Sorry. You don\'t have permissions to post jobs.',
                    'de' => '',
                    'fr' => '',
                    'es' => '',
                    'ru' => 'У вас нет привилегий для добавления вакансий.',
                ],
                [
                    'en' => 'Sorry. You don\'t have permissions to search resumes.',
                    'de' => '',
                    'fr' => '',
                    'es' => '',
                    'ru' => 'У вас нет привилегий для поиска резюме.',
                ],
                [
                    'en' => 'Sorry. You don\'t have permissions to post resume.',
                    'de' => '',
                    'fr' => '',
                    'es' => '',
                    'ru' => 'У вас нет привилегий для создания резюме.',
                ],
                [
                    'en' => 'Sorry. There are no are no products available.',
                    'de' => '',
                    'fr' => '',
                    'es' => '',
                    'ru' => 'Нет ни одного продукта.',
                ],
            ]
        ];

        $success = true;
        foreach (['de', 'en', 'es', 'fr', 'ru'] as $lang) {
            $langFile = SJB_BASE_DIR . "languages/{$lang}.pages.xml";
            if (!file_exists($langFile)) {
                continue;
            }
            $contents = file_get_contents($langFile);
            foreach ($phrases['remove'] as $phrase) {
                $phrase = preg_quote($phrase);
                $contents = preg_replace("|\\s+<string key=\"{$phrase}.*<\\/string>|uUsm", '', $contents);
            }
            foreach ($phrases['add'] as $phrase) {
                $trans = $phrase[$lang];
                $phrase = $phrase['en'];
                $contents = str_replace(
                    '<page key="Frontend">',
                    sprintf(
                        join("\n", [
                            '<page key="Frontend">',
                            '      <string key="%s">',
                            '        <tr lang="%s"> %s </tr>',
                            '      </string>',
                            ]),
                        XML_Util::replaceEntities($phrase),
                        $lang,
                        XML_Util::replaceEntities($trans)
                    ),
                    $contents
                );
            }
            $success &= (bool) file_put_contents($langFile, $contents);
        }

        return $success;
    },
    'SL-172', function() {
        $phrases = [
            [
                'en' => 'Your job will be published as soon as it is reviewed and approved.',
                'de' => '',
                'fr' => '',
                'es' => '',
                'ru' => 'Ваша вакансия будет опубликована после рассмотрения администрацией сайта.',
            ],
            [
                'en' => 'Pending Approval',
                'de' => '',
                'fr' => '',
                'es' => '',
                'ru' => 'На модерации',
            ],
        ];

        $success = true;
        foreach (['de', 'en', 'es', 'fr', 'ru'] as $lang) {
            $langFile = SJB_BASE_DIR . "languages/{$lang}.pages.xml";
            if (!file_exists($langFile)) {
                continue;
            }
            $contents = file_get_contents($langFile);
            foreach ($phrases as $phrase) {
                $trans = $phrase[$lang];
                $phrase = $phrase['en'];
                $contents = str_replace(
                    '<page key="Frontend">',
                    sprintf(
                        join("\n", [
                            '<page key="Frontend">',
                            '      <string key="%s">',
                            '        <tr lang="%s"> %s </tr>',
                            '      </string>',
                        ]),
                        XML_Util::replaceEntities($phrase),
                        $lang,
                        XML_Util::replaceEntities($trans)
                    ),
                    $contents
                );
            }
            $success &= (bool) file_put_contents($langFile, $contents);
        }

        $cols = SJB_DB::query('show columns from listings');
        foreach ($cols as $col) {
            if ($col['Field'] == 'email_frequency') {
                $success &= (bool) SJB_DB::query('alter table `listings` drop `email_frequency`');
                break;
            }
        }
        return $success;
    },
    '5.0.5', function() {
        SJB_DB::query('delete from `pages` where `uri` = "/search-results/"');
        SJB_DB::query('delete from settings where `name` = "listing_currency"');

        $simplyhired = SJB_BASE_DIR . 'system/plugins/simply_hired';
        if (file_exists($simplyhired)) {
            $iterator = new RecursiveDirectoryIterator($simplyhired, FilesystemIterator::SKIP_DOTS);
            $iterator = new RecursiveIteratorIterator($iterator);
            foreach ($iterator as $file) {
                @unlink($file->getPathName());
            }
        }
        @rmdir($simplyhired);
        ThemeManager::compileStyles();
        SJB_TemplateProcessor::deleteCache();
        return true;
    },
];
