<?php

class Greeting
{
    use DatabaseCommunication;

    public static $empty = 'zákazníku';

    public static $stats = [
        'exact' => 0,
        'sex' => 0,
        'fail' => 0,
        'count' => 0,
    ];

    public static function getGreeting($name, $surname, $prioritize = 'name')
    {
        $names = [$name, $surname];
        $types = ['greeting_name', 'greeting_surname'];

        if ($prioritize == 'surname') {
            $names = array_reverse($names);
            $types = array_reverse($types);
        }

        $ret = self::get($names, $types);

        $ret['greeting'] = self::finalizeName($ret['greeting'] ?? '');

        return $ret;
    }

    public static function prepareName($name)
    {
        $name = mb_strtolower($name, 'utf-8'); // Prevest na maly pismenka
        $name = preg_replace('/(ing\. |mgr\. |bc\. | csc\.)/i', '', $name); // Odstranit tituly 20x
        $name = trim($name); // Orezat whitechars
        $name = preg_split('/,| /i', $name)[0]; // Prvni slovo ze jmena a prijmeni v jednom chlivecku ('Adam Brezovsky') 100x

        return $name;
    }

    public static function finalizeName($name)
    {
        $name = mb_convert_case($name, MB_CASE_TITLE, 'utf-8'); // Prvni pismenko velky

        return $name;
    }

    public static function pickBySex($rows, $sex)
    {
        foreach ($rows as $row) {
            if ($row['sex'] == $sex) {
                return $row;
            }
        }

        logError(__FILE__, __LINE__, 'Greeting::pickBySex error');
    }

    public static function getFromName($name, $surname = null)
    {
        $ret = self::get([$name, $surname], ['greeting_name', 'greeting_surname']);

        if (!$ret) {
            return self::$empty;
        }

        return self::finalizeName($ret['greeting']);
    }

    public static function getFromSurname($surname, $name = null)
    {
        $ret = self::get([$surname, $name], ['greeting_surname', 'greeting_name']);

        if (!$ret) {
            return self::$empty;
        }

        $gender = $ret['sex'] == 'male' ? 'pane' : 'paní';
        $greeting = self::finalizeName($ret['greeting']);

        return "{$gender} {$greeting}";
    }

    public static function get($names, $tables, $level = 0)
    {
        $compare = '';

        if ($level == 0) { // Compare BINARY
            $compare = 'AND BINARY original = :name';
        }

        $first = sqlQuery("SELECT greeting, sex FROM `kupshop_shared`.{$tables[0]} WHERE original = :name {$compare} ORDER BY count DESC", ['name' => self::prepareName($names[0])]);

        switch (sqlNumRows($first)) {
            case 0: // Name not found
                switch (++$level) {
                    case 1:
                        return self::get($names, $tables, $level);

                    case 2:
                        return self::get(array_reverse($names), $tables, $level);
                }

                self::$stats['fail']++;

                return null;

            case 1: // Exactly one name found
                self::$stats['exact']++;

                return sqlFetchAssoc($first);
        }

        if (!empty($names[1])) {
            $second = sqlQuery("SELECT greeting, sex FROM `kupshop_shared`.{$tables[1]} WHERE original = :name ORDER BY count DESC", ['name' => self::prepareName($names[1])]);

            if (sqlNumRows($second) == 1) {
                self::$stats['sex']++;

                return self::pickBySex($first, sqlFetchAssoc($second)['sex']);
            }
        }

        self::$stats['count']++;

        return sqlFetchAssoc($first);
    }
}
