<?php
namespace MGModule\DNSManager2\mgLibs\custom\helpers;
use \MGModule\DNSManager2 as main;

class CollationHelper 
{
    public static function fixCollation(array $tablesRepos = array(), $baseTableName)
    {
        $baseCollationDetails = self::getCollation($baseTableName);
                
        foreach ($tablesRepos as $repo)
        {
            $temp = '\MGModule\DNSManager2\\'.$repo;
            $tName = $temp::tableName();
            $tCollDetails = self::getCollation($tName);
            if($tCollDetails['collation'] !== $baseCollationDetails['collation'])
            {
                main\mgLibs\MySQL\query::query("ALTER TABLE `".$tName."` ".
                    (($baseCollationDetails['charset'] && $baseCollationDetails['charset'] !== $tCollDetails['charset']) 
                        ? "DEFAULT CHARACTER SET ".$baseCollationDetails['charset']." " : "").
                    " COLLATE=".$baseCollationDetails['collation']);
            }
        }
      
    }

    public static function getCollation($tableName = 'tblconfiguration')
    {
        global $db_name;
        $schemaRow = main\mgLibs\MySQL\query::query("SELECT * FROM information_schema.`TABLES` T,
            information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
            WHERE CCSA.collation_name = T.table_collation
            AND T.table_schema = '{$db_name}'
            AND T.table_name = '{$tableName}'")->fetch();

        $charset = $schemaRow['CHARACTER_SET_NAME'];
        $colation = !empty($schemaRow['COLLATION_NAME']) ? $schemaRow['COLLATION_NAME'] : self::getCollationIfNotProvided($tableName);
        
        return array(
                'collation' => ($colation && $colation != '') ? $colation : false, 
                'charset' => ($charset && $charset != '') ? $charset : false
            );
    }
    
    public static function setCollationForTableStructure(&$struct, $collationDetails)
    {
        if($collationDetails['collation'])
        {
            $struct['COLLATE'] = $collationDetails['collation'];
        }
        
        if($collationDetails['charset'])
        {
            $struct['charset'] = $collationDetails['charset'];
        }        
    }
    
    public static function getCollationIfNotProvided($tableName)
    {
        $tableName = main\mgLibs\MySQL\query::realEscapeString($tableName);
        $collation = main\mgLibs\MySQL\query::query("SHOW TABLE STATUS LIKE '$tableName' ")->fetch();
        
        return $collation['Collation'];
    }
}
