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

// Seguridad: Solo el admin configurado puede realizar cambios
$masterAdmin = $db_settings['admin_user'] ?? 'Admin';
if (!isset($_SESSION['logged_in']) || $_SESSION['user_id'] !== $masterAdmin) {
    echo json_encode(['status' => 'error', 'message' => 'No autorizado']);
    exit;
}

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);

    // 1. Procesar la Imagen Principal
    $imagePath = "";
    if (isset($_FILES['sch_img']) && $_FILES['sch_img']['error'] === 0) {
        $dir = "../assets/eventos/";
        if (!is_dir($dir)) mkdir($dir, 0777, true);
        
        $ext = pathinfo($_FILES['sch_img']['name'], PATHINFO_EXTENSION);
        $cleanName = preg_replace("/[^a-zA-Z0-9]/", "", $_POST['name']);
        $fileName = time() . "_" . $cleanName . "." . $ext;
        
        if (move_uploaded_file($_FILES['sch_img']['tmp_name'], $dir . $fileName)) {
            $imagePath = "assets/eventos/" . $fileName;
        }
    }

    // 2. Procesar Múltiples Drops con sus Rarezas (Sincronizado con JS)
    $dropData = [];
    // Cambiamos 'glow_types' por 'rarities' para que coincida con el FormData del JS
    $rarities = isset($_POST['rarities']) ? $_POST['rarities'] : [];

    if (isset($_FILES['drops_images']) && is_array($_FILES['drops_images']['tmp_name'])) {
        $dropsDir = "../assets/drops/";
        if (!is_dir($dropsDir)) mkdir($dropsDir, 0777, true);

        foreach ($_FILES['drops_images']['tmp_name'] as $key => $tmpName) {
            if ($_FILES['drops_images']['error'][$key] === 0) {
                $dropExt = pathinfo($_FILES['drops_images']['name'][$key], PATHINFO_EXTENSION);
                $uniqueDropName = time() . "_item_" . $key . "." . $dropExt;
                
                if (move_uploaded_file($tmpName, $dropsDir . $uniqueDropName)) {
                    // USAMOS 'rarities' que es lo que envía el JavaScript
                    // Si no existe la posición, usamos 'common' por defecto
                    $currentRarity = isset($rarities[$key]) ? $rarities[$key] : 'common';
                    
                    // Guardamos en formato imagen|rareza
                    $dropData[] = $uniqueDropName . '|' . $currentRarity;
                }
            }
        }
    }
    
    $dropsString = !empty($dropData) ? implode(',', $dropData) : null;

    // 3. Insertar en la Base de Datos
    $sql = "INSERT INTO Web_Schedules (type, name, times, gmt, image_url, description, drops, status) 
            VALUES (?, ?, ?, ?, ?, ?, ?, 1)";
    
    $stmt = $pdo->prepare($sql);
    $success = $stmt->execute([
        $_POST['type'],
        $_POST['name'],
        $_POST['times'],
        $_POST['gmt'],
        $imagePath,
        $_POST['description'] ?? '',
        $dropsString
    ]);

    if ($success) {
        echo json_encode(['status' => 'success', 'message' => 'Configuración guardada correctamente']);
    } else {
        throw new Exception("No se pudo insertar el registro.");
    }

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