<?php
session_start();
require_once '../../database/connection.php';

// Simular usuario logueado para pruebas
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = 1;
    $_SESSION['username'] = 'admin';
    $_SESSION['role'] = 'admin';
}

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método no permitido']);
    exit;
}

$action = $_POST['action'] ?? '';

try {
    $pdo = getDB()->getConnection();
    
    switch ($action) {
        case 'create_table':
            // Crear tabla desk_allowed_statuses
            $sql = "CREATE TABLE IF NOT EXISTS desk_allowed_statuses (
                id INT AUTO_INCREMENT PRIMARY KEY,
                desk_id INT NOT NULL,
                status VARCHAR(50) NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY unique_desk_status (desk_id, status),
                FOREIGN KEY (desk_id) REFERENCES desks(id) ON DELETE CASCADE
            )";
            
            $pdo->exec($sql);
            echo json_encode(['success' => true, 'message' => 'Tabla desk_allowed_statuses creada correctamente']);
            break;
            
        case 'add_default_permissions':
            // Agregar permisos por defecto para todos los desks
            $default_statuses = ['new', 'contacted', 'qualified', 'proposal', 'negotiation', 'closed_won', 'closed_lost'];
            
            // Obtener todos los desks
            $stmt = $pdo->query("SELECT id FROM desks");
            $desks = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            if (empty($desks)) {
                echo json_encode(['success' => false, 'message' => 'No hay desks configurados']);
                break;
            }
            
            $added = 0;
            foreach ($desks as $desk_id) {
                foreach ($default_statuses as $status) {
                    try {
                        $stmt = $pdo->prepare("INSERT IGNORE INTO desk_allowed_statuses (desk_id, status) VALUES (?, ?)");
                        $stmt->execute([$desk_id, $status]);
                        if ($stmt->rowCount() > 0) $added++;
                    } catch (Exception $e) {
                        // Ignorar duplicados
                    }
                }
            }
            
            echo json_encode(['success' => true, 'message' => "Se agregaron $added permisos por defecto"]);
            break;
            
        case 'fix_desk_permissions':
            $desk_id = intval($_POST['desk_id'] ?? 0);
            if ($desk_id <= 0) {
                echo json_encode(['success' => false, 'message' => 'Desk ID inválido']);
                break;
            }
            
            // Verificar que el desk existe
            $stmt = $pdo->prepare("SELECT id FROM desks WHERE id = ?");
            $stmt->execute([$desk_id]);
            if (!$stmt->fetch()) {
                echo json_encode(['success' => false, 'message' => 'Desk no encontrado']);
                break;
            }
            
            // Agregar permisos por defecto para este desk específico
            $default_statuses = ['new', 'contacted', 'qualified', 'proposal', 'negotiation', 'closed_won', 'closed_lost'];
            
            $added = 0;
            foreach ($default_statuses as $status) {
                try {
                    $stmt = $pdo->prepare("INSERT IGNORE INTO desk_allowed_statuses (desk_id, status) VALUES (?, ?)");
                    $stmt->execute([$desk_id, $status]);
                    if ($stmt->rowCount() > 0) $added++;
                } catch (Exception $e) {
                    // Ignorar duplicados
                }
            }
            
            echo json_encode(['success' => true, 'message' => "Se agregaron $added permisos para el Desk $desk_id"]);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Acción no válida']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>