<?php

class DomainConnectAPI
{
  private $namespace = 'wb-onboard/v1';
  private $route = '/domain-connect';

  public function register_routes()
  {
    register_rest_route($this->namespace, $this->route, [
      [
        'methods' => 'POST',
        'callback' => [$this, 'handle_domain_form'],
        'permission_callback' => '__return_true',
        'args' => [
          'hasDomain' => [
            'required' => true,
            'type' => 'boolean'
          ],
          'domain' => [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field'
          ],
          'provider' => [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field'
          ],
          'purchaseOption' => [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field'
          ],
          'desiredDomain' => [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field'
          ],
          'hasPurchasedDomain' => [
            'type' => 'boolean'
          ]
        ]
      ]
    ]);
  }

  public function handle_domain_form($request)
  {
    $params = $request->get_params();
    $hasDomain = $params['hasDomain'];
    $errors = [];

    if ($hasDomain) {
      // Validation pour "I already have a domain"
      if (empty($params['domain'])) {
        $errors[] = 'Domain name is required';
      }
      if (empty($params['provider'])) {
        $errors[] = 'Provider is required';
      }
    } else {
      // Validation pour "I don't have a domain"
      if (empty($params['purchaseOption'])) {
        $errors[] = 'Please select a purchase option';
      } else {
        if ($params['purchaseOption'] === 'mio') {
          if (empty($params['desiredDomain'])) {
            $errors[] = 'Desired domain name is required';
          }
        } else if ($params['purchaseOption'] === 'self') {
          if (empty($params['hasPurchasedDomain'])) {
            $errors[] = 'Please confirm that you have purchased your domain';
          }
          if (empty($params['domain'])) {
            $errors[] = 'Please enter the domain name you purchased';
          }
        }
      }
    }

    if (!empty($errors)) {
      return new \WP_Error(
        'validation_failed',
        'Form validation failed',
        [
          'status' => 400,
          'errors' => $errors
        ]
      );
    }

    // Mettre à jour l'option
    $updated = update_option('form-connect-domaine-live-site', true);

    if (!$updated) {
      return new \WP_Error(
        'update_failed',
        'Failed to update domain status',
        ['status' => 500]
      );
    }

    $message = "[ACTION REQUIRED] Customer wants to go live on their personalized domain:\n";
    $message .= "- Customer: " . get_site_url() . "\n";
    $message .= "- Request type: " . ($params['hasDomain'] ? 'Has Domain' : 'Needs Domain') . "\n";

    if ($params['hasDomain']) {
      $message .= "- Domain: " . $params['domain'] . "\n";
      $message .= "- Provider: " . $params['provider'] . "\n";
    } else {
      $message .= "- Purchase Option: " . ($params['purchaseOption'] === 'mio' ? 'MioCommerce Purchase' : 'Self Purchase') . "\n";
      if ($params['purchaseOption'] === 'mio') {
        $message .= "- Desired Domain: " . $params['desiredDomain'] . "\n";
      } else {
        $message .= "- Domain: " . $params['domain'] . "\n";
        $message .= "- Domain Purchase Confirmed: " . ($params['hasPurchasedDomain'] ? 'Yes' : 'No') . "\n";
      }
    }

    error_log($message);

    if (!str_contains(get_site_url(), 'localhost')) {
      // Send Slack notification to MioCommerce
      wp_remote_post(
        'https://hooks.slack.com/services/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',
        [
          'body' => json_encode([
            'text' => $message
          ]),
          'headers' => [
            'Content-Type' => 'application/json'
          ],
          'timeout' => 30
        ]
      );

      // Send discord notification to Orphic
      wp_remote_post('https://discordapp.com/api/webhooks/1340153500612562956/7euy5g7APuNmKjqWy1kbfeNpDA6O8TB-m6P7Js8150oa0K5-EEOqcb2IiwAF2hg_rBNs', [
        'body' => [
          'content' => $message
        ]
      ]);
    }

    return rest_ensure_response([
      'success' => true,
      'data' => [
        'message' => 'Domain form processed successfully'
      ]
    ]);
  }
}
