<?php
/**
 * BookiFlex Background Jobs Extension
 *
 * @package    BookiFlex
 * @subpackage BackgroundJobs
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Extensions\BackgroundJobs\Admin;

use BookiFlex\Core\Admin\Field\SectionNotice;
use BookiFlex\Extensions\BackgroundJobs\Contract\HealthStatus;
use BookiFlex\Extensions\BackgroundJobs\Service\HealthChecker;
use Carbon_Fields\Field;

defined( 'ABSPATH' ) || exit;

/**
 * Background Jobs Settings
 *
 * Settings UI for the Background Jobs extension.
 */
class BackgroundJobsSettings
{
    /**
     * Build settings fields
     *
     * @return array Carbon Fields array
     */
    public function __invoke(): array
    {
        return [
            Field::make('separator', 'bflex__bgj__external_sep', __('External Cron Setup', 'bookiflex')),
            SectionNotice::make(
                'bflex__bgj__description',
                __('BookiFlex uses background jobs to send emails and process scheduled actions. These jobs run automatically, but on low-traffic sites they may be delayed.', 'bookiflex'),
            ),

            // External Cron Setup (static HTML with inline onclick)
            Field::make('html', 'bflex__bgj__external_cron')
                ->set_classes(['bflex-bgj-external-cron'])
                ->set_html($this->renderExternalCronUI()),
        ];
    }

    /**
     * Render description HTML
     *
     * @return string HTML markup
     */
    private function renderDescription(): string
    {
        return sprintf(
            '<p>%s</p>',
            esc_html__('BookiFlex uses background jobs to send emails and process scheduled actions.
These jobs run automatically, but on low-traffic sites they may be delayed.', 'bookiflex')
        );
    }

    /**
     * Render dynamic health status block
     *
     * @param HealthStatus $status Health status object
     * @return string HTML markup
     */
    private function renderHealthStatus(HealthStatus $status): string
    {
        $statusText = match ($status->status) {
            'ok' => __('OK', 'bookiflex'),
            'warning' => __('Warning', 'bookiflex'),
            'delayed' => __('Delayed', 'bookiflex'),
            default => __('Unknown', 'bookiflex'),
        };

        $statusColor = match ($status->status) {
            'ok' => '#46b450',
            'warning' => '#ffb900',
            'delayed' => '#dc3232',
            default => '#8c8f94',
        };

        $lastRun = $status->lastRunTime
            ? human_time_diff($status->lastRunTime) . ' ' . __('ago', 'bookiflex')
            : __('Never', 'bookiflex');

        return sprintf(
            '
            <div style="padding: 15px; background: #f9f9f9; border-left: 4px solid %s; margin: 10px 0;">
                <h3 style="margin-top: 0;">%s</h3>
                <p style="margin: 5px 0;"><strong>%s:</strong> %s</p>
                <p style="margin: 5px 0;"><strong>%s:</strong> %d</p>
                <p style="margin: 5px 0;">&nbsp;</p>
                <p style="margin: 5px 0;"><strong>%s:</strong> <span style="color: %s; font-weight: 600;">%s</span></p>
            </div>
            ',
            esc_attr($statusColor),
            esc_html__('Background jobs status', 'bookiflex'),
            esc_html__('Last run', 'bookiflex'),
            esc_html($lastRun),
            esc_html__('Pending jobs', 'bookiflex'),
            $status->pendingJobsCount,
            esc_html__('Status', 'bookiflex'),
            esc_attr($statusColor),
            esc_html($statusText)
        );
    }

    /**
     * Render external cron setup UI
     *
     * @return string HTML markup with inline JavaScript
     */
    private function renderExternalCronUI(): string
    {
        $endpoint = rest_url('bflex/v1/cron');

        return sprintf(
            '
            <div class="bflex-external-cron-block" style="padding: 15px; background: #f9f9f9; border: 1px solid #ddd; margin: 10px 0;">
                <p class="description">%s</p>
                <div class="endpoint-display" style="margin: 15px 0; display: flex; gap: 10px; align-items: center;">
                    <code id="bflex-cron-endpoint" style="flex: 1; padding: 10px; background: #fff; border: 1px solid #ddd; display: block;">%s</code>
                    <button type="button" class="button" onclick="navigator.clipboard.writeText(document.getElementById(\'bflex-cron-endpoint\').textContent).then(() => { this.textContent = \'%s\'; setTimeout(() => this.textContent = \'%s\', 2000); })">%s</button>
                </div>
                <p><a href="https://cron-job.org" target="_blank" class="button">%s</a></p>
                <p class="description">%s</p>
            </div>
            ',
            esc_html__('To ensure reliable and timely email delivery, we recommend setting up an external cron job that runs every 5 minutes.:', 'bookiflex'),
            esc_html($endpoint),
            esc_js(__('Copied!', 'bookiflex')),
            esc_js(__('Copy URL', 'bookiflex')),
            esc_html__('Copy URL', 'bookiflex'),
            esc_html__('Setup External Cron', 'bookiflex'),
            sprintf(
                /* translators: %s: example of online cron services */
                esc_html__('Recommended: Call this endpoint every 5 minutes via external service (e.g., %s)', 'bookiflex'),
                'cron-job.org, UptimeRobot'
            )
        );
    }
}
