<?php

namespace Bdp\Modules\Gruppen\Controllers;

use Bdp\Libs\FileAccess;

class MainController
{
    public const KOMPASS_STAMMESGRUPPEN_GRUPPEN = 'kompass_stammesgruppen_gruppen';
	public const KOMPASS_STAMMESGRUPPEN_TEILIS = 'kompass_stammesgruppen_teilis';

    public static function setup()
    {
	    global $wpdb;

        $charset = $wpdb->get_charset_collate();
        $fileReader = new FileAccess();
        foreach ([self::KOMPASS_STAMMESGRUPPEN_GRUPPEN, self::KOMPASS_STAMMESGRUPPEN_TEILIS] as $table) {
	        $sqlTable = $wpdb->prefix . $table;
	        $sql      = "SHOW TABLES LIKE '$sqlTable'";

	        $result = $wpdb->get_var( $sql );
	        if ( $result == $sqlTable ) {
		        continue;
	        }

	        $sqlSetup = str_replace(
		        '%tablename%',
		        $sqlTable,
		        $fileReader->get_contents( WP_PLUGIN_DIR . '/' . BDP_LV_PLUGIN_SLUG . '/lib/database/' . $table . '.sql' ) );

	        $sqlSetup = str_replace('%charset%', $charset, $sqlSetup);
	        $sqlSetup = str_replace('%prefix%', $wpdb->prefix, $sqlSetup);



	        dbDelta( $sqlSetup );
        }

    }
    public function __construct()
    {
        add_submenu_page(
                BDP_LV_PLUGIN_DIR . '/modules/index.php',
                __('Groups', BDP_LV_PLUGIN_SLUG),
	            __('Groups', BDP_LV_PLUGIN_SLUG),
                'show_groups',
                'kompass-groups',
                [$this, 'router'],
                1);
    }


    public function router()
    {
        if (isset($_REQUEST['action'])) {
            switch ($_REQUEST['action']) {
                case 'searchmember':
                    $this->searchMember();
                    break;

                default:
	                kompass_print_gruppen_overview();
            }
        } else {
	        kompass_print_gruppen_overview();
        }
    }

    private function searchMember()
    {
	    global $dbHandler;
        $members = $dbHandler->readSqlFromDb(self::KOMPASS_STAMMESGRUPPEN_TEILIS,
        'SELECT * FROM %tablename% WHERE CONCAT(`vorname`, " " , `nachname`) LIKE "%' . $_POST['member_name'] . '%"');
        $this->printMembers($members);
    }

    private function printMembers(array $memberList)
    {
        if (count($memberList) === 0) {
            exit;
        }
        kompass_print_gruppen_members($memberList);
    }

}