<?php

declare(strict_types=1);

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

/**
 * Feedback API routes for Amazon product insert card system
 * Handles customer feedback submission and validation
 */
return function (App $app) {
    
    /**
     * Submit customer feedback
     * 
     * @route POST /api/feedback
     */
    $app->post('/api/feedback', function (Request $request, Response $response) {
        try {
            $data = json_decode($request->getBody()->getContents(), true);
            
            // Validate required fields
            $requiredFields = ['product', 'marketplace', 'orderNumber', 'satisfaction', 'usedFor7Days', 'customerName', 'email'];
            foreach ($requiredFields as $field) {
                if (empty($data[$field])) {
                    $response->getBody()->write(json_encode([
                        'success' => false,
                        'message' => "Missing required field: $field"
                    ]));
                    return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
                }
            }
            
            // Validate email format
            if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
                $response->getBody()->write(json_encode([
                    'success' => false,
                    'message' => 'Invalid email format'
                ]));
                return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
            }
            
            // Validate satisfaction level
            $validSatisfactionLevels = ['Very Satisfied', 'Somewhat Satisfied', 'Neither Satisfied Nor Dissatisfied', 'Very Dissatisfied'];
            if (!in_array($data['satisfaction'], $validSatisfactionLevels)) {
                $response->getBody()->write(json_encode([
                    'success' => false,
                    'message' => 'Invalid satisfaction level'
                ]));
                return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
            }
            
            // Get database connection
            $pdo = $this->get('db');
            
            // Check if email already exists
            $emailCheckStmt = $pdo->prepare("SELECT id FROM customer_feedback WHERE email = ?");
            $emailCheckStmt->execute([$data['email']]);
            if ($emailCheckStmt->fetch()) {
                $response->getBody()->write(json_encode([
                    'success' => false,
                    'message' => 'This email has already been used to submit feedback. Each customer can only submit feedback once.'
                ]));
                return $response->withStatus(409)->withHeader('Content-Type', 'application/json');
            }
            
            // Insert feedback data
            $stmt = $pdo->prepare("
                INSERT INTO customer_feedback (
                    product, product_asin, marketplace, order_number, satisfaction, used_for_7_days,
                    customer_name, email, phone, accepts_offers, review_text, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            
            $stmt->execute([
                $data['product'],
                $data['productAsin'] ?? null,
                $data['marketplace'],
                $data['orderNumber'],
                $data['satisfaction'],
                $data['usedFor7Days'],
                $data['customerName'],
                $data['email'],
                $data['phone'] ?? null,
                $data['acceptsOffers'] ? 1 : 0,
                $data['reviewText'] ?? null
            ]);
            
            $response->getBody()->write(json_encode([
                'success' => true,
                'message' => 'Feedback submitted successfully',
                'id' => $pdo->lastInsertId()
            ]));
            
            return $response->withStatus(201)->withHeader('Content-Type', 'application/json');
            
        } catch (PDOException $e) {
            error_log('Feedback submission error: ' . $e->getMessage());
            
            // Check if it's a duplicate entry error (MySQL error code 1062)
            if ($e->getCode() == 23000 && strpos($e->getMessage(), 'unique_email') !== false) {
                $response->getBody()->write(json_encode([
                    'success' => false,
                    'message' => 'This email has already been used to submit feedback. Each customer can only submit feedback once.'
                ]));
                return $response->withStatus(409)->withHeader('Content-Type', 'application/json');
            }
            
            $response->getBody()->write(json_encode([
                'success' => false,
                'message' => 'Internal server error'
            ]));
            return $response->withStatus(500)->withHeader('Content-Type', 'application/json');
        } catch (Exception $e) {
            error_log('Feedback submission error: ' . $e->getMessage());
            $response->getBody()->write(json_encode([
                'success' => false,
                'message' => 'Internal server error'
            ]));
            return $response->withStatus(500)->withHeader('Content-Type', 'application/json');
        }
    });
    
    /**
     * Get feedback statistics (for admin use)
     * 
     * @route GET /api/feedback/stats
     */
    $app->get('/api/feedback/stats', function (Request $request, Response $response) {
        try {
            $pdo = $this->get('db');
            
            // Get satisfaction distribution
            $stmt = $pdo->prepare("
                SELECT satisfaction, COUNT(*) as count 
                FROM customer_feedback 
                GROUP BY satisfaction
            ");
            $stmt->execute();
            $satisfactionStats = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Get total feedback count
            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM customer_feedback");
            $stmt->execute();
            $totalFeedback = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
            
            // Get most recent feedback
            $stmt = $pdo->prepare("
                SELECT product, satisfaction, created_at 
                FROM customer_feedback 
                ORDER BY created_at DESC 
                LIMIT 10
            ");
            $stmt->execute();
            $recentFeedback = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $response->getBody()->write(json_encode([
                'success' => true,
                'data' => [
                    'total' => $totalFeedback,
                    'satisfaction_distribution' => $satisfactionStats,
                    'recent_feedback' => $recentFeedback
                ]
            ]));
            
            return $response->withHeader('Content-Type', 'application/json');
            
        } catch (Exception $e) {
            error_log('Feedback stats error: ' . $e->getMessage());
            $response->getBody()->write(json_encode([
                'success' => false,
                'message' => 'Internal server error'
            ]));
            return $response->withStatus(500)->withHeader('Content-Type', 'application/json');
        }
    });
    
};
