<?php

namespace EasyLinkAutomations\Triggers\LearnPress;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Triggers\BaseTrigger;

final class CourseCompletedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'learnpress/course_completed';
    }

    public static function getName(): string
    {
        return __('Course Completed', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Fires when a user completes a course in LearnPress.', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'LearnPress';
    }

    public static function getIcon(): string
    {
        return 'learnpress';
    }


    public static function isAvailable(): bool
    {
        return class_exists('LearnPress');
    }

    public static function getOutputFields(): array
    {
        return [
            'user_id'       => ['label' => 'User ID', 'type' => 'number'],
            'user_login'    => ['label' => 'Username', 'type' => 'string'],
            'user_email'    => ['label' => 'User Email', 'type' => 'email'],
            'user_name'     => ['label' => 'Display Name', 'type' => 'string'],
            'course_id'     => ['label' => 'Course ID', 'type' => 'number'],
            'course_title'  => ['label' => 'Course Title', 'type' => 'string'],
            'course_url'    => ['label' => 'Course URL', 'type' => 'url'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [];
    }

    public function register(callable $callback): void
    {
        $this->callback = $callback;

        add_action('learn-press/user-course-finished', function (mixed $courseId, mixed $userId, mixed $result): void {
            $data = $this->handle($courseId, $userId);
            if (empty($data)) {
                return;
            }
            $this->fire($data);
        }, 10, 3);
    }

    public function handle(mixed ...$args): array
    {
        [$courseId, $userId] = $args;

        if (empty($userId)) {
            return [];
        }

        $user = get_userdata((int) $userId);

        return [
            'user_id'      => $userId,
            'user_login'   => $user ? $user->user_login : '',
            'user_email'   => $user ? $user->user_email : '',
            'user_name'    => $user ? $user->display_name : '',
            'course_id'    => $courseId,
            'course_title' => get_the_title((int) $courseId),
            'course_url'   => get_permalink((int) $courseId),
        ];
    }
}
