<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php'; 
require_once '../../core/database.php';

require_login();
require_permission('module.crm'); 

// Capturar el usuario real que está eliminando la oportunidad
$sessionUser = current_user();
$currentUser = !empty($sessionUser['name']) ? $sessionUser['name'] : (!empty($sessionUser['email']) ? $sessionUser['email'] : 'Sistema');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die('Método no permitido.');
}

$pdo = db();
$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;

// 🔥 FIX: Detectar si la petición viene de nuestro interceptor AJAX
$isAjax = isset($_POST['ajax']) && $_POST['ajax'] === '1';

if ($id <= 0) {
    if ($isAjax) { echo json_encode(['success' => false, 'error' => 'ID inválido.']); exit; }
    die('ID inválido.');
}

$stmt = $pdo->prepare("
    SELECT *
    FROM crm_opportunities
    WHERE id = ?
      AND deleted_at IS NULL
    LIMIT 1
");

$stmt->execute(array($id));
$opportunity = $stmt->fetch();

if (!$opportunity) {
    if ($isAjax) { echo json_encode(['success' => false, 'error' => 'Oportunidad no encontrada.']); exit; }
    die('Oportunidad no encontrada.');
}

$stmt = $pdo->prepare("
    UPDATE crm_opportunities
    SET deleted_at = NOW()
    WHERE id = ?
");

$stmt->execute(array($id));

$description = "La oportunidad fue eliminada del embudo, pero se conserva el registro interno.";

if (!empty($opportunity['expected_value'])) {
    $description .= "\nValor esperado: " . $opportunity['expected_value'];
}

if (!empty($opportunity['stage'])) {
    $description .= "\nEtapa al eliminar: " . $opportunity['stage'];
}

$stmt = $pdo->prepare("
    INSERT INTO crm_activities
    (
        opportunity_id,
        customer_id,
        customer_name,
        activity_type,
        title,
        description,
        owner_name,
        activity_date
    )
    VALUES (?, ?, ?, 'deleted', 'Oportunidad eliminada', ?, ?, NOW())
");

$stmt->execute(array(
    $id,
    !empty($opportunity['customer_id']) ? (int) $opportunity['customer_id'] : null,
    $opportunity['customer_name'],
    $description,
    $currentUser
));

// 🔥 FIX: Si es AJAX, respondemos JSON y terminamos. Si no, hacemos el redirect clásico.
if ($isAjax) {
    header('Content-Type: application/json');
    echo json_encode(['success' => true]);
    exit;
}

header('Location: /modules/crm/');
exit;