<?php
// File: phonetics.php
// API endpoints for phonetics system

require_once 'config.php';
require_once 'enhanced_security.php';

// CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, X-API-Key, User-Agent");
header("Content-Type: application/json; charset=UTF-8");

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// API key validation (API_KEY is defined in enhanced_security.php)
if (!isset($_SERVER['HTTP_X_API_KEY']) || $_SERVER['HTTP_X_API_KEY'] !== API_KEY) {
    http_response_code(403);
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access. Invalid API key.',
        'status_code' => 403
    ]);
    exit();
}

// Rate limiting
if (!RateLimiter::checkLimit($_SERVER['REMOTE_ADDR'], RATE_LIMIT_REQUESTS, RATE_LIMIT_WINDOW)) {
    http_response_code(429);
    echo json_encode([
        'success' => false,
        'message' => 'Rate limit exceeded. Please try again later.',
        'status_code' => 429
    ]);
    exit();
}

// Get database connection
try {
    $conn = getDBConnection();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database connection failed',
        'status_code' => 500
    ]);
    exit();
}

// Determine the action
$action = $_GET['action'] ?? 'list';

try {
    switch ($action) {
        case 'list':
            // Get all phonetics data
            $stmt = $conn->prepare("
                SELECT 
                    id, english_letter, ipa_symbol, sinhala_letter, 
                    category, level,
                    sound_file, mouth_video, animation_video, 
                    examples, audio_lesson, text_lesson, short_description
                FROM phonetics 
                WHERE is_active = 1 
                ORDER BY level ASC, category ASC, english_letter ASC
            ");
            $stmt->execute();
            $phonetics = $stmt->fetchAll();

            // Parse JSON examples for each phonetic
            foreach ($phonetics as &$phonetic) {
                if ($phonetic['examples']) {
                    $phonetic['examples'] = json_decode($phonetic['examples'], true);
                }
            }

            echo json_encode([
                'success' => true,
                'data' => [
                    'phonetics' => $phonetics,
                    'count' => count($phonetics)
                ],
                'message' => 'Phonetics data retrieved successfully'
            ]);
            break;

        case 'get':
            // Get specific phonetic by ID
            $phonetic_id = $_GET['id'] ?? null;
            
            if (!$phonetic_id || !is_numeric($phonetic_id)) {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'message' => 'Invalid phonetic ID',
                    'status_code' => 400
                ]);
                exit();
            }

            $stmt = $conn->prepare("
                SELECT 
                    id, english_letter, ipa_symbol, sinhala_letter, 
                    category, level,
                    sound_file, mouth_video, animation_video, 
                    examples, audio_lesson, text_lesson, short_description
                FROM phonetics 
                WHERE id = ? AND is_active = 1
            ");
            $stmt->execute([$phonetic_id]);
            $phonetic = $stmt->fetch();

            if (!$phonetic) {
                http_response_code(404);
                echo json_encode([
                    'success' => false,
                    'message' => 'Phonetic not found',
                    'status_code' => 404
                ]);
                exit();
            }

            // Parse JSON examples
            if ($phonetic['examples']) {
                $phonetic['examples'] = json_decode($phonetic['examples'], true);
            }

            echo json_encode([
                'success' => true,
                'data' => $phonetic,
                'message' => 'Phonetic data retrieved successfully'
            ]);
            break;

        case 'search':
            // Search phonetics by letter or IPA
            $query = $_GET['q'] ?? '';
            
            if (empty($query)) {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'message' => 'Search query is required',
                    'status_code' => 400
                ]);
                exit();
            }

            $stmt = $conn->prepare("
                SELECT 
                    id, english_letter, ipa_symbol, sinhala_letter, 
                    category, level,
                    sound_file, mouth_video, animation_video, 
                    examples, audio_lesson, text_lesson, short_description
                FROM phonetics 
                WHERE is_active = 1 
                AND (
                    english_letter LIKE ? OR 
                    ipa_symbol LIKE ? OR 
                    sinhala_letter LIKE ? OR
                    category LIKE ? OR
                    level LIKE ?
                )
                ORDER BY level ASC, category ASC, english_letter ASC
            ");
            $search_term = "%{$query}%";
            $stmt->execute([$search_term, $search_term, $search_term, $search_term, $search_term]);
            $phonetics = $stmt->fetchAll();

            // Parse JSON examples for each phonetic
            foreach ($phonetics as &$phonetic) {
                if ($phonetic['examples']) {
                    $phonetic['examples'] = json_decode($phonetic['examples'], true);
                }
            }

            echo json_encode([
                'success' => true,
                'data' => [
                    'phonetics' => $phonetics,
                    'count' => count($phonetics),
                    'query' => $query
                ],
                'message' => 'Search completed successfully'
            ]);
            break;

        case 'filter':
            // Filter phonetics by category and/or level
            $category = $_GET['category'] ?? null;
            $level = $_GET['level'] ?? null;
            
            $where_conditions = ["is_active = 1"];
            $params = [];
            
            if ($category) {
                $where_conditions[] = "category = ?";
                $params[] = $category;
            }
            
            if ($level) {
                $where_conditions[] = "level = ?";
                $params[] = $level;
            }
            
            $where_clause = implode(" AND ", $where_conditions);
            
            $stmt = $conn->prepare("
                SELECT 
                    id, english_letter, ipa_symbol, sinhala_letter, 
                    category, level,
                    sound_file, mouth_video, animation_video, 
                    examples, audio_lesson, text_lesson, short_description
                FROM phonetics 
                WHERE {$where_clause}
                ORDER BY level ASC, category ASC, english_letter ASC
            ");
            $stmt->execute($params);
            $phonetics = $stmt->fetchAll();

            // Parse JSON examples for each phonetic
            foreach ($phonetics as &$phonetic) {
                if ($phonetic['examples']) {
                    $phonetic['examples'] = json_decode($phonetic['examples'], true);
                }
            }

            echo json_encode([
                'success' => true,
                'data' => [
                    'phonetics' => $phonetics,
                    'count' => count($phonetics),
                    'filters' => [
                        'category' => $category,
                        'level' => $level
                    ]
                ],
                'message' => 'Filtered phonetics data retrieved successfully'
            ]);
            break;

        default:
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action. Supported actions: list, get, search, filter',
                'status_code' => 400
            ]);
            break;
    }

} catch (Exception $e) {
    error_log("Phonetics API Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal server error',
        'status_code' => 500
    ]);
}

// Close database connection
$conn = null;
?>