<?php
require_once 'config/db.php';

try {
    echo "🏗️ Instalando Tablas de Chat y Wallet...\n";

    // 0. Limpiar tablas anteriores (solo desarrollo/test)
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 0;");
    $pdo->exec("DROP TABLE IF EXISTS transactions, messages, chat_members, chats;");
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 1;");
    echo "🗑️ Tablas antiguas eliminadas.\n";

    // 1. Tabla de Chats (Conversaciones)
    $sql_chats = "CREATE TABLE IF NOT EXISTS chats (
        id INT AUTO_INCREMENT PRIMARY KEY,
        type ENUM('private', 'group') DEFAULT 'private',
        name VARCHAR(100),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )";
    $pdo->exec($sql_chats);
    echo "✅ Tabla 'chats' creada.\n";

    $sql_members = "CREATE TABLE IF NOT EXISTS chat_members (
        chat_id INT,
        user_id INT, -- Referencia a i_users.iuid
        role ENUM('member', 'admin') DEFAULT 'member',
        joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (chat_id, user_id),
        FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE,
        FOREIGN KEY (user_id) REFERENCES i_users(iuid) ON DELETE CASCADE
    )";
    $pdo->exec($sql_members);
    echo "✅ Tabla 'chat_members' creada.\n";

    $sql_messages = "CREATE TABLE IF NOT EXISTS messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        chat_id INT,
        sender_id INT, -- Referencia a i_users.iuid
        type ENUM('text', 'image', 'voice', 'gift', 'payment', 'video', 'file') DEFAULT 'text',
        content TEXT, 
        meta_data JSON, 
        is_ephemeral BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE,
        FOREIGN KEY (sender_id) REFERENCES i_users(iuid) ON DELETE CASCADE
    )";
    $pdo->exec($sql_messages);
    echo "✅ Tabla 'messages' creada.\n";

    $sql_transactions = "CREATE TABLE IF NOT EXISTS transactions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT, -- Referencia a i_users.iuid
        type ENUM('purchase', 'gift_sent', 'gift_received', 'content_sold', 'content_bought') NOT NULL,
        amount INT NOT NULL,
        reference_id INT, -- ID del mensaje o regalo relacionado
        description VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES i_users(iuid) ON DELETE CASCADE
    )";
    $pdo->exec($sql_transactions);
    echo "✅ Tabla 'transactions' creada.\n";

    echo "\n🚀 SISTEMA DE CHAT INSTALADO CORRECTAMENTE.";

} catch(PDOException $e) {
    die("❌ Error en instalación: " . $e->getMessage());
}
?>
