<?php

namespace PloverCRM\Modules\Reminders\Endpoints;

use PloverCRM\Common\Permissions;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\Reminders\Settings;
use WP_REST_Request;

/**
 * Reminders Settings REST API Endpoint
 * 
 * GET /wp-json/plover-crm/v1/reminders/settings - Get reminder alert message settings
 * PUT /wp-json/plover-crm/v1/reminders/settings - Update reminder alert message settings
 */
class SettingsEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/reminders/settings';
    }

    public function getMethod()
    {
        return ['GET', 'PUT'];
    }

    public function handle(WP_REST_Request $request)
    {
        if ($request->get_method() === 'GET') {
            return $this->getSettings();
        }

        return $this->updateSettings($request);
    }

    private function getSettings()
    {
        if (!Permissions::canAccessSetting('notification_templates', 'view')) {
            return $this->error(
                'You do not have permission to view reminder alert templates.',
                403,
                'reminder_templates_read_permission_denied'
            );
        }

        $settings = Settings::getSettings();

        return $this->success([
            'settings' => [
                'title' => $settings['notification_title'],
                'body_template' => $settings['notification_body'],
            ],
            'placeholders' => Settings::getAllPlaceholders(),
            'preview' => Settings::getPreview($settings),
        ]);
    }

    private function updateSettings(WP_REST_Request $request)
    {
        if (!Permissions::canAccessSetting('notification_templates', 'manage')) {
            return $this->error(
                'You do not have permission to manage reminder alert templates.',
                403,
                'reminder_templates_manage_permission_denied'
            );
        }

        $current = Settings::getSettings();
        $data = $request->get_json_params();

        if (isset($data['title'])) {
            $current['notification_title'] = sanitize_text_field($data['title']);
        }

        if (isset($data['body_template'])) {
            $current['notification_body'] = sanitize_textarea_field($data['body_template']);
        }

        update_option(Settings::OPTION_NAME, $current);

        return $this->success([
            'settings' => [
                'title' => $current['notification_title'],
                'body_template' => $current['notification_body'],
            ],
            'placeholders' => Settings::getAllPlaceholders(),
            'preview' => Settings::getPreview($current),
            'message' => 'Reminder alert message saved successfully',
        ]);
    }
}
