<?php

namespace EasyLinkAutomations\Triggers\AcademyLMS;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user enrolls in a course in Academy LMS.
 */
final class EnrolledCourseTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'academylms/enrolled_course';
    }

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

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

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

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


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

    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'],
            'display_name'      => ['label' => 'Display Name', 'type' => 'string'],
            'first_name'        => ['label' => 'First Name', 'type' => 'string'],
            'last_name'         => ['label' => 'Last Name', 'type' => 'string'],
            'user_role'         => ['label' => 'User Role', 'type' => 'string'],
            'course_id'         => ['label' => 'Course ID', 'type' => 'number'],
            'course_title'      => ['label' => 'Course Title', 'type' => 'string'],
            'course_url'        => ['label' => 'Course URL', 'type' => 'url'],
            'enrollment_id'     => ['label' => 'Enrollment ID', 'type' => 'number'],
            'enrollment_date'   => ['label' => 'Enrollment Date', 'type' => 'datetime'],
            'enrollment_status' => ['label' => 'Enrollment Status', 'type' => 'string'],
        ];
    }

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

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

        add_action('academy/course/after_enroll', function (int $courseId, int $enrollId, int $userId): void {
            if (empty($userId)) {
                return;
            }
            $data = $this->handle($courseId, $enrollId, $userId);
            if (empty($data)) {
                return;
            }
            $this->fire($data);
        }, 10, 3);
    }

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

        global $wpdb;

        $user   = get_userdata((int) $userId);
        $course = get_post((int) $courseId);

        if (!$user || !$course) {
            return [];
        }

        // Fetch the latest enrollment record for this course.
        $enrollment = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->posts} WHERE post_type = %s AND post_parent = %d ORDER BY ID DESC LIMIT 1",
            'academy_enrolled',
            $courseId
        ));

        $roles = $user->roles ?? [];

        return [
            'user_id'           => $user->ID,
            'user_login'        => $user->user_login,
            'user_email'        => $user->user_email,
            'display_name'      => $user->display_name,
            'first_name'        => get_user_meta($user->ID, 'first_name', true),
            'last_name'         => get_user_meta($user->ID, 'last_name', true),
            'user_role'         => $roles[0] ?? '',
            'course_id'         => $course->ID,
            'course_title'      => $course->post_title,
            'course_url'        => get_permalink($course->ID) ?: '',
            'enrollment_id'     => $enrollment ? (int) $enrollment->ID : (int) $enrollId,
            'enrollment_date'   => $enrollment ? $enrollment->post_date : current_time('mysql'),
            'enrollment_status' => $enrollment ? $enrollment->post_status : '',
        ];
    }
}
