<?php

namespace BitApps\SocialPro\HTTP\Services\Notification;

/**
 * Thin static wrapper that bridges WordPress hooks to the
 * EmailNotificationService, plus helpers to (un)schedule the digest cron
 * on a custom "every N day|week|month" interval.
 */
class NotificationHandler
{
    public const DIGEST_HOOK = 'bit_social_pro_digest';

    public const DIGEST_SCHEDULE = 'bit_social_pro_digest_schedule';

    // Legacy hooks from the earlier daily/weekly implementation (cleared on resave).
    public const LEGACY_HOOKS = ['bit_social_pro_digest_daily', 'bit_social_pro_digest_weekly'];

    /**
     * Listener for the free plugin's `bit_social_log_data` action.
     *
     * @param int|null     $scheduleId
     * @param string       $platform
     * @param int          $status     0 = fail, 1 = success
     * @param array|object $details
     */
    public static function onLog($scheduleId, $platform, $status, $details)
    {
        if ((int) $status !== 0) {
            return;
        }

        $service = new EmailNotificationService();
        $settings = $service->getSettings();

        if (empty($settings['isEnabled']) || empty($settings['onFailure'])) {
            return;
        }

        $service->sendFailureEmail($scheduleId, $platform, $details);
    }

    public static function runDigest()
    {
        (new EmailNotificationService())->sendDigest();
    }

    /**
     * Registers the dynamic digest interval (from saved settings) so
     * wp_schedule_event() can use it. Hooked to `cron_schedules`.
     *
     * @param array $schedules
     *
     * @return array
     */
    public static function registerDigestSchedule($schedules)
    {
        $interval = self::digestIntervalSeconds((new EmailNotificationService())->getSettings());

        if ($interval > 0) {
            $schedules[self::DIGEST_SCHEDULE] = [
                'interval' => $interval,
                'display'  => __('Bit Social digest interval', 'bit-social'),
            ];
        }

        return $schedules;
    }

    /**
     * (Re)schedules the digest cron from the saved notification settings.
     *
     * @param array $settings
     */
    public static function rescheduleDigest($settings)
    {
        self::clearDigestSchedules();

        $enabled = !empty($settings['isEnabled']) && !empty($settings['digestEnabled']);
        $interval = self::digestIntervalSeconds($settings);

        if ($enabled && $interval > 0) {
            wp_schedule_event(time() + $interval, self::DIGEST_SCHEDULE, self::DIGEST_HOOK);
        }
    }

    public static function clearDigestSchedules()
    {
        wp_clear_scheduled_hook(self::DIGEST_HOOK);

        foreach (self::LEGACY_HOOKS as $hook) {
            wp_clear_scheduled_hook($hook);
        }
    }

    /**
     * Converts the digest interval/unit settings to seconds.
     *
     * @param array $settings
     *
     * @return int
     */
    public static function digestIntervalSeconds($settings)
    {
        $count = isset($settings['digestInterval']) ? max(1, (int) $settings['digestInterval']) : 1;
        $unit = isset($settings['digestUnit']) ? $settings['digestUnit'] : 'week';

        $unitSeconds = [
            'day'   => DAY_IN_SECONDS,
            'week'  => WEEK_IN_SECONDS,
            'month' => MONTH_IN_SECONDS,
        ];

        $seconds = isset($unitSeconds[$unit]) ? $unitSeconds[$unit] : WEEK_IN_SECONDS;

        return $count * $seconds;
    }
}
