<?php
/**
 * Acciones JSON para el Módulo Escritorios
 */

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

// Iniciar sesión si no está iniciada
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Definir BASE_PATH si no está definido
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__DIR__))); // .../simple_crm
}

// Incluir configuración y conexión de base de datos
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

// Helper de autenticación si no existe
if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'No autenticado']);
    exit;
}

$db = getDB();
$pdo = $db->getConnection();

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

function json_input() {
    $contentType = $_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '';
    if (stripos($contentType, 'application/json') !== false) {
        $raw = file_get_contents('php://input');
        $data = json_decode($raw, true);
        return is_array($data) ? $data : [];
    }
    return $_POST;
}

try {
switch ($action) {
    case 'check_name': {
        // Validate if a desk name already exists (case-insensitive)
        $input = json_decode(file_get_contents('php://input'), true);
        $name = isset($_GET['name']) ? trim($_GET['name']) : trim($input['name'] ?? '');
        $ignore_id = isset($_GET['ignore_id']) ? (int)$_GET['ignore_id'] : (int)($input['ignore_id'] ?? 0);
        if ($name === '') {
            echo json_encode(['success' => false, 'error' => 'Nombre requerido']);
            exit;
        }
        // Case-insensitive comparison
        $stmt = $pdo->prepare("SELECT id FROM desks WHERE LOWER(name) = LOWER(?) LIMIT 1");
        $stmt->execute([$name]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $exists = false;
        if ($row && (int)$row['id'] !== $ignore_id) { $exists = true; }
        echo json_encode(['success' => true, 'exists' => $exists]);
        exit;
    }
        case 'get_details': {
            $desk_id = isset($_GET['desk_id']) ? (int)$_GET['desk_id'] : 0;
            if ($desk_id <= 0) {
                throw new Exception('ID de escritorio inválido');
            }
            $desk = $db->selectOne("SELECT d.*, u.username AS manager_name FROM desks d LEFT JOIN users u ON d.manager_id = u.id WHERE d.id = ?", [$desk_id]);
            if (!$desk) throw new Exception('Escritorio no encontrado');
            echo json_encode(['success' => true, 'desk' => $desk]);
            break;
        }
        case 'create': {
            $data = json_input();
            $name = trim($data['name'] ?? '');
            $description = trim($data['description'] ?? '');
            $manager_id = isset($data['manager_id']) && $data['manager_id'] !== '' ? (int)$data['manager_id'] : null;
            $status = $data['status'] ?? 'active';
            $working_hours_start = $data['working_hours_start'] ?? '09:00';
            $working_hours_end = $data['working_hours_end'] ?? '18:00';

            if ($name === '') throw new Exception('El nombre es obligatorio');
            if (strlen($name) > 100) throw new Exception('El nombre no puede exceder 100 caracteres');

            $existing = $db->selectOne("SELECT id FROM desks WHERE name = ?", [$name]);
            if ($existing) throw new Exception('Ya existe un escritorio con ese nombre');

            $desk_id = $db->execute(
                "INSERT INTO desks (name, description, manager_id, status, working_hours_start, working_hours_end, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())",
                [$name, $description, $manager_id, $status, $working_hours_start, $working_hours_end]
            );

            $created = $db->selectOne("SELECT d.*, u.username AS manager_name FROM desks d LEFT JOIN users u ON d.manager_id = u.id WHERE d.id = ?", [$desk_id]);
            echo json_encode(['success' => true, 'desk' => $created]);
            break;
        }
        case 'list_managers': {
            $users = $db->select("SELECT id, username FROM users WHERE status = 'active' ORDER BY username");
            echo json_encode(['success' => true, 'users' => $users]);
            break;
        }
        case 'list_desk_users': {
            $desk_id = isset($_GET['desk_id']) ? (int)$_GET['desk_id'] : 0;
            if ($desk_id <= 0) throw new Exception('ID de escritorio inválido');
            // Asegurar tabla desk_users
            $pdo->exec("CREATE TABLE IF NOT EXISTS desk_users (
                desk_id INT NOT NULL,
                user_id INT NOT NULL,
                assigned_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (desk_id, user_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            $rows = $db->select("SELECT u.id, u.username, u.first_name, u.last_name, u.email, u.status FROM desk_users du INNER JOIN users u ON du.user_id = u.id WHERE du.desk_id = ? ORDER BY u.first_name, u.last_name", [$desk_id]);
            echo json_encode(['success' => true, 'users' => $rows]);
            break;
        }
        case 'list_statuses': {
            // Ensure statuses table exists
            $pdo->exec("CREATE TABLE IF NOT EXISTS lead_statuses (
                id INT AUTO_INCREMENT PRIMARY KEY,
                `key` VARCHAR(50) NOT NULL UNIQUE,
                display_name VARCHAR(100) NOT NULL,
                color VARCHAR(7) DEFAULT '#64748b',
                is_active TINYINT(1) DEFAULT 1,
                is_system TINYINT(1) DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            $rows = $db->select("SELECT id, `key`, display_name, color, is_active FROM lead_statuses WHERE is_active = 1 ORDER BY display_name ASC");
            echo json_encode(['success' => true, 'statuses' => $rows]);
            break;
        }
        case 'create_status': {
            $data = json_input();
            $key = strtolower(trim($data['key'] ?? ''));
            $name = trim($data['display_name'] ?? '');
            $color = trim($data['color'] ?? '#64748b');
            if ($name === '' || $key === '') throw new Exception('Nombre y clave son obligatorios');
            if (!preg_match('/^[a-z0-9_]{3,50}$/', $key)) throw new Exception('La clave debe ser minúsculas, números y _');
            if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) $color = '#64748b';
            // Ensure table exists
            $pdo->exec("CREATE TABLE IF NOT EXISTS lead_statuses (
                id INT AUTO_INCREMENT PRIMARY KEY,
                `key` VARCHAR(50) NOT NULL UNIQUE,
                display_name VARCHAR(100) NOT NULL,
                color VARCHAR(7) DEFAULT '#64748b',
                is_active TINYINT(1) DEFAULT 1,
                is_system TINYINT(1) DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            $exists = $db->selectOne("SELECT id FROM lead_statuses WHERE `key` = ?", [$key]);
            if ($exists) throw new Exception('Ya existe un estado con esa clave');
            $db->execute("INSERT INTO lead_statuses (`key`, display_name, color, is_active, is_system, created_at) VALUES (?, ?, ?, 1, 0, NOW())", [$key, $name, $color]);
            $created = $db->selectOne("SELECT id, `key`, display_name, color FROM lead_statuses WHERE `key` = ?", [$key]);
            echo json_encode(['success' => true, 'status' => $created]);
            break;
        }
        case 'update_status': {
            $data = json_input();
            $key = strtolower(trim($data['key'] ?? ''));
            $displayName = trim($data['display_name'] ?? '');
            if ($key === '') throw new Exception('Clave del estado requerida');
            $exists = $db->selectOne("SELECT id FROM lead_statuses WHERE `key` = ?", [$key]);
            if (!$exists) throw new Exception('Estado no encontrado');
            if ($displayName === '') throw new Exception('Nombre del estado requerido');
            if (mb_strlen($displayName) > 100) throw new Exception('Nombre demasiado largo');
            $db->execute("UPDATE lead_statuses SET display_name = ?, updated_at = NOW() WHERE `key` = ?", [$displayName, $key]);
            $updated = $db->selectOne("SELECT id, `key`, display_name, color FROM lead_statuses WHERE `key` = ?", [$key]);
            echo json_encode(['success' => true, 'status' => $updated]);
            break;
        }
        case 'delete_status': {
            $data = json_input();
            $key = strtolower(trim($data['key'] ?? ''));
            if ($key === '') throw new Exception('Clave del estado requerida');
            if (!preg_match('/^[a-z0-9_\-]{2,50}$/', $key)) throw new Exception('Clave inválida');
            // Asegurar tablas
            $pdo->exec("CREATE TABLE IF NOT EXISTS lead_statuses (
                id INT AUTO_INCREMENT PRIMARY KEY,
                `key` VARCHAR(50) NOT NULL UNIQUE,
                display_name VARCHAR(100) NOT NULL,
                color VARCHAR(7) DEFAULT '#64748b',
                is_active TINYINT(1) DEFAULT 1,
                is_system TINYINT(1) DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            $pdo->exec("CREATE TABLE IF NOT EXISTS desk_allowed_statuses (
                id INT AUTO_INCREMENT PRIMARY KEY,
                desk_id INT NOT NULL,
                status VARCHAR(50) NOT NULL,
                position INT DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY unique_desk_status (desk_id, status)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            $exists = $db->selectOne("SELECT id FROM lead_statuses WHERE `key` = ?", [$key]);
            if (!$exists) throw new Exception('Estado no encontrado');
            $pdo->beginTransaction();
            try {
                // Quitar de todos los desks
                $db->execute("DELETE FROM desk_allowed_statuses WHERE status = ?", [$key]);
                // Eliminar del catálogo global
                $db->execute("DELETE FROM lead_statuses WHERE `key` = ?", [$key]);
                $pdo->commit();
            } catch (Exception $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                throw $e;
            }
            echo json_encode(['success' => true, 'deleted' => $key]);
            break;
        }
        case 'update': {
            $data = json_input();
            $desk_id = isset($data['desk_id']) ? (int)$data['desk_id'] : 0;
            if ($desk_id <= 0) throw new Exception('ID de escritorio inválido');

            $name = trim($data['name'] ?? '');
            $description = trim($data['description'] ?? '');
            $manager_id = isset($data['manager_id']) && $data['manager_id'] !== '' ? (int)$data['manager_id'] : null;
            $status = $data['status'] ?? 'active';
            $working_hours_start = $data['working_hours_start'] ?? '09:00';
            $working_hours_end = $data['working_hours_end'] ?? '18:00';

            if ($name === '') throw new Exception('El nombre es obligatorio');
            if (strlen($name) > 100) throw new Exception('El nombre no puede exceder 100 caracteres');

            $existing = $db->selectOne("SELECT id FROM desks WHERE name = ? AND id <> ?", [$name, $desk_id]);
            if ($existing) throw new Exception('Ya existe otro escritorio con ese nombre');

            $db->execute(
                "UPDATE desks SET name = ?, description = ?, manager_id = ?, status = ?, working_hours_start = ?, working_hours_end = ?, updated_at = NOW() WHERE id = ?",
                [$name, $description, $manager_id, $status, $working_hours_start, $working_hours_end, $desk_id]
            );

            $updated = $db->selectOne("SELECT d.*, u.username AS manager_name FROM desks d LEFT JOIN users u ON d.manager_id = u.id WHERE d.id = ?", [$desk_id]);
            echo json_encode(['success' => true, 'desk' => $updated]);
            break;
        }
        case 'remove_allowed_status': {
            $data = json_input();
            $desk_id = isset($data['desk_id']) ? (int)$data['desk_id'] : 0;
            $key = strtolower(trim($data['key'] ?? ''));
            if ($desk_id <= 0 || $key === '') throw new Exception('Parámetros inválidos');
            if (!preg_match('/^[a-z0-9_\-]{2,50}$/', $key)) throw new Exception('Clave de estado inválida');
            // Asegurar existencia y formato de la tabla
            $pdo->exec("CREATE TABLE IF NOT EXISTS desk_allowed_statuses (
                id INT AUTO_INCREMENT PRIMARY KEY,
                desk_id INT NOT NULL,
                status VARCHAR(50) NOT NULL,
                position INT DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                UNIQUE KEY unique_desk_status (desk_id, status)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
            try {
                $stmtCol = $pdo->prepare("SELECT DATA_TYPE, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'desk_allowed_statuses' AND COLUMN_NAME = 'status' LIMIT 1");
                $stmtCol->execute([DB_NAME]);
                $col = $stmtCol->fetch(PDO::FETCH_ASSOC);
                if ($col && stripos($col['COLUMN_TYPE'] ?? '', 'enum(') === 0) {
                    $pdo->exec("ALTER TABLE desk_allowed_statuses MODIFY status VARCHAR(50) NOT NULL");
                }
            } catch (Exception $e) { /* continuar */ }
            // Eliminar el estado permitido para el desk
            $db->execute("DELETE FROM desk_allowed_statuses WHERE desk_id = ? AND status = ?", [$desk_id, $key]);
            echo json_encode(['success' => true, 'desk_id' => $desk_id, 'removed' => $key]);
            break;
        }
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Acción no soportada']);
    }
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

?>