<?php
/**
 * Módulo Escritorios - Editar
 */

if (!isLoggedIn()) {
    header('Location: /index.php?module=auth&action=login');
    exit;
}

$db = getDB();
$message = '';
$error = '';

$desk_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($desk_id <= 0) {
    $error = 'ID de escritorio inválido.';
} else {
    // Obtener escritorio
    $desk = $db->selectOne("SELECT * FROM desks WHERE id = ?", [$desk_id]);
    if (!$desk) {
        $error = 'Escritorio no encontrado.';
    }
}

// Obtener usuarios para manager
$users = $db->select("SELECT id, username, first_name, last_name FROM users WHERE status = 'active' ORDER BY username");

if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($error)) {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $manager_id = $_POST['manager_id'] ?? null;
    $status = $_POST['status'] ?? 'active';
    $working_hours_start = $_POST['working_hours_start'] ?? '09:00';
    $working_hours_end = $_POST['working_hours_end'] ?? '18:00';

    // Validaciones
    if (empty($name)) {
        $error = 'El nombre del escritorio es obligatorio.';
    } elseif (strlen($name) > 100) {
        $error = 'El nombre no puede exceder 100 caracteres.';
    } else {
        // Verificar si el nombre ya existe en otro escritorio
        $existing = $db->selectOne("SELECT id FROM desks WHERE name = ? AND id <> ?", [$name, $desk_id]);
        if ($existing) {
            $error = 'Ya existe otro escritorio con ese nombre.';
        }
    }

    if (empty($error)) {
        try {
            $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 ?: null, $status, $working_hours_start, $working_hours_end, $desk_id]
            );
            $message = 'Escritorio actualizado correctamente.';
            // Refrescar datos
            $desk = $db->selectOne("SELECT * FROM desks WHERE id = ?", [$desk_id]);
        } catch (Exception $e) {
            $error = 'Error al actualizar el escritorio: ' . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Editar Escritorio - <?php echo APP_NAME; ?></title>
    <link rel="stylesheet" href="/test/simple_crm/public/style.css">
</head>
<body>
    <?php include BASE_PATH . '/modules/shared/header.php'; ?>

    <div class="container">
        <div class="card">
            <div class="card-header d-flex justify-between align-center">
                <h1 class="card-title">Editar Escritorio</h1>
                <a href="?module=desks" class="btn btn-secondary">Volver al listado</a>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            <?php if ($message): ?>
                <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>

            <?php if (!empty($desk)): ?>
            <form method="post" class="form-grid">
                <div class="form-row">
                    <div class="form-group">
                        <label for="name">Nombre del Escritorio</label>
                        <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($desk['name'] ?? ''); ?>" maxlength="100" required>
                    </div>
                    <div class="form-group">
                        <label for="manager_id">Manager</label>
                        <select id="manager_id" name="manager_id">
                            <option value="">Sin asignar</option>
                            <?php foreach ($users as $u): ?>
                                <?php $selected = ($desk['manager_id'] ?? null) == $u['id'] ? 'selected' : ''; ?>
                                <option value="<?php echo (int)$u['id']; ?>" <?php echo $selected; ?>>
                                    <?php echo htmlspecialchars($u['username']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group" style="grid-column: 1 / -1;">
                        <label for="description">Descripción</label>
                        <textarea id="description" name="description" rows="3" placeholder="Descripción del escritorio..."><?php echo htmlspecialchars($desk['description'] ?? ''); ?></textarea>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="status">Estado</label>
                        <select id="status" name="status">
                            <option value="active" <?php echo ($desk['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Activo</option>
                            <option value="inactive" <?php echo ($desk['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactivo</option>
                            <option value="suspended" <?php echo ($desk['status'] ?? '') === 'suspended' ? 'selected' : ''; ?>>Suspendido</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="working_hours_start">Horario Inicio</label>
                        <input type="time" id="working_hours_start" name="working_hours_start" value="<?php echo htmlspecialchars($desk['working_hours_start'] ?? '09:00'); ?>">
                    </div>
                    <div class="form-group">
                        <label for="working_hours_end">Horario Fin</label>
                        <input type="time" id="working_hours_end" name="working_hours_end" value="<?php echo htmlspecialchars($desk['working_hours_end'] ?? '18:00'); ?>">
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-success">Guardar Cambios</button>
                    <a href="?module=desks" class="btn btn-secondary">Cancelar</a>
                </div>
            </form>
            <?php endif; ?>
        </div>

        <!-- Estados permitidos del escritorio -->
        <?php if (!empty($desk)): ?>
        <div class="card">
            <div class="card-header d-flex justify-between align-center">
                <h3>Estados Permitidos del Escritorio</h3>
                <div>
                    <button id="reloadStatusesBtn" class="btn btn-small">Recargar</button>
                    <button id="saveStatusesBtn" class="btn btn-small btn-success">Guardar Estados</button>
                </div>
            </div>
            <div id="deskStatusesList" class="permissions-grid" style="padding: 1rem;"></div>
            <div class="card-footer">
                <small>Define qué estados de lead puede usar este escritorio.</small>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script>
    (function(){
        const deskId = <?php echo (int)$desk_id; ?>;
        const list = document.getElementById('deskStatusesList');
        const reloadBtn = document.getElementById('reloadStatusesBtn');
        const saveBtn = document.getElementById('saveStatusesBtn');

        function loadStatuses(){
            if (!list) return;
            list.innerHTML = '<span class="text-muted">Cargando estados...</span>';
            fetch(`/modules/desks/get_allowed_statuses.php?desk_id=${encodeURIComponent(deskId)}`)
                .then(r => r.json())
                .then(j => {
                    if (!j.success) { list.innerHTML = `<span style='color:#ef4444'>${j.message||'No se pudo cargar'}</span>`; return; }
                    const all = j.all || ['new','contacted','qualified','demo_scheduled','demo_completed','deposit_pending','deposited','active_trader','inactive','closed_lost'];
                    const allowed = new Set(j.allowed || []);
                    list.innerHTML = '';
                    all.forEach(s => {
                        const row = document.createElement('label');
                        row.className = 'permission-check';
                        row.style.margin = '4px 0';
                        row.innerHTML = `
                            <input type="checkbox" class="desk-status-chk" value="${s}" ${allowed.has(s)?'checked':''}>
                            <span class="permission-label" data-text="${s.replace('_',' ')}">${s.replace('_',' ')}</span>
                        `;
                        list.appendChild(row);
                    });
                })
                .catch(e => { list.innerHTML = `<span style='color:#ef4444'>Error de red: ${e.message}</span>`; });
        }

        function saveStatuses(){
            const selected = Array.from(document.querySelectorAll('.desk-status-chk:checked')).map(cb => cb.value);
            saveBtn.disabled = true; saveBtn.textContent = 'Guardando...';
            fetch('/modules/desks/save_allowed_statuses.php', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ desk_id: deskId, statuses: selected })
            }).then(r => r.json()).then(j => {
                if (j.success) {
                    if (window.ProfixCRM && typeof window.ProfixCRM.showNotification === 'function') {
        window.ProfixCRM.showModalNotification({ type:'success', title:'Estados guardados', message:'Los cambios de estados han sido guardados' });
                    } else { alert('Estados guardados'); }
                } else {
                    const msg = j.message || 'No se pudo guardar';
                    if (window.ProfixCRM && typeof window.ProfixCRM.showNotification === 'function') {
        window.ProfixCRM.showModalNotification({ type:'error', title:'Error', message: msg });
                    } else { alert('Error: ' + msg); }
                }
            }).catch(e => {
                const msg = 'Error de red: ' + e.message;
                if (window.ProfixCRM && typeof window.ProfixCRM.showNotification === 'function') {
        window.ProfixCRM.showModalNotification({ type:'error', title:'Error', message: msg });
                } else { alert(msg); }
            }).finally(() => { saveBtn.disabled = false; saveBtn.textContent = 'Guardar Estados'; });
        }

        if (reloadBtn) reloadBtn.addEventListener('click', loadStatuses);
        if (saveBtn) saveBtn.addEventListener('click', saveStatuses);
        loadStatuses();
    })();
    </script>

    <style>
        .form-grid { display: grid; gap: 1rem; padding: 1rem; }
        .form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 1rem; }
        .form-group label { display:block; margin-bottom: .35rem; color: #374151; }
        .form-group input[type="text"], .form-group input[type="time"], .form-group select, .form-group textarea {
            width: 100%; padding: .5rem .6rem; border: 1px solid #d1d5db; border-radius: .5rem; font-size: .95rem;
        }
        .form-actions { display:flex; gap:.6rem; padding: 0 1rem 1rem; }
        .permissions-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: .5rem; }
        .permission-check { display:flex; gap:.6rem; align-items:center; }
        .permission-label { text-transform: capitalize; color:#374151; }
    </style>

    <script src="/public/script.js"></script>
</body>
</html>