<?php

use system\entity\filter\baseFilter;

class Ftr_sql
{

    public static function generateUpdate($table, $fieldList, $whereFieldWithValue = '')
    {
        $sql = "update " . $table . " set ";

        foreach ($fieldList as $field) {
            $sql .= ($fieldList[count($fieldList) - 1] == $field) ? $field . " = ?" : $field . " = ?, ";
        }

        if (!empty($whereFieldWithValue)) {
            $sql .= ' where ' . $whereFieldWithValue;
        }
        return $sql;
    }

    public static function generateInsert($table, $fieldList)
    {
        $sql = 'insert into ' . $table . ' (';
        $fields = '(';

        foreach ($fieldList as $field) {
            $sql .= ($fieldList[count($fieldList) - 1] == $field) ? $field . ")" : $field . ",";
            $fields .= ($fieldList[count($fieldList) - 1] == $field) ? "?)" : "?, ";
        }
        $sql .= ' values ' . $fields;

        return $sql;
    }

    /**
     * @param $tableName
     * @param baseFilter|null $filters
     * @param array|null $orderBy
     * @param null $start
     * @param null $limit
     * @return string
     */
    public static function generateSelect($tableName, BaseFilter $filters = null, array $orderBy = null, $start = null, $limit = null)
    {

        $sql = 'select * from ' . $tableName;

        if ( !is_null($filters) && ($filters instanceof BaseFilter) ) {

            if (!is_null($filters->getWhere())) {
                $sql .= $filters->getWhere();
            }

            if (!is_null($filters->getAndWhere())) {
                $sql .= $filters->getAndWhere();
            }

        }

        if (!is_null($start) || !is_null($limit)) {
            if ($start < 0) {
                $start = 0;
            }

            if ($limit < 1) {
                $limit = 20;
            }

            $sql .= " LIMIT " . (int)$start . "," . (int)$limit;
        }

        return $sql;
    }

    /**
     * @param $tableName
     * @param baseFilter|null $filters
     * @return string
     */
    public static function generateDelete($tableName, BaseFilter $filters = null)
    {

        $sql = 'delete from ' . $tableName;

        if(!is_null($filters) && ($filters instanceof BaseFilter)){

            if (!is_null($filters->getWhere())) {
                $sql .= $filters->getWhere();
            }

        }

        return $sql;
    }

}