<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/format.php';
require_once '../../services/crm/CrmService.php';
require_once '../../core/permissions.php';

require_login();
// /modules/crm/opportunity_edit.php (Línea 8 aprox)
require_login();
require_permission('module.crm'); // ¡Agrega esta línea!

// 1. Obtener y limpiar errores y datos antiguos de la sesión primero
$formErrors = $_SESSION['form_errors'] ?? array();
$formOld = $_SESSION['form_old'] ?? array();

unset($_SESSION['form_errors']);
unset($_SESSION['form_old']);

// 2. Funciones helper de validación
function field_error($field, $formErrors)
{
    return isset($formErrors[$field]) ? $formErrors[$field] : '';
}

function field_class($field, $formErrors, $required = false)
{
    $classes = array('form-field');

    if ($required) {
        $classes[] = 'is-required';
    }

    if (isset($formErrors[$field])) {
        $classes[] = 'has-error';
    }

    return implode(' ', $classes);
}

// 3. Carga de datos iniciales
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

$crm = new CrmService();
$opportunity = $crm->getOpportunity($id);

if (!$opportunity) {
    die('Oportunidad no encontrada.');
}

$customers = $crm->getCustomers();
$assignableUsers = $crm->getAssignableUsers();
$ownerValue = $opportunity['owner_name'] ?? '';

// 4. Inicialización de valores con fallbacks (Prioriza valores antiguos ante fallos de validación)
$nextActionDateValue = $formOld['next_action_date'] ?? $opportunity['next_action_date'] ?? '';
$expectedCloseDateValue = $formOld['expected_close_date'] ?? $opportunity['expected_close_date'] ?? '';
$stageValue = $formOld['stage'] ?? $opportunity['stage'] ?? 'nuevo';
$sourceValue = $formOld['source'] ?? $opportunity['source'] ?? '';
$nextActionValue = $formOld['next_action'] ?? $opportunity['next_action'] ?? '';
$paymentStatusValue = $opportunity['payment_status'] ?? 'no_facturado';
$competitorValue = $opportunity['competitor'] ?? '';

// 5. Mapeos de opciones para selects
$sourceOptions = array(
    'Instagram' => 'Instagram',
    'Web' => 'Web',
    'OpenLab' => 'OpenLab',
    'Recomendación' => 'Recomendación',
    'Email' => 'Email',
    'Llamada' => 'Llamada',
    'Distribuidor' => 'Distribuidor',
    'Reposicion predictiva' => 'Reposición predictiva',
    'Otro' => 'Otro'
);

$stageOptions = array(
    'nuevo' => 'Nuevo',
    'contactado' => 'Contactado',
    'cotizando' => 'Cotizando',
    'negociacion' => 'Negociación',
    'ganada' => 'Ganada',
    'perdida' => 'Perdida',
    'facturada' => 'Facturada'
);

$paymentStatusOptions = array(
    'no_facturado' => 'No facturado',
    'por_cobrar' => 'Por cobrar',
    'pagado' => 'Pagado',
    'atrasado' => 'Atrasado',
    'incobrable' => 'Incobrable'
);

$competitorOptions = array(
    '' => 'No identificado',
    'Abstrax' => 'Abstrax',
    'HopBurst' => 'HopBurst',
    'Pellets' => 'Pellets',
    'Proveedor tradicional' => 'Proveedor tradicional',
    'Otro' => 'Otro'
);

$nextActionOptions = array(
    '' => 'Sin acción',
    'Llamar' => 'Llamar',
    'Enviar cotización' => 'Enviar cotización',
    'Enviar muestra' => 'Enviar muestra',
    'Agendar reunión' => 'Agendar reunión',
    'Hacer seguimiento' => 'Hacer seguimiento',
    'Esperar respuesta' => 'Esperar respuesta'
);

$page_title = 'Editar oportunidad';

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';

?>

