<?php

/**
 * Class TableModel
 * 
 * Model for table operations using PDO
 */
class TableModel
{
    /**
     * Get table rows with pagination
     * @param string $database_name
     * @param string $table_name
     * @param int $page
     * @param int $per_page
     * @return array
     */
    public static function getTableRows($database_name, $table_name, $page = 1, $per_page = 20)
    {
        $database = DatabaseFactory::getFactory()->getConnection();
        
        $offset = ($page - 1) * $per_page;
        
        $sql = "SELECT * FROM `" . $database_name . "`.`" . $table_name . "` LIMIT :offset, :per_page";
        $query = $database->prepare($sql);
        $query->bindParam(':offset', $offset, PDO::PARAM_INT);
        $query->bindParam(':per_page', $per_page, PDO::PARAM_INT);
        $query->execute();
        
        return $query->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get total number of rows in a table
     * @param string $database_name
     * @param string $table_name
     * @return int
     */
    public static function getTableRowCount($database_name, $table_name)
    {
        $database = DatabaseFactory::getFactory()->getConnection();
        
        $sql = "SELECT COUNT(*) as count FROM `" . $database_name . "`.`" . $table_name . "`";
        $query = $database->prepare($sql);
        $query->execute();
        
        $result = $query->fetch(PDO::FETCH_ASSOC);
        return (int)$result['count'];
    }

    /**
     * Get table column information
     * @param string $database_name
     * @param string $table_name
     * @return array
     */
    public static function getTableColumns($database_name, $table_name)
    {
        $database = DatabaseFactory::getFactory()->getConnection();
        
        $sql = "SHOW COLUMNS FROM `" . $database_name . "`.`" . $table_name . "`";
        $query = $database->prepare($sql);
        $query->execute();
        
        return $query->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get table indexes
     * @param string $database_name
     * @param string $table_name
     * @return array
     */
    public static function getTableIndexes($database_name, $table_name)
    {
        $database = DatabaseFactory::getFactory()->getConnection();
        
        $sql = "SHOW INDEX FROM `" . $database_name . "`.`" . $table_name . "`";
        $query = $database->prepare($sql);
        $query->execute();
        
        return $query->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Get table information
     * @param string $database_name
     * @param string $table_name
     * @return array
     */
    public static function getTableInfo($database_name, $table_name)
    {
        $database = DatabaseFactory::getFactory()->getConnection();
        
        $sql = "SHOW TABLE STATUS FROM `" . $database_name . "` LIKE :table_name";
        $query = $database->prepare($sql);
        $query->execute(array(':table_name' => $table_name));
        
        $result = $query->fetch(PDO::FETCH_ASSOC);
        
        if ($result) {
            return array(
                'engine' => $result['Engine'],
                'rows' => $result['Rows'],
                'data_size' => self::formatBytes($result['Data_length']),
                'index_size' => self::formatBytes($result['Index_length']),
                'total_size' => self::formatBytes($result['Data_length'] + $result['Index_length']),
                'collation' => $result['Collation'],
                'comment' => $result['Comment'],
                'auto_increment' => $result['Auto_increment'],
                'create_time' => $result['Create_time'],
                'update_time' => $result['Update_time']
            );
        }
        
        return array();
    }

    /**
     * Create a new table
     * @param string $database_name
     * @param string $table_name
     * @param array $columns
     * @return bool
     */
    public static function createTable($database_name, $table_name, $columns)
    {
        if (!$database_name || !$table_name || empty($columns)) {
            return false;
        }

        $database = DatabaseFactory::getFactory()->getConnection();
        
        $column_definitions = array();
        foreach ($columns as $column) {
            $definition = "`" . $column['name'] . "` " . $column['type'];
            
            if (isset($column['null']) && $column['null'] === 'NO') {
                $definition .= " NOT NULL";
            }
            
            if (isset($column['default']) && $column['default'] !== '') {
                $definition .= " DEFAULT '" . $column['default'] . "'";
            }
            
            if (isset($column['extra']) && $column['extra'] === 'auto_increment') {
                $definition .= " AUTO_INCREMENT";
            }
            
            $column_definitions[] = $definition;
        }
        
        foreach ($columns as $column) {
            if (isset($column['key']) && $column['key'] === 'PRI') {
                $column_definitions[] = "PRIMARY KEY (`" . $column['name'] . "`)";
                break;
            }
        }
        
        $columns_sql = implode(', ', $column_definitions);
        
        try {
            $sql = "CREATE TABLE `" . $database_name . "`.`" . $table_name . "` (" . $columns_sql . ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
            $query = $database->prepare($sql);
            return $query->execute();
        } catch (PDOException $e) {
            return false;
        }
    }

    /**
     * Delete a table
     * @param string $database_name
     * @param string $table_name
     * @return bool
     */
    public static function deleteTable($database_name, $table_name)
    {
        if (!$database_name || !$table_name) {
            return false;
        }

        $database = DatabaseFactory::getFactory()->getConnection();
        
        try {
            $sql = "DROP TABLE `" . $database_name . "`.`" . $table_name . "`";
            $query = $database->prepare($sql);
            return $query->execute();
        } catch (PDOException $e) {
            return false;
        }
    }

    /**
     * Add a column to a table
     * @param string $database_name
     * @param string $table_name
     * @param string $column_name
     * @param string $column_type
     * @param string $column_null
     * @param string $column_key
     * @param string $column_default
     * @param string $column_extra
     * @return bool
     */
    public static function addColumn($database_name, $table_name, $column_name, $column_type, $column_null, $column_key, $column_default, $column_extra)
    {
        if (!$database_name || !$table_name || !$column_name || !$column_type) {
            return false;
        }

        $database = DatabaseFactory::getFactory()->getConnection();
        
        $definition = "`" . $column_name . "` " . $column_type;
        
        if ($column_null === 'NO') {
            $definition .= " NOT NULL";
        }
        
        if ($column_default !== '') {
            $definition .= " DEFAULT '" . $column_default . "'";
        }
        
        if ($column_extra === 'auto_increment') {
            $definition .= " AUTO_INCREMENT";
        }
        
        try {
            $sql = "ALTER TABLE `" . $database_name . "`.`" . $table_name . "` ADD " . $definition;
            $query = $database->prepare($sql);
            return $query->execute();
        } catch (PDOException $e) {
            return false;
        }
    }

    /**
     * Drop a column from a table
     * @param string $database_name
     * @param string $table_name
     * @param string $column_name
     * @return bool
     */
    public static function dropColumn($database_name, $table_name, $column_name)
    {
        if (!$database_name || !$table_name || !$column_name) {
            return false;
        }

        $database = DatabaseFactory::getFactory()->getConnection();
        
        try {
            $sql = "ALTER TABLE `" . $database_name . "`.`" . $table_name . "` DROP COLUMN `" . $column_name . "`";
            $query = $database->prepare($sql);
            return $query->execute();
        } catch (PDOException $e) {
            return false;
        }
    }

    /**
     * Get the primary key column name for a table
     * @param string $database_name
     * @param string $table_name
     * @return string|null
     */
    public static function getPrimaryKeyColumn($database_name, $table_name)
    {
        $columns = self::getTableColumns($database_name, $table_name);
        foreach ($columns as $column) {
            if ($column['Key'] === 'PRI') {
                return $column['Field'];
            }
        }
        return null;
    }

    /**
     * Get a single row by primary key
     * @param string $database_name
     * @param string $table_name
     * @param mixed $pk_value
     * @return array|null
     */
    public static function getRow($database_name, $table_name, $pk_value)
    {
        $pk_column = self::getPrimaryKeyColumn($database_name, $table_name);
        if (!$pk_column) {
            return null;
        }

        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "SELECT * FROM `" . $database_name . "`.`" . $table_name . "` WHERE `" . $pk_column . "` = :pk_value LIMIT 1";
        $query = $database->prepare($sql);
        $query->execute(array(':pk_value' => $pk_value));

        return $query->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * Update a row in the table
     * @param string $database_name
     * @param string $table_name
     * @param mixed $pk_value
     * @param array $data - associative array of column => value
     * @return bool
     */
    public static function updateRow($database_name, $table_name, $pk_value, $data)
    {
        if (!$database_name || !$table_name || !$pk_value || empty($data)) {
            return false;
        }

        $pk_column = self::getPrimaryKeyColumn($database_name, $table_name);
        if (!$pk_column) {
            return false;
        }

        $database = DatabaseFactory::getFactory()->getConnection();

        $set_parts = array();
        $params = array();
        $i = 0;
        foreach ($data as $column => $value) {
            if ($column === $pk_column) {
                continue;
            }
            $param_name = ':param_' . $i;
            $set_parts[] = "`" . $column . "` = " . $param_name;
            $params[$param_name] = $value === '' ? null : $value;
            $i++;
        }

        if (empty($set_parts)) {
            return false;
        }

        $params[':pk_value'] = $pk_value;

        try {
            $sql = "UPDATE `" . $database_name . "`.`" . $table_name . "` SET " . implode(', ', $set_parts) . " WHERE `" . $pk_column . "` = :pk_value";
            $query = $database->prepare($sql);
            return $query->execute($params);
        } catch (PDOException $e) {
            return false;
        }
    }

    /**
     * Delete a row from the table
     * @param string $database_name
     * @param string $table_name
     * @param mixed $pk_value
     * @return bool
     */
    public static function deleteRow($database_name, $table_name, $pk_value)
    {
        if (!$database_name || !$table_name || !$pk_value) {
            return false;
        }

        $pk_column = self::getPrimaryKeyColumn($database_name, $table_name);
        if (!$pk_column) {
            return false;
        }

        $database = DatabaseFactory::getFactory()->getConnection();

        try {
            $sql = "DELETE FROM `" . $database_name . "`.`" . $table_name . "` WHERE `" . $pk_column . "` = :pk_value";
            $query = $database->prepare($sql);
            return $query->execute(array(':pk_value' => $pk_value));
        } catch (PDOException $e) {
            return false;
        }
    }

    /**
     * Insert a new row into the table
     * @param string $database_name
     * @param string $table_name
     * @param array $data - associative array of column => value
     * @return bool|int - returns insert ID on success, false on failure
     */
    public static function insertRow($database_name, $table_name, $data)
    {
        if (!$database_name || !$table_name || empty($data)) {
            return false;
        }

        $database = DatabaseFactory::getFactory()->getConnection();

        $columns = array();
        $placeholders = array();
        $params = array();
        $i = 0;

        foreach ($data as $column => $value) {
            if ($value === '' || $value === null) {
                continue;
            }
            $columns[] = "`" . $column . "`";
            $param_name = ':param_' . $i;
            $placeholders[] = $param_name;
            $params[$param_name] = $value;
            $i++;
        }

        if (empty($columns)) {
            return false;
        }

        try {
            $sql = "INSERT INTO `" . $database_name . "`.`" . $table_name . "` (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $placeholders) . ")";
            $query = $database->prepare($sql);
            $query->execute($params);
            return $database->lastInsertId();
        } catch (PDOException $e) {
            return false;
        }
    }

    /**
     * Format bytes to human readable format
     * @param int $bytes
     * @return string
     */
    private static function formatBytes($bytes)
    {
        if ($bytes >= 1073741824) {
            return number_format($bytes / 1073741824, 2) . ' GB';
        } elseif ($bytes >= 1048576) {
            return number_format($bytes / 1048576, 2) . ' MB';
        } elseif ($bytes >= 1024) {
            return number_format($bytes / 1024, 2) . ' KB';
        } elseif ($bytes > 1) {
            return $bytes . ' bytes';
        } elseif ($bytes == 1) {
            return '1 byte';
        } else {
            return '0 bytes';
        }
    }
}