<?php
if (!defined('ABSPATH')) exit;

use FluentPlayer\Framework\Foundation\Application;
use FluentPlayer\App\Hooks\Handlers\ActivationHandler;
use FluentPlayer\App\Hooks\Handlers\DeactivationHandler;

return function($file) {
    /**
     * Load custom error handler only in debug mode
     * This follows WordPress debugging best practices by:
     * 1. Only loading error handler when WP_DEBUG is true
     * 2. Not directly modifying error_reporting levels
     * 3. Respecting WordPress debug configuration
     */
    $errorHandler = __DIR__ . "/error_handler.php";
    if (defined('WP_DEBUG') && WP_DEBUG && file_exists($errorHandler)) {
        require_once $errorHandler;
    }

    $app = new Application($file);

    register_activation_hook($file, function() use ($app) {
        ($app->make(ActivationHandler::class))->handle();
    });

    register_deactivation_hook($file, function() use ($app) {
        ($app->make(DeactivationHandler::class))->handle();
    });

    add_action('plugins_loaded', function() use ($app) {
        do_action('fluent_player/loaded', $app);

        // Run migrations if DB version is stale
        $currentDBVersion = get_option('fluent_player_db_version');
        if (!$currentDBVersion || version_compare($currentDBVersion, FLUENT_PLAYER_DB_VERSION, '<')) {
            \FluentPlayer\Database\DBMigrator::run();
            update_option('fluent_player_db_version', FLUENT_PLAYER_DB_VERSION, 'no');
        }

        /**
         * Plugin Updater
         */
        $apiUrl = 'https://fluentcommunity.co/wp-admin/admin-ajax.php?action=fluent_player_update&time=' . time();
        new \FluentPlayer\App\Services\PluginManager\Updater($apiUrl, FLUENT_PLAYER_DIR_FILE, array(
            'version'   => FLUENT_PLAYER_VERSION,
            'license'   => '12345',
            'item_name' => 'FluentPlayer',
            'item_id'   => 'fluent-player',
            'author'    => 'wpmanageninja'
        ),
            array(
                'license_status' => 'valid',
                'admin_page_url' => admin_url('admin.php?page=fluent-player#/'),
                'purchase_url'   => 'https://fluentplayer.com',
                'plugin_title'   => 'FluentPlayer'
            )
        );


        add_filter('plugin_row_meta', function ($links, $file) {
            if ('fluent-player/fluent-player.php' !== $file) {
                return $links;
            }

            $checkUpdateUrl = esc_url(admin_url('plugins.php?fluent-player-check-update=' . time()));

            $row_meta = array(
                'check_update' => '<a  style="color: #583fad;font-weight: 600;" href="' . $checkUpdateUrl . '" aria-label="' . esc_attr__('Check Update', 'fluent-player') . '">' . esc_html__('Check Update', 'fluent-player') . '</a>',
            );

            return array_merge($links, $row_meta);

        }, 10, 2);

    });



    return $app;
};
