<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Upgrade file
 *
 * @package   theme_boost_magnific
 * @copyright 2025 Eduardo Kraus {@link https://eduardokraus.com}
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

use theme_boost_magnific\admin\setting_scss;

/**
 * function xmldb_supervideo_upgrade
 *
 * @param int $oldversion
 * @return bool
 * @throws Exception
 */
function xmldb_theme_boost_magnific_upgrade($oldversion) {
    global $DB, $USER, $CFG;

    if ($oldversion < 2025090300) {
        create_theme_boost_magnific_pages();

        $color = get_config("theme_boost_magnific", "background_color");
        set_config("startcolor", $color, "theme_boost_magnific");
        set_config("brandcolor", $color, "theme_boost_magnific");

        // Home Editor.
        if (get_config("theme_boost_magnific", "home_type") != 0) {

            $homehtmleditor = get_config("theme_boost_magnific", "home_htmleditor_{$CFG->lang}");
            if (!isset($homehtmleditor[40])) {
                $page = (object) [
                    "local" => "home", "type" => "html", "title" => "Home", "html" => $homehtmleditor, "info" => "{}",
                    "template" => "", "lang" => $USER->lang, "sort" => time(),
                ];
                $DB->insert_record("theme_boost_magnific_pages", $page);
            }

            $listoftranslations = get_string_manager()->get_list_of_translations();
            foreach ($listoftranslations as $langkey => $langname) {
                if ($CFG->lang == $langkey) {
                    continue;
                }

                $homehtmleditor = get_config("theme_boost_magnific", "home_htmleditor_{$langkey}");
                if (!isset($homehtmleditor[40])) {
                    $page = (object) [
                        "local" => "home", "type" => "html", "title" => "Home {$langkey}", "html" => $homehtmleditor,
                        "info" => "{}", "template" => "", "lang" => $langkey, "sort" => time(),
                    ];
                    $DB->insert_record("theme_boost_magnific_pages", $page);
                }
            }

        } else {
            if (get_config("theme_boost_magnific", "frontpage_about_enable")) {
                $frontpageaboutlogo = get_config("theme_boost_magnific", "frontpage_about_logo");
                $frontpageabouttitle = get_config("theme_boost_magnific", "frontpage_about_title");
                $frontpageaboutdescription = get_config("theme_boost_magnific", "frontpage_about_description");

                if (!empty($frontpageaboutlogo)) {
                    $frontpageaboutlogo = '<img class="frontpage_about_logo" src="' . $frontpageaboutlogo . '" alt="Logo">';
                }
                $about = '
                <style>
                    .frontpage_about_area {
                        display: flex;
                        flex-direction: column;
                        gap: 40px;
                        margin: 40px auto;
                        max-width: 1200px;
                        padding: 20px;
                    }
                    .frontpage_about_logoarea {
                        text-align: center;
                    }
                    .frontpage_about_logoarea img.frontpage_about_logo {
                        max-height: 120px;
                        margin-bottom: 15px;
                    }
                    .frontpage_about_logoarea h3 {
                        font-size: 28px;
                        font-weight: 600;
                        margin-bottom: 10px;
                        color: var(--primary, #2c3e50);
                    }
                    .frontpage_about_description {
                        font-size: 16px;
                        color: #555;
                        margin: 0 auto 20px;
                        max-width: 700px;
                        line-height: 1.6;
                    }
                    .frontpage_about_counterbox {
                        display: flex;
                        flex-wrap: wrap;
                        justify-content: center;
                        gap: 30px;
                    }
                    .frontpage_about_box {
                        background: #fff;
                        border-radius: 12px;
                        padding: 20px 30px;
                        box-shadow: 0 5px 15px rgba(0,0,0,0.08);
                        text-align: center;
                        width: 220px;
                        position: relative;
                        transition: transform 0.3s ease, box-shadow 0.3s ease;
                    }
                    .frontpage_about_box:hover {
                        transform: translateY(-5px);
                        box-shadow: 0 8px 20px rgba(0,0,0,0.12);
                    }
                    .frontpage_about_box .separator {
                        width: 40px;
                        height: 3px;
                        background: var(--primary, #0073e6);
                        display: block;
                        margin: 0 auto 15px;
                        border-radius: 2px;
                    }
                    .frontpage_about_box .number {
                        font-size: 32px;
                        font-weight: 700;
                        color: var(--primary, #0073e6);
                        margin-bottom: 10px;
                    }
                    .frontpage_about_box .title {
                        font-size: 16px;
                        font-weight: 500;
                        color: #333;
                    }
                </style>
                <div class="frontpage_about_area">
                    <div class="frontpage_about_logoarea text-center">
                        ' . $frontpageaboutlogo . '
                        <h3>' . $frontpageabouttitle . '</h3>
                        <div class="frontpage_about_description">' . $frontpageaboutdescription . '</div>
                    </div>
                    <div class="frontpage_about_counterbox text-center">';

                for ($i = 1; $i <= 4; $i++) {
                    $frontpageabouttext = get_config("theme_boost_magnific", "frontpage_about_text_{$i}");
                    $frontpageaboutnumber = get_config("theme_boost_magnific", "frontpage_about_number_{$i}");

                    if ($frontpageaboutnumber && isset($frontpageabouttext[3])) {
                        $about .= '
                            <div class="frontpage_about_box">
                                <span class="separator"></span>
                                <div class="number">
                                    <span class="number_counter text-primary">' . $frontpageaboutnumber . '</span>
                                </div>
                                <div class="title_counter">
                                    <h4 class="title">' . $frontpageabouttext . '</h4>
                                </div>
                            </div>';
                    }
                }

                $about .= "</div></div>";

                $page = (object) [
                    "local" => "home", "type" => "html", "title" => "About", "html" => $about, "info" => "{}", "template" => "",
                    "lang" => $USER->lang, "sort" => time(),
                ];
                $DB->insert_record("theme_boost_magnific_pages", $page);
            }
        }

        if ($customcss = get_config("theme_boost_magnific", "customcss")) {
            set_config("scsspos", $customcss, "theme_boost_magnific");
        }

        // Footer.
        if (get_config("theme_boost_magnific", "footer_type") == 0) {
            // Footer description.
            $footerdescription = get_config("theme_boost_magnific", "footer_description");
            if (isset($footerdescription[3])) {
                set_config("footer_html_1", $footerdescription, "theme_boost_magnific");
            }

            // Links Util.
            $footerlinkstitle = get_config("theme_boost_magnific", "footer_links_title");
            $footerlinks = get_config("theme_boost_magnific", "footer_links");
            if (!empty($footerlinkstitle) && !empty($footerlinks)) {
                set_config("footer_title_2", $footerlinkstitle, "theme_boost_magnific");

                $html = theme_boost_magnific_generate_links($footerlinks);
                set_config("footer_html_2", $html, "theme_boost_magnific");
            }

            // Social.
            $footersocialtitle = get_config("theme_boost_magnific", "footer_social_title");
            $facebook = get_config("theme_boost_magnific", "social_facebook");
            $youtube = get_config("theme_boost_magnific", "social_youtube");
            $linkedin = get_config("theme_boost_magnific", "social_linkedin");
            $twitter = get_config("theme_boost_magnific", "social_twitter");
            $instagram = get_config("theme_boost_magnific", "social_instagram");
            if (!empty($footersocialtitle) && ($facebook || $youtube || $linkedin || $twitter || $instagram)) {
                set_config("footer_title_3", $footersocialtitle, "theme_boost_magnific");

                $html = "<div>";
                $html .= "<divclass='footer-icons'>";
                if ($facebook) {
                    $html .= html_writer::link($facebook, html_writer::tag("i", "", ["class" => "fa fa-facebook"]),
                        ["target" => "_blank"]);
                }
                if ($youtube) {
                    $html .= html_writer::link(
                        $youtube, html_writer::tag(
                        "i", "", ["class" => "fa fa-youtube"]
                    ), ["target" => "_blank"]
                    );
                }
                if ($linkedin) {
                    $html .= html_writer::link(
                        $linkedin, html_writer::tag(
                        "i", "", ["class" => "fa fa-linkedin"]
                    ), ["target" => "_blank"]
                    );
                }
                if ($twitter) {
                    $html .= html_writer::link(
                        $twitter, html_writer::tag(
                        "i", "", ["class" => "fa fa-twitter"]
                    ), ["target" => "_blank"]
                    );
                }
                if ($instagram) {
                    $html .= html_writer::link(
                        $instagram, html_writer::tag(
                        "i", "", ["class" => "fa fa-instagram"]
                    ), ["target" => "_blank"]
                    );
                }
                $html .= "<div><div>";
                set_config("footer_html_3", $html, "theme_boost_magnific");
            }

            // Contact.
            $contacttitle = get_config("theme_boost_magnific", "contact_footer_title");
            $address = get_config("theme_boost_magnific", "contact_address");
            $phone = get_config("theme_boost_magnific", "contact_phone");
            $email = get_config("theme_boost_magnific", "contact_email");
            if ($contacttitle && ($address || $phone || $email)) {
                set_config("footer_title_4", $contacttitle, "theme_boost_magnific");

                $html = '<div class="footer-contact">';
                if ($address) {
                    $html .= '<p class="contact-address">' . format_text($address, FORMAT_HTML) . '</p>';
                }
                if ($phone) {
                    $html .= '<p class="contact-phone"><a href="tel:' . preg_replace('/\D+/', '', $phone) . '">' . s($phone) .
                        '</a></p>';
                }
                if ($email) {
                    $html .= '<p class="contact-email"><a href="mailto:' . s($email) . '">' . s($email) . '</a></p>';
                }
                $html .= '</div>';

                set_config("footer_html_4", $html, 'theme_boost_magnific');
            }
        }

        upgrade_plugin_savepoint(true, 2025090300, "theme", "boost_magnific");
    }

    if ($oldversion < 2025091000) {
        create_theme_boost_magnific_pages();

        $itens = ["differentials", "featured", "pricing"];
        foreach ($itens as $item) {
            $DB->execute("UPDATE {theme_boost_magnific_pages} SET template = '{$item}' WHERE template LIKE '{$item}-%'");
        }

        upgrade_plugin_savepoint(true, 2025091000, "theme", "boost_magnific");
    }

    if ($oldversion < 2025100400) {
        $scss = get_config("theme_boost_magnific", "scss");
        set_config("scsspos", $scss, "theme_boost_magnific");

        upgrade_plugin_savepoint(true, 2025100400, "theme", "boost_magnific");
    }

    if ($oldversion < 2025101300) {
        $settingscss = new setting_scss("test", "test", "", "");

        $scss = get_config("theme_boost_magnific", "scsspos");
        if ($settingscss->validate($scss) !== true) {
            set_config("scsspos", "", "theme_boost_magnific");
        }

        $scss = get_config("theme_boost_magnific", "scsspre");
        if ($settingscss->validate($scss) !== true) {
            set_config("scsspre", "", "theme_boost_magnific");
        }

        upgrade_plugin_savepoint(true, 2025101300, "theme", "boost_magnific");
    }

    if ($oldversion < 2026022500) {
        set_config("secondary", "#ced4da", "theme_boost");
        set_config("navbarlayout", "classic", "theme_boost_magnific");

        upgrade_plugin_savepoint(true, 2026022500, "theme", "boost_magnific");
    }

    if ($oldversion < 2026022800) {
        $records = $DB->get_records_select(
            'config_plugins',
            "plugin = 'theme_boost_magnific' AND name LIKE 'override_course_color_%'"
        );

        if ($records) {
            foreach ($records as $record) {
                $suffix = substr($record->name, strlen("override_course_color_"));
                $newname = "override_course_primarycolor_{$suffix}";

                set_config($newname, $record->value, 'theme_boost_magnific');
                unset_config($record->name, 'theme_boost_magnific');
            }
        }
        upgrade_plugin_savepoint(true, 2026022800, "theme", "boost_magnific");
    }

    if ($oldversion < 2026030700) {
        set_config("breadcrumb_show_mycourses_courses", 0, "theme_boost_magnific");
        set_config("breadcrumb_show_categories", 0, "theme_boost_magnific");
        set_config("breadcrumb_show_course", 0, "theme_boost_magnific");
        set_config("breadcrumb_show_navigation_duplicates", 0, "theme_boost_magnific");
        set_config("breadcrumb_show_sections", 0, "theme_boost_magnific");
        set_config("breadcrumb_show_no_link_items", 0, "theme_boost_magnific");

        upgrade_plugin_savepoint(true, 2026030700, "theme", "boost_magnific");
    }

    if ($oldversion < 2026052800) {
        $dbman = $DB->get_manager();

        $table = new xmldb_table('theme_boost_magnific_accesslog');
        if (!$dbman->table_exists($table)) {
            $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
            $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
            $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
            $table->add_field('cmid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
            $table->add_field('action', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null);
            $table->add_field('item', XMLDB_TYPE_CHAR, '100', null, null, null, null);
            $table->add_field('status', XMLDB_TYPE_CHAR, '20', null, null, null, null);
            $table->add_field('activeitems', XMLDB_TYPE_TEXT, null, null, null, null, null);
            $table->add_field('statejson', XMLDB_TYPE_TEXT, null, null, null, null, null);
            $table->add_field('pageurl', XMLDB_TYPE_TEXT, null, null, null, null, null);
            $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '20', null, XMLDB_NOTNULL, null, '0');

            $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
            $table->add_index('userid', XMLDB_INDEX_NOTUNIQUE, ['userid']);
            $table->add_index('action', XMLDB_INDEX_NOTUNIQUE, ['action']);
            $table->add_index('timecreated', XMLDB_INDEX_NOTUNIQUE, ['timecreated']);

            $dbman->create_table($table);
        }

        upgrade_plugin_savepoint(true, 2026052800, 'theme', 'boost_magnific');
    }

    return true;
}

/**
 * Create theme_boost_magnific_pages
 *
 * @return void
 * @throws Exception
 */
function create_theme_boost_magnific_pages() {
    global $DB;

    // Define a estrutura da tabela.
    $table = new xmldb_table('theme_boost_magnific_pages');

    // Campos.
    $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
    $table->add_field('local', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null);
    $table->add_field('type', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null);
    $table->add_field('title', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
    $table->add_field('html', XMLDB_TYPE_TEXT, null, null, null, null, null);
    $table->add_field('info', XMLDB_TYPE_TEXT, null, null, null, null, null);
    $table->add_field('template', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null);
    $table->add_field('lang', XMLDB_TYPE_CHAR, '6', null, null, null, null);
    $table->add_field('sort', XMLDB_TYPE_INTEGER, '10', null, null, null, null);

    // Chave primária.
    $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);

    // Cria a tabela, se não existir.
    $dbman = $DB->get_manager();
    if (!$dbman->table_exists($table)) {
        $dbman->create_table($table);
    }
}

/**
 * Convert Footer Links
 *
 * @param string $menustr Footer block link name.
 * @return string The Footer links are return.
 * @throws Exception
 */
function theme_boost_magnific_generate_links($menustr = "") {
    $htmlstr = "";
    $menusettings = explode("\n", $menustr);
    foreach ($menusettings as $menukey => $menuval) {
        $expset = explode("|", $menuval);
        if (!empty($expset) && isset($expset[0]) && isset($expset[1])) {
            [$ltxt, $lurl] = $expset;
            $ltxt = trim($ltxt);
            $lurl = trim($lurl);
            if (empty($ltxt)) {
                continue;
            }
            if (empty($lurl)) {
                $lurl = "javascript:void(0);";
            }

            $pos = strpos($lurl, "http");
            if ($pos === false) {
                $lurl = new moodle_url($lurl);
            }
            $htmlstr .= '<li><a href="' . $lurl . '">' . $ltxt . '</a></li>' . "\n";
        }
    }
    return $htmlstr;
}
