<?php

namespace PloverCRM\Core\Api\V1;

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

/**
 * Business Information Settings Endpoint
 *
 * GET /wp-json/plover-crm/v1/settings/business-information
 * PUT /wp-json/plover-crm/v1/settings/business-information
 */
class BusinessInformationSettingsEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/settings/business-information';
    }

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

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

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

    private function getBusinessInformation()
    {
        if (!Permissions::canAccessSetting('business_information', 'view')) {
            return $this->error(
                'You do not have permission to view business information.',
                403,
                'business_information_read_permission_denied'
            );
        }

        return $this->success([
            'business_information' => BusinessInformationService::get(),
        ]);
    }

    private function updateBusinessInformation(WP_REST_Request $request)
    {
        if (!Permissions::canAccessSetting('business_information', 'manage')) {
            return $this->error(
                'You do not have permission to update business information.',
                403,
                'business_information_update_permission_denied'
            );
        }

        $payload = $request->get_json_params();
        $businessInformation = $payload['business_information'] ?? [];

        if ($businessInformation === null) {
            $businessInformation = [];
        }

        if (!is_array($businessInformation)) {
            return $this->error(
                'Business information payload must be an object.',
                422,
                'business_information_invalid_payload'
            );
        }

        $businessEmail = trim((string) ($businessInformation['businessEmail'] ?? ''));
        if ($businessEmail !== '' && !is_email($businessEmail)) {
            return $this->error(
                'Please provide a valid business email address.',
                422,
                'business_information_invalid_email'
            );
        }

        $updated = BusinessInformationService::update($businessInformation);

        return $this->success([
            'business_information' => $updated,
            'message' => $updated
                ? 'Business information updated successfully.'
                : 'Business information cleared successfully.',
        ]);
    }
}
