<?php

namespace App\Http\Controllers\Services;

use ReflectionClass;
use ReflectionMethod;

class FunctionScanner
{
    public function getControllers()
    {
        $allowedControllers = [
            \App\Http\Controllers\DashboardController::class,
            \App\Http\Controllers\WebhookController::class,
            \App\Http\Controllers\UserController::class,
        ];

        $controllers = [];

        foreach ($allowedControllers as $class) {

            if (!class_exists($class)) {
                continue;
            }

            try {

                $reflection = new ReflectionClass($class);

                if ($reflection->isAbstract()) {
                    continue;
                }

                $methods = [];

                foreach ($reflection->getMethods() as $method) {

                    if (
                        $method->class !== $class ||
                        !$method->isPublic() ||
                        str_starts_with($method->name, '__')
                    ) {
                        continue;
                    }

                    $code = $this->getMethodCode($method);

                    $methods[] = [
                        'name' => $method->name,
                        'parameters' => $method->getNumberOfParameters(),
                        'code' => $code,
                        'line_start' => $method->getStartLine(),
                        'line_end' => $method->getEndLine(),
                    ];
                }

                $controllers[] = [
                    'class' => $class,
                    'name' => $reflection->getShortName(),
                    'methods' => $methods,
                ];

            } catch (\Throwable $e) {
                continue;
            }
        }

        return $controllers;
    }

    private function getMethodCode(ReflectionMethod $method)
    {
        $file = $method->getFileName();

        if (!$file || !file_exists($file)) {
            return 'Source code tidak ditemukan.';
        }

        $lines = file($file);

        $start = $method->getStartLine() - 1;
        $length = $method->getEndLine() - $start;

        return implode(
            '',
            array_slice($lines, $start, $length)
        );
    }
}