<?php

class CompanyAreaDependency {

    const TABLE = 'company_area_map';
    const PARENT_FIELD = 'CompanySourceTD';
    const CHILD_FIELD  = 'area';

    static function getTableName() {
        global $cfg;

        $prefix = '';
        if (is_object($cfg) && method_exists($cfg, 'getDbPrefix')) {
            $prefix = $cfg->getDbPrefix();
        }

        if (!$prefix)
            $prefix = 'ost_';

        return $prefix . self::TABLE;
    }

    static function getListItemsTableName() {
        global $cfg;

        $prefix = '';
        if (is_object($cfg) && method_exists($cfg, 'getDbPrefix')) {
            $prefix = $cfg->getDbPrefix();
        }

        if (!$prefix)
            $prefix = 'ost_';

        return $prefix . 'list_items';
    }

    static function normalizeValue($value) {
        if (is_array($value)) {
            if (isset($value['value']))
                $value = $value['value'];
            else
                $value = reset($value);
        }

        $value = trim((string)$value);
        $value = preg_replace('/\s+/', ' ', $value);

        return $value;
    }

    static function resolveListItemValue($value) {
        $value = self::normalizeValue($value);

        if ($value === '')
            return $value;

        if (!preg_match('/^\d+$/', $value))
            return $value;

        $table = self::getListItemsTableName();
        $sql = 'SELECT `value`
                FROM `' . $table . '`
                WHERE id = ' . (int)$value . '
                LIMIT 1';

        $res = db_query($sql);
        if ($res && ($row = db_fetch_array($res)) && isset($row['value'])) {
            return self::normalizeValue($row['value']);
        }

        return $value;
    }

    static function getChildren($parentValue, $onlyActive = true) {
        $parentValue = self::normalizeValue($parentValue);

        if ($parentValue === '')
            return array();

        $table = self::getTableName();
        $sql = 'SELECT child_value
                FROM `' . $table . '`
                WHERE parent_value = ' . db_input($parentValue);

        if ($onlyActive)
            $sql .= ' AND is_active = 1';

        $sql .= ' ORDER BY sort ASC, child_value ASC';

        $res = db_query($sql);
        $items = array();

        if ($res) {
            while ($row = db_fetch_array($res)) {
                $items[] = $row['child_value'];
            }
        }

        return $items;
    }

    static function getPairsByParent($parentValue, $onlyActive = true) {
        $parentValue = self::normalizeValue($parentValue);

        if ($parentValue === '')
            return array();

        $table = self::getTableName();
        $sql = 'SELECT id, parent_value, child_value, is_active, sort
                FROM `' . $table . '`
                WHERE parent_value = ' . db_input($parentValue);

        if ($onlyActive)
            $sql .= ' AND is_active = 1';

        $sql .= ' ORDER BY sort ASC, child_value ASC';

        $res = db_query($sql);
        $items = array();

        if ($res) {
            while ($row = db_fetch_array($res)) {
                $items[] = $row;
            }
        }

        return $items;
    }

    static function isValidPair($parentValue, $childValue, $onlyActive = true) {
        $parentValue = self::resolveListItemValue($parentValue);
        $childValue  = self::resolveListItemValue($childValue);

        $parentValue = self::normalizeValue($parentValue);
        $childValue  = self::normalizeValue($childValue);

        if ($parentValue === '' || $childValue === '')
            return false;

        $table = self::getTableName();
        $sql = 'SELECT id
                FROM `' . $table . '`
                WHERE parent_value = ' . db_input($parentValue) . '
                  AND child_value = ' . db_input($childValue);

        if ($onlyActive)
            $sql .= ' AND is_active = 1';

        $sql .= ' LIMIT 1';

        $res = db_query($sql);

        return ($res && db_num_rows($res));
    }

    static function extractValueByVar($source, $varname) {
        if (!is_array($source) || !$varname)
            return null;

        if (array_key_exists($varname, $source))
            return self::normalizeValue($source[$varname]);

        foreach ($source as $key => $value) {
            if (is_array($value)) {
                if (array_key_exists($varname, $value))
                    return self::normalizeValue($value[$varname]);

                if (isset($value['name']) && $value['name'] === $varname && isset($value['value']))
                    return self::normalizeValue($value['value']);

                $found = self::extractValueByVar($value, $varname);
                if ($found !== null && $found !== '')
                    return $found;
            }
        }

        return null;
    }

    static function extractParentValue($source) {
        return self::extractValueByVar($source, self::PARENT_FIELD);
    }

    static function extractChildValue($source) {
        return self::extractValueByVar($source, self::CHILD_FIELD);
    }

    static function validateSource($source, &$errors, $parentKey = null, $childKey = null) {
        if (!is_array($errors))
            $errors = array();

        if (!$parentKey)
            $parentKey = self::PARENT_FIELD;

        if (!$childKey)
            $childKey = self::CHILD_FIELD;

        $parent = self::extractParentValue($source);
        $child  = self::extractChildValue($source);

        if ($parent === null || $child === null)
            return true;

        $parent = self::resolveListItemValue($parent);
        $child  = self::resolveListItemValue($child);

        $parent = self::normalizeValue($parent);
        $child  = self::normalizeValue($child);

        if ($parent === '' || $child === '')
            return true;

        if (!self::isValidPair($parent, $child, true)) {
            $errors[$childKey] = __('El área seleccionada no pertenece a la empresa/ciudad/unidad elegida.');
            return false;
        }

        return true;
    }
}