<?php
// ════════════════════════════════════════════════════════
// DESCRIPTIONS API
// Place in: Triangle_Tree_Life_Number/api/data/descriptions.php
// ════════════════════════════════════════════════════════

error_reporting(E_ALL);
ini_set('display_errors', 0);

// Remove any existing headers first
if (function_exists('header_remove')) {
    header_remove('Access-Control-Allow-Methods');
}

// Force CORS headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

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

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/helpers.php';

// Verify JWT token
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? '';

if (empty($authHeader) || !preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$token = $matches[1];
$jwtSecret = getenv('JWT_SECRET') ?: 'default_secret_change_this';
$payload = verifyJWT($token, $jwtSecret);

if (!$payload) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid token']);
    exit();
}

// Accept both GET and POST
$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method === 'GET') {
        // ══════════════════════════════════════
        // GET - Load all descriptions
        // ══════════════════════════════════════
        
        // Load single nodes (numbers 1-9 descriptions)
        $stmt = $pdo->query("
            SELECT 
                id, 
                node, 
                val,
                desc_en,
                desc_ms,
                desc_zh,
                sens_en,
                sens_ms,
                sens_zh
            FROM single_nodes
            ORDER BY val ASC
        ");
        $singleNodesRaw = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Transform to format expected by frontend
        $singleNodes = array_map(function($row) {
            return [
                'id' => (int)$row['id'],
                'node' => $row['node'],
                'val' => (int)$row['val'],
                'desc' => [
                    'en' => $row['desc_en'] ?? '',
                    'ms' => $row['desc_ms'] ?? '',
                    'zh' => $row['desc_zh'] ?? ''
                ],
                'sensDesc' => [
                    'en' => $row['sens_en'] ?? '',
                    'ms' => $row['sens_ms'] ?? '',
                    'zh' => $row['sens_zh'] ?? ''
                ]
            ];
        }, $singleNodesRaw);
        
        // Load combo rules (will add when you have data in combo_rules table)
        $comboRules = [];
        
        // Load frequency rules (will add when you have data)
        $freqRules = [];
        
        // Load node combination rules (will add when you have data)
        $nodeCombRules = [];
        
        // Load tiangan descriptions (will add when you have data)
        $tianganDesc = [];
        
        echo json_encode([
            'singleNodes' => $singleNodes,
            'comboRules' => $comboRules,
            'freqRules' => $freqRules,
            'nodeCombRules' => $nodeCombRules,
            'tianganDesc' => $tianganDesc
        ]);
        
    } elseif ($method === 'POST') {
        // ══════════════════════════════════════
        // POST - Save descriptions (for future implementation)
        // ══════════════════════════════════════
        
        $input = json_decode(file_get_contents('php://input'), true);
        
        // For now, just return success
        // You can implement saving logic later when needed
        echo json_encode([
            'success' => true,
            'message' => 'Save functionality will be implemented when needed'
        ]);
    } else {
        // Method not supported
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed - use GET or POST']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Server error', 
        'message' => $e->getMessage()
    ]);
}
?>
