<?php
require_once(__DIR__ . '/../config/settings.php');

header('Content-Type: application/json');

try {
    $dsn = "dblib:host={$db_settings['host']};dbname={$db_settings['name']};charset=UTF8";
    $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $type = $_GET['type'] ?? 'event';

    $stmt = $pdo->prepare("SELECT id, type, name, times, gmt, image_url, description, drops, status FROM Web_Schedules WHERE type = ? AND status = 1 ORDER BY id DESC");
    $stmt->execute([$type]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // PROCESAMIENTO CLAVE:
    $formattedResults = array_map(function($item) {
        $item['drops'] = $item['drops'] ?? '';
        
        // Creamos un nuevo campo 'drop_rarity' para que el JavaScript 
        // de la función fetchSchedules() lo encuentre fácilmente.
        if (!empty($item['drops'])) {
            // Si el drop es "imagen.jpg|excellent,item2.png|boss"
            // extraemos solo las rarezas: "excellent,boss"
            $parts = explode(',', $item['drops']);
            $rarities = array_map(function($p) {
                $sub = explode('|', $p);
                return $sub[1] ?? 'common';
            }, $parts);
            
            $item['drop_rarity'] = implode(',', $rarities);
        } else {
            $item['drop_rarity'] = 'common';
        }

        return $item;
    }, $results);

    echo json_encode($formattedResults);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Error en el servidor: ' . $e->getMessage()
    ]);
}