<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Common\Permissions;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Core\Services\PlaceholderService;
use WP_REST_Request;

/**
 * Push Notification Settings Endpoint
 * 
 * GET /wp-json/plover-crm/v1/settings/push-notifications - Get settings
 * PUT /wp-json/plover-crm/v1/settings/push-notifications - Update settings
 */
class PushNotificationSettingsEndpoint extends AbstractEndpoint
{
    /**
     * Default settings
     */
    const DEFAULTS = [
        'title' => 'New Lead Added!',
        'body_template' => '{full_name} | from {city}, {country} | Workspace: {workspace} | Time: {datetime}',
    ];

    public function getRoute(): string
    {
        return '/settings/push-notifications';
    }

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

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

    /**
     * Get current settings
     */
    private function getSettings()
    {
        if (!Permissions::canAccessSetting('notification_templates', 'view')) {
            return $this->error(
                'You do not have permission to view notification templates.',
                403,
                'notification_templates_read_permission_denied'
            );
        }

        $settings = get_option('plover_crm_push_notifications', []);
        
        // Merge with defaults
        $settings = array_merge(self::DEFAULTS, $settings);

        // Get available placeholders for UI
        $placeholders = PlaceholderService::getAvailablePlaceholders();

        // Generate preview
        $preview = [
            'title' => PlaceholderService::preview($settings['title']),
            'body' => PlaceholderService::preview($settings['body_template']),
        ];

        return $this->success([
            'settings' => $settings,
            'placeholders' => $placeholders,
            'preview' => $preview,
        ]);
    }

    /**
     * Update settings
     */
    private function updateSettings(WP_REST_Request $request)
    {
        if (!Permissions::canAccessSetting('notification_templates', 'manage')) {
            return $this->error(
                'You do not have permission to manage notification templates.',
                403,
                'notification_templates_manage_permission_denied'
            );
        }

        $data = $request->get_json_params();
        
        $current = get_option('plover_crm_push_notifications', []);
        $settings = array_merge(self::DEFAULTS, $current);

        // Update only provided fields
        if (isset($data['title'])) {
            $settings['title'] = sanitize_text_field($data['title']);
        }

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

        update_option('plover_crm_push_notifications', $settings);

        // Generate preview
        $preview = [
            'title' => PlaceholderService::preview($settings['title']),
            'body' => PlaceholderService::preview($settings['body_template']),
        ];

        return $this->success([
            'settings' => $settings,
            'preview' => $preview,
            'message' => 'Settings updated successfully',
        ]);
    }
}