<main class="app-main">
    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content">

        <div class="page-header page-header-compact">
            <div class="page-header-content">
                <span class="label">CRM · Oportunidades</span>
                <h1>Editar oportunidad</h1>
                <p class="text-secondary"><?php echo safe_text($opportunity['customer_name']); ?></p>
            </div>
        </div>
        
        <?php if (!empty($formErrors)): ?>
            <div class="alert alert-error">
                <strong>No fue posible guardar la oportunidad.</strong>
                <span>Revisa los campos marcados en rojo.</span>
            </div>
        <?php endif; ?>

        <form class="opportunity-form" action="/modules/crm/opportunity_update.php" method="POST">

            <input type="hidden" name="id" value="<?php echo (int) $opportunity['id']; ?>">

            <section class="card form-card">
                <div class="card-body">
                    <div class="form-grid form-grid-client">

                        <div class="form-field">
                            <label class="label">Cliente</label>
                            <select class="select" name="customer_id">
                                <?php foreach ($customers as $customer): ?>
                                    <option value="<?php echo (int) $customer['id']; ?>" <?php echo (int) $opportunity['customer_id'] === (int) $customer['id'] ? 'selected' : ''; ?>>
                                        <?php echo safe_text(!empty($customer['commercial_name']) ? $customer['commercial_name'] : $customer['customer_name']); ?>
                                        <?php if (!empty($customer['customer_tax_id'])): ?>
                                            — <?php echo safe_text($customer['customer_tax_id']); ?>
                                        <?php endif; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="<?php echo field_class('title', $formErrors, true); ?>">
                            <label class="label">Título de la oportunidad</label>
                            <input
                                class="input"
                                type="text"
                                name="title"
                                required
                                value="<?php echo safe_text($formOld['title'] ?? $opportunity['title']); ?>"
                            >
                            <?php if ($error = field_error('title', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                    </div>
                </div>
            </section>

            <section class="card form-card">
                <div class="card-header">
                    <div>
                        <span class="label">Oportunidad</span>
                        <h3>Datos comerciales</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="form-grid form-grid-4">

                        <div class="<?php echo field_class('stage', $formErrors, true); ?>">
                            <label class="label">Etapa</label>
                            <div class="custom-select">
                                <button class="custom-select-trigger" type="button">
                                    <span class="custom-select-label">
                                        <?php echo safe_text($stageOptions[$stageValue] ?? 'Seleccionar estado'); ?>
                                    </span>
                                    <i data-lucide="chevron-down"></i>
                                </button>
                            
                                <input type="hidden" name="stage" value="<?php echo safe_text($stageValue); ?>">
                            
                                <div class="custom-select-menu">
                                    <?php foreach ($stageOptions as $value => $label): ?>
                                        <button class="custom-select-option <?php echo $stageValue === $value ? 'is-selected' : ''; ?>" type="button" data-value="<?php echo safe_text($value); ?>">
                                            <?php echo safe_text($label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php if ($error = field_error('stage', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>
                        
                        <div class="form-field">
                            <label class="label">Estado de cobranza</label>
                            <div class="custom-select">
                                <button class="custom-select-trigger" type="button">
                                    <span class="custom-select-label">
                                        <?php echo safe_text($paymentStatusOptions[$paymentStatusValue] ?? 'No facturado'); ?>
                                    </span>
                                    <i data-lucide="chevron-down"></i>
                                </button>
                            
                                <input type="hidden" name="payment_status" value="<?php echo safe_text($paymentStatusValue); ?>">
                            
                                <div class="custom-select-menu">
                                    <?php foreach ($paymentStatusOptions as $value => $label): ?>
                                        <button class="custom-select-option <?php echo $paymentStatusValue === $value ? 'is-selected' : ''; ?>" type="button" data-value="<?php echo safe_text($value); ?>">
                                            <?php echo safe_text($label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-field">
                            <label class="label">Fecha vencimiento pago</label>
                            <input
                                class="input"
                                type="date"
                                name="payment_due_date"
                                value="<?php echo safe_text($opportunity['payment_due_date']); ?>"
                            >
                        </div>
                        
                        <div class="form-field">
                            <label class="label">Fecha de pago</label>
                            <input
                                class="input"
                                type="date"
                                name="payment_paid_date"
                                value="<?php echo safe_text($opportunity['payment_paid_date']); ?>"
                            >
                        </div>

                        <div class="form-field">
                            <label class="label">Responsable comercial</label>
                            <select class="select" name="owner_user_id" onchange="this.nextElementSibling.value = this.options[this.selectedIndex].getAttribute('data-name') || '';">
                                <option value="">Sin responsable</option>
                                <?php foreach ($assignableUsers as $user): ?>
                                    <?php 
                                        $isSelected = false;
                                        if (!empty($opportunity['owner_user_id']) && (int)$opportunity['owner_user_id'] === (int)$user['id']) $isSelected = true;
                                        elseif (!empty($ownerValue) && $user['name'] === $ownerValue) $isSelected = true;
                                    ?>
                                    <option value="<?php echo (int)$user['id']; ?>" data-name="<?php echo safe_text($user['name']); ?>" <?php echo $isSelected ? 'selected' : ''; ?>>
                                        <?php echo safe_text($user['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            
                            <input type="hidden" name="owner_name" value="<?php echo safe_text($ownerValue ?? ''); ?>">
                        </div>

                        <div class="<?php echo field_class('source', $formErrors, true); ?>">
                            <label class="label">Origen</label>
                            <div class="custom-select">
                                <button class="custom-select-trigger" type="button">
                                    <span class="custom-select-label">
                                        <?php echo safe_text($sourceOptions[$sourceValue] ?? 'Seleccionar origen'); ?>
                                    </span>
                                    <i data-lucide="chevron-down"></i>
                                </button>
                            
                                <input type="hidden" name="source" value="<?php echo safe_text($sourceValue); ?>">
                            
                                <div class="custom-select-menu">
                                    <?php foreach ($sourceOptions as $value => $label): ?>
                                        <button
                                            class="custom-select-option <?php echo $sourceValue === $value ? 'is-selected' : ''; ?>"
                                            type="button"
                                            data-value="<?php echo safe_text($value); ?>"
                                        >
                                            <?php echo safe_text($label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php if ($error = field_error('source', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                        <div class="form-field">
                            <label class="label">Competidor / Alternativa</label>
                            <div class="custom-select">
                                <button class="custom-select-trigger" type="button">
                                    <span class="custom-select-label">
                                        <?php echo safe_text($competitorOptions[$competitorValue] ?? 'No identificado'); ?>
                                    </span>
                                    <i data-lucide="chevron-down"></i>
                                </button>
                            
                                <input type="hidden" name="competitor" value="<?php echo safe_text($competitorValue); ?>">
                            
                                <div class="custom-select-menu">
                                    <?php foreach ($competitorOptions as $value => $label): ?>
                                        <button class="custom-select-option <?php echo $competitorValue === $value ? 'is-selected' : ''; ?>" type="button" data-value="<?php echo safe_text($value); ?>">
                                            <?php echo safe_text($label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>

                        <div class="form-field">
                            <label class="label">Valor esperado</label>
                            <input
                                class="input"
                                type="number"
                                name="expected_value"
                                min="0"
                                step="1"
                                value="<?php echo (float) $opportunity['expected_value']; ?>"
                            >
                        </div>

                        <div class="form-field">
                            <label class="label">Probabilidad (%)</label>
                            <input
                                class="input"
                                type="number"
                                name="probability"
                                min="0"
                                max="100"
                                value="<?php echo (int) $opportunity['probability']; ?>"
                            >
                        </div>

                        <div class="<?php echo field_class('expected_close_date', $formErrors, true); ?>">
                            <label class="label">Fecha estimada de cierre</label>
                            <input
                                class="input"
                                type="date"
                                name="expected_close_date"
                                value="<?php echo safe_text($expectedCloseDateValue); ?>"
                            >
                            <?php if ($error = field_error('expected_close_date', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                        <div class="<?php echo field_class('next_action', $formErrors, true); ?>">
                            <label class="label">Próxima acción</label>
                            <div class="custom-select">
                                <button class="custom-select-trigger" type="button">
                                    <span class="custom-select-label">
                                        <?php echo safe_text($nextActionOptions[$nextActionValue] ?? 'Sin acción'); ?>
                                    </span>
                                    <i data-lucide="chevron-down"></i>
                                </button>
                            
                                <input type="hidden" name="next_action" value="<?php echo safe_text($nextActionValue); ?>">
                            
                                <div class="custom-select-menu">
                                    <?php foreach ($nextActionOptions as $value => $label): ?>
                                        <button class="custom-select-option <?php echo $nextActionValue === $value ? 'is-selected' : ''; ?>" type="button" data-value="<?php echo safe_text($value); ?>">
                                            <?php echo safe_text($label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php if ($error = field_error('next_action', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                        <div class="<?php echo field_class('next_action_date', $formErrors, true); ?>">
                            <label class="label">Fecha próxima acción</label>
                            <input
                                class="input"
                                type="date"
                                name="next_action_date"
                                value="<?php echo safe_text($nextActionDateValue); ?>"
                            >
                            <?php if ($error = field_error('next_action_date', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                        <div class="form-field form-field-wide">
                            <label class="label">Notas</label>
                            <textarea
                                class="textarea"
                                name="notes"
                                placeholder="Escribe aquí las notas de la oportunidad..."
                            ><?php echo safe_text($opportunity['notes']); ?></textarea>
                        </div>

                    </div>
                </div>
            </section>

            <section class="card form-card danger-zone">
                <div class="card-header">
                    <div>
                        <span class="label">Zona crítica</span>
                        <h3>Eliminar oportunidad</h3>
                    </div>
                </div>

                <div class="card-body">
                    <p class="text-secondary">
                        Esta acción quitará la oportunidad del CRM y del embudo, pero conservará el registro interno.
                    </p>

                    <button
                        class="btn btn-danger"
                        type="submit"
                        form="deleteOpportunityForm"
                    >
                        <i data-lucide="trash-2"></i>
                        <span>Eliminar oportunidad</span>
                    </button>
                </div>
            </section>

            <section class="card form-card form-actions-card">
                <div class="card-body">
                    <div class="cluster">
                        <button class="btn btn-primary" type="submit">
                            <i data-lucide="save"></i>
                            <span>Guardar cambios</span>
                        </button>

                        <a class="btn btn-outline" href="/modules/crm/opportunity.php?id=<?php echo (int) $opportunity['id']; ?>">
                            Cancelar
                        </a>
                    </div>
                </div>
            </section>

        </form>

        <form
            id="deleteOpportunityForm"
            action="/modules/crm/opportunity_delete.php"
            method="POST"
            onsubmit="return confirm('¿Seguro que quieres eliminar esta oportunidad?');"
        >
            <input type="hidden" name="id" value="<?php echo (int) $opportunity['id']; ?>">
        </form>

    </section>
</main>

<?php require_once '../../layouts/footer.php'; ?>