<?php

namespace WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers;

use WP_REST_Request;
use WP_REST_Response;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use WPUltimateSecurity\UltimateSecurity\Modules\Authentication\LoginNotifications;
use WPUltimateSecurity\UltimateSecurity\Modules\Authentication\LoginNotifications\DigestService;
use WPUltimateSecurity\UltimateSecurity\Support\Validation\EmailValidator;

/**
 * REST API Controller for Login Notifications
 *
 * Handles API endpoints for login notification settings and data.
 */
class LoginNotificationsController
{
    /**
     * Get login notification settings
     *
     * @param WP_REST_Request $request REST request object
     * @return WP_REST_Response
     */
    public static function get_settings(WP_REST_Request $request): WP_REST_Response
    {
        $options = Utils::ultimate_security_get_option();
        $settings = $options['security']['login_notifications'] ?? [];

        // Include admin email as default if notification_email is empty
        if (empty($settings['notification_email'])) {
            $settings['default_email'] = get_option('admin_email');
        }

        // Get next scheduled times for cron jobs
        $settings['next_daily_digest'] = wp_next_scheduled('ultimate_security_daily_login_digest');
        $settings['next_weekly_summary'] = wp_next_scheduled('ultimate_security_weekly_login_summary');

        if ($settings['next_daily_digest']) {
            $settings['next_daily_digest_formatted'] = wp_date(
                get_option('date_format') . ' ' . get_option('time_format'),
                $settings['next_daily_digest']
            );
        }

        if ($settings['next_weekly_summary']) {
            $settings['next_weekly_summary_formatted'] = wp_date(
                get_option('date_format') . ' ' . get_option('time_format'),
                $settings['next_weekly_summary']
            );
        }

        return new WP_REST_Response($settings, 200);
    }

    /**
     * Update login notification settings
     *
     * @param WP_REST_Request $request REST request object
     * @return WP_REST_Response
     */
    public static function update_settings(WP_REST_Request $request): WP_REST_Response
    {
        $options = Utils::ultimate_security_get_option();
        $data = $request->get_json_params();

        // Validate email if provided using EmailValidator
        if (!empty($data['notification_email'])) {
            $emailValidator = EmailValidator::create()->withDnsCheck();
            if (!$emailValidator->validate($data['notification_email'])) {
                $errors = $emailValidator->getErrors();
                return new WP_REST_Response([
                    'success' => false,
                    'message' => !empty($errors) ? $errors[0] : __('Invalid email address', 'ultimate-security'),
                ], 400);
            }
        }

        // Validate threshold
        if (isset($data['failed_threshold'])) {
            $threshold = intval($data['failed_threshold']);
            if ($threshold < 1 || $threshold > 100) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => __('Failed threshold must be between 1 and 100', 'ultimate-security'),
                ], 400);
            }
            $data['failed_threshold'] = (string) $threshold;
        }

        // Sanitize and validate allowed fields
        $allowed_fields = [
            'enabled',
            'notify_on_failed',
            'failed_threshold',
            'notify_on_lockout',
            'notify_on_new_ip',
            'notify_on_new_device',
            'notify_on_success_after_fail',
            'daily_digest',
            'daily_digest_time',
            'weekly_summary',
            'weekly_summary_day',
            'notification_email',
            'include_geolocation',
            'one_click_block',
        ];

        foreach ($data as $key => $value) {
            if (in_array($key, $allowed_fields, true)) {
                $options['security']['login_notifications'][$key] = sanitize_text_field($value);
            }
        }

        Utils::ultimate_security_update_option($options);

        // Reschedule cron jobs if settings changed
        self::reschedule_cron_jobs($options['security']['login_notifications']);

        return new WP_REST_Response([
            'success' => true,
            'message' => __('Settings saved successfully', 'ultimate-security'),
        ], 200);
    }

    /**
     * Get recent notifications/events
     *
     * @param WP_REST_Request $request REST request object
     * @return WP_REST_Response
     */
    public static function get_recent(WP_REST_Request $request): WP_REST_Response
    {
        $limit = $request->get_param('limit');
        $limit = $limit ? intval($limit) : 50;
        $limit = min(max($limit, 1), 100);

        $recent = DigestService::get_recent_activity($limit);

        // Get summary statistics
        $stats_24h = DigestService::get_summary_stats(strtotime('-24 hours'));
        $stats_7d = DigestService::get_summary_stats(strtotime('-7 days'));

        return new WP_REST_Response([
            'events' => $recent,
            'stats' => [
                'last_24h' => $stats_24h,
                'last_7d' => $stats_7d,
            ],
        ], 200);
    }

    /**
     * Send test notification
     *
     * @param WP_REST_Request $request REST request object
     * @return WP_REST_Response
     */
    public static function send_test(WP_REST_Request $request): WP_REST_Response
    {
        $email = $request->get_param('email');

        if (empty($email)) {
            $options = Utils::ultimate_security_get_option();
            $email = $options['security']['login_notifications']['notification_email'] ?? '';

            if (empty($email)) {
                $email = get_option('admin_email');
            }
        }

        // Validate email using EmailValidator with DNS check
        $emailValidator = EmailValidator::create()->withDnsCheck();
        if (!$emailValidator->validate($email)) {
            $errors = $emailValidator->getErrors();
            return new WP_REST_Response([
                'success' => false,
                'message' => !empty($errors) ? $errors[0] : __('Invalid email address', 'ultimate-security'),
            ], 400);
        }

        $result = LoginNotifications::send_test_notification($email);

        if ($result) {
            return new WP_REST_Response([
                'success' => true,
                'message' => sprintf(
                    /* translators: %s: Email address */
                    __('Test notification sent to %s', 'ultimate-security'),
                    $email
                ),
            ], 200);
        }

        return new WP_REST_Response([
            'success' => false,
            'message' => __('Failed to send test notification. Please check your WordPress email settings.', 'ultimate-security'),
        ], 500);
    }

    /**
     * Clear notification history
     *
     * @param WP_REST_Request $request REST request object
     * @return WP_REST_Response
     */
    public static function clear_history(WP_REST_Request $request): WP_REST_Response
    {
        delete_option('ultimate_security_notification_log');

        return new WP_REST_Response([
            'success' => true,
            'message' => __('Notification history cleared', 'ultimate-security'),
        ], 200);
    }

    /**
     * Trigger digest manually (for testing)
     *
     * @param WP_REST_Request $request REST request object
     * @return WP_REST_Response
     */
    public static function trigger_digest(WP_REST_Request $request): WP_REST_Response
    {
        $type = $request->get_param('type');

        if ($type === 'daily') {
            LoginNotifications::send_daily_digest();
            return new WP_REST_Response([
                'success' => true,
                'message' => __('Daily digest triggered', 'ultimate-security'),
            ], 200);
        }

        if ($type === 'weekly') {
            LoginNotifications::send_weekly_summary();
            return new WP_REST_Response([
                'success' => true,
                'message' => __('Weekly summary triggered', 'ultimate-security'),
            ], 200);
        }

        return new WP_REST_Response([
            'success' => false,
            'message' => __('Invalid digest type. Use "daily" or "weekly".', 'ultimate-security'),
        ], 400);
    }

    /**
     * Get dashboard statistics
     *
     * @param WP_REST_Request $request REST request object
     * @return WP_REST_Response
     */
    public static function get_stats(WP_REST_Request $request): WP_REST_Response
    {
        $period = $request->get_param('period');

        $since = match ($period) {
            '1h' => strtotime('-1 hour'),
            '6h' => strtotime('-6 hours'),
            '24h' => strtotime('-24 hours'),
            '7d' => strtotime('-7 days'),
            '30d' => strtotime('-30 days'),
            default => strtotime('-24 hours'),
        };

        $events = LoginNotifications::get_events_since($since);

        if ($period === '7d' || $period === '30d') {
            $stats = DigestService::compile_weekly_stats($events);
        } else {
            $stats = DigestService::compile_daily_stats($events);
        }

        return new WP_REST_Response([
            'success' => true,
            'period' => $period,
            'stats' => $stats,
        ], 200);
    }

    /**
     * Reschedule cron jobs based on new settings
     *
     * @param array $settings Login notification settings
     */
    protected static function reschedule_cron_jobs(array $settings): void
    {
        // Clear existing schedules
        wp_clear_scheduled_hook('ultimate_security_daily_login_digest');
        wp_clear_scheduled_hook('ultimate_security_weekly_login_summary');

        // Re-register the module to set up new schedules
        if ($settings['enabled'] === '1') {
            LoginNotifications::register();
        }
    }
}
