<?php

namespace App\Modules\Workflow;

use Illuminate\Support\Facades\DB;

class WorkflowHelpers
{
    public static function getEvents()
    {
        return [
            'creating', 'created', 'updating', 'updated',
            'deleting', 'deleted', 'saving', 'saved',
            'restoring', 'restored',
        ];
    }

    public static function getModels()
    {
        $classes = [];

        foreach (get_declared_classes() as $class) {
            if (is_subclass_of($class, 'ValidationModel') && $class != 'ValidationModel') {
                $short_name = explode('\\', $class);
                $short_name = end($short_name);

                array_push($classes, [
                    'name'       => $class,
                    'short_name' => $short_name,
                    'attributes' => self::getAttributes($class),
                ]);
            }
        }

        return $classes;
    }

    public static function getActions()
    {
        return [];
    }

    public static function getAttributes($model)
    {
        $instance = new $model();

        switch (DB::connection()->getConfig('driver')) {
            case 'pgsql':
                $query = "SELECT column_name FROM information_schema.columns WHERE table_name = '".$instance->getTable()."'";
                $column_name = 'column_name';
                $reverse = true;
                break;

            case 'mysql':
                $query = 'SHOW COLUMNS FROM '.$instance->getTable();
                $column_name = 'Field';
                $reverse = false;
                break;

            case 'sqlsrv':
                $parts = explode('.', $instance->getTable());
                $num = (count($parts) - 1);
                $table = $parts[$num];
                $query = 'SELECT column_name FROM '.DB::connection()->getConfig('database').".INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'".$table."'";
                $column_name = 'column_name';
                $reverse = false;
                break;

            default:
                $error = 'Database driver not supported: '.DB::connection()->getConfig('driver');
                throw new Exception($error);
                break;
        }

        $columns = [];

        foreach (DB::select($query) as $column) {
            $columns[] = $column->$column_name;
        }

        if ($reverse) {
            $columns = array_reverse($columns);
        }

        return $columns;
    }
}
