<?php
declare(strict_types=1);

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;

return function (App $app) {
    // Health check endpoint
    $app->get('/api/health', function (Request $request, Response $response) {
        $data = [
            'status' => 'ok',
            'timestamp' => time(),
            'message' => 'Tigo Nova API is running'
        ];
        $response->getBody()->write(json_encode($data));
        return $response->withHeader('Content-Type', 'application/json');
    });// Newsletter subscription endpoint
    $app->post('/api/newsletter/subscribe', function (Request $request, Response $response) {
        require_once __DIR__ . '/config.php';
        $data = $request->getParsedBody();
        $email = $data['email'] ?? '';
        $name = $data['name'] ?? '';
        $recaptchaToken = $data['recaptchaToken'] ?? '';

        // Verify reCAPTCHA v3
        if (empty($recaptchaToken)) {
            $response->getBody()->write(json_encode([
                'success' => false,
                'message' => 'reCAPTCHA verification failed (no token)'
            ]));
            return $response
                ->withHeader('Content-Type', 'application/json')
                ->withStatus(400);
        }
        $recaptchaSecret = RECAPTCHA_SECRET_KEY;
        $verifyUrl = 'https://www.google.com/recaptcha/api/siteverify';
        $verifyData = [
            'secret' => $recaptchaSecret,
            'response' => $recaptchaToken,
            'remoteip' => $request->getServerParams()['REMOTE_ADDR'] ?? null
        ];
        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($verifyData),
                'timeout' => 5
            ]
        ];
        $context  = stream_context_create($options);
        $result = @file_get_contents($verifyUrl, false, $context);
        if ($result === false) {
            $response->getBody()->write(json_encode([
                'success' => false,
                'message' => 'reCAPTCHA verification failed (no response)'
            ]));
            return $response
                ->withHeader('Content-Type', 'application/json')
                ->withStatus(400);
        }
        $recaptchaResult = json_decode($result, true);
        // Only check score in production
        if (APP_ENV === 'production' && (empty($recaptchaResult['success']) || ($recaptchaResult['score'] ?? 0) < 0.5)) {
            $response->getBody()->write(json_encode([
                'success' => false,
                'message' => 'reCAPTCHA verification failed (score too low)'
            ]));
            return $response
                ->withHeader('Content-Type', 'application/json')
                ->withStatus(400);
        }
        
        // Validate email
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $response->getBody()->write(json_encode([
                'success' => false,
                'message' => 'Invalid email address'
            ]));
            return $response
                ->withHeader('Content-Type', 'application/json')
                ->withStatus(400);
        }
        
        // Validate name
        if (empty($name)) {
            $response->getBody()->write(json_encode([
                'success' => false,
                'message' => 'Name is required'
            ]));
            return $response
                ->withHeader('Content-Type', 'application/json')
                ->withStatus(400);
        }
        
        // Store in database
        try {
            $db = $this->get('db');
            $stmt = $db->prepare('INSERT INTO newsletter_subscribers (name, email, subscribed_at, ip_address) VALUES (?, ?, NOW(), ?)');
            $clientIp = $request->getServerParams()['REMOTE_ADDR'] ?? '';
            $stmt->execute([$name, $email, $clientIp]);
            
            $response->getBody()->write(json_encode([
                'success' => true,
                'message' => 'Successfully subscribed to the newsletter'
            ]));
            return $response->withHeader('Content-Type', 'application/json');
        } catch (\PDOException $e) {
            // Check if it's a duplicate entry error
            if ($e->getCode() == 23000) {
                $response->getBody()->write(json_encode([
                    'success' => false,
                    'message' => 'This email is already subscribed'
                ]));
                return $response
                    ->withHeader('Content-Type', 'application/json')
                    ->withStatus(400);
            }
            
            $response->getBody()->write(json_encode([
                'success' => false,
                'message' => 'An error occurred while processing your request'
            ]));
            return $response
                ->withHeader('Content-Type', 'application/json')
                ->withStatus(500);
        }
    });
    
    // API Documentation (OpenAPI/Swagger)
    $app->get('/api/docs', function (Request $request, Response $response) {
        $response->getBody()->write(file_get_contents(APP_ROOT . '/public/docs/index.html'));
        return $response->withHeader('Content-Type', 'text/html');
    });

    // Include feedback routes
    $feedbackRoutes = require __DIR__ . '/routes/feedback.php';
    $feedbackRoutes($app);
};
