<?php

namespace BitApps\SocialPro\HTTP\Controllers;

use BitApps\SocialPro\Config;
use BitApps\SocialPro\Deps\BitApps\WPKit\Http\Request\Request;
use BitApps\SocialPro\Deps\BitApps\WPKit\Http\Response;
use BitApps\SocialPro\HTTP\Requests\NotificationUpdateRequest;
use BitApps\SocialPro\HTTP\Services\Notification\EmailNotificationService;
use BitApps\SocialPro\HTTP\Services\Notification\NotificationHandler;

class SettingsController
{
    public function updateGeneralSettings(Request $request)
    {
        // $settings = $request->settings;

        // update simple settings that has not extra works to do
    }

    /**
     * Persists the failure/digest email notification settings and
     * (re)schedules the digest cron accordingly.
     */
    public function updateNotificationSetting(NotificationUpdateRequest $request)
    {
        $incoming = $request->settings;

        if (!isset($incoming['notification']) || !\is_array($incoming['notification'])) {
            return Response::error(['errors' => ['notification' => __('Invalid notification settings!', 'bit-social')]]);
        }

        $notification = wp_parse_args($incoming['notification'], [
            'isEnabled'      => false,
            'recipients'     => '',
            'onFailure'      => false,
            'digestEnabled'  => false,
            'digestInterval' => 1,
            'digestUnit'     => 'week',
        ]);

        $notification['isEnabled'] = (bool) $notification['isEnabled'];
        $notification['onFailure'] = (bool) $notification['onFailure'];
        $notification['digestEnabled'] = (bool) $notification['digestEnabled'];
        $notification['digestInterval'] = max(1, (int) $notification['digestInterval']);

        if (!\in_array($notification['digestUnit'], ['day', 'week', 'month'], true)) {
            $notification['digestUnit'] = 'week';
        }

        // Sanitize recipients and keep only valid emails.
        $recipients = array_filter(array_map('trim', explode(',', (string) $notification['recipients'])));
        $validRecipients = [];
        foreach ($recipients as $email) {
            $email = sanitize_email($email);
            if ($email && is_email($email)) {
                $validRecipients[] = $email;
            }
        }
        $notification['recipients'] = implode(', ', $validRecipients);

        $wantsEmail = $notification['isEnabled'] && ($notification['onFailure'] || $notification['digestEnabled']);
        if ($wantsEmail && empty($validRecipients)) {
            return Response::error(['errors' => ['recipients' => __('Please add at least one valid email address.', 'bit-social')]]);
        }

        // Merge into the existing pro settings to preserve other groups (e.g. cron).
        $proSettings = Config::getOption('settings', []);
        if (!\is_array($proSettings)) {
            $proSettings = [];
        }
        $proSettings['notification'] = $notification;

        Config::updateOption('settings', $proSettings);

        NotificationHandler::rescheduleDigest($notification);

        return Response::success($proSettings);
    }

    /**
     * Sends the digest report immediately for the configured interval window,
     * so the user can preview/trigger it without waiting for the next cron run.
     */
    public function sendDigestNow()
    {
        $result = (new EmailNotificationService())->sendDigest();

        if (empty($result['sent'])) {
            return Response::error(['message' => $result['message']]);
        }

        return Response::success(['message' => $result['message']]);
    }
}
