<?php

namespace GriffinForms;

class Loader
{   
    /**
     * Handle missing class files without breaking the site.
     *
     * @param string $class Fully qualified class name.
     * @param string $file  Expected file path.
     */
    private static function handleMissingFile(string $class, string $file): void
    {
        $message = sprintf(
            'GriffinForms Autoloader: Class file not found for %s at %s',
            $class,
            $file
        );
        $remedy = 'Verify the class file exists and matches the lowercase autoload path, or disable the related integration temporarily.';

        // Log for debugging; prefer WordPress debug log when available.
        if (function_exists('error_log')) {
            error_log($message);
        }

        if (function_exists('do_action')) {
            do_action('griffinforms_autoload_error', $class, $file, $message);
        }

        // Persist a log entry for visibility in the admin logs UI (if available).
        try {
            if (class_exists('\\GriffinForms\\Log')) {
                $log = \GriffinForms\Log::getInstance();
                $user_id = function_exists('get_current_user_id') ? (int) get_current_user_id() : 0;
                $log->add(
                    'error',
                    'autoload',
                    0,
                    $user_id,
                    $message . ' Remedy: ' . $remedy,
                    'Autoloader'
                );
            }
        } catch (\Throwable $e) {
            // Never allow logging failures to break site load.
        }
    }

    public static function loadClass($class)
    {
        $is_griffinforms_class = strpos($class, 'GriffinForms\\') === 0 && strpos($class, 'GriffinFormsPro\\') !== 0;
        $is_sendgrid_class = strpos($class, 'SendGrid') === 0 ? true : false;

        if ($is_griffinforms_class) {
            $internal_class = str_replace('GriffinForms\\', '', $class);
            $file = plugin_dir_path(__FILE__) . strtolower(str_replace('\\', '/', $internal_class)) . '.php';
            
            if (file_exists($file)) {
                require_once $file; // Ensures the file is loaded only once
            } else {
                self::handleMissingFile($class, $file);
            }
        }

        if ($is_sendgrid_class) {
            $internal_class = str_replace('SendGrid\\', '', $class);
            $file = plugin_dir_path(__FILE__) . 'external/sendgrid/' . strtolower(str_replace('\\', '/', $internal_class)) . '.php';
            
            if (file_exists($file)) {
                require_once $file; // Ensures the file is loaded only once
            } else {
                self::handleMissingFile($class, $file);
            }
        }
    }
}
