<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/database.php';
require_once '../../services/crm/OpportunityAccessService.php';

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

$isAjax = isset($_POST['ajax']) && $_POST['ajax'] === '1';
if ($isAjax) header('Content-Type: application/json; charset=utf-8');

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

csrf_require_valid_request();
$user = current_user() ?: array();
if (!OpportunityAccessService::canDelete($user)) {
    http_response_code(403);
    if ($isAjax) { echo json_encode(array('success' => false, 'error' => 'Solo Administración puede eliminar oportunidades. Usa Cerrar y archivar para conservar el historial.')); exit; }
    die('No autorizado.');
}

$pdo = db();
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($id <= 0) {
    http_response_code(422);
    if ($isAjax) { echo json_encode(array('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(PDO::FETCH_ASSOC);
if (!$opportunity) {
    http_response_code(404);
    if ($isAjax) { echo json_encode(array('success' => false, 'error' => 'Oportunidad no encontrada.')); exit; }
    die('Oportunidad no encontrada.');
}

$userName = trim((string)($user['name'] ?? $user['email'] ?? 'Sistema')) ?: 'Sistema';
try {
    $pdo->beginTransaction();
    $stmt = $pdo->prepare("UPDATE crm_opportunities SET deleted_at=NOW(), updated_at=NOW() WHERE id=? AND deleted_at IS NULL");
    $stmt->execute(array($id));
    if ($stmt->rowCount() !== 1) throw new RuntimeException('La oportunidad cambió antes de eliminarla.');

    $description = "Eliminación administrativa. El registro se conserva internamente.\nEtapa: " . ($opportunity['stage'] ?? 'sin etapa');
    if (!empty($opportunity['expected_value'])) $description .= "\nValor esperado: " . $opportunity['expected_value'];
    $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'] ?? null, $description, $userName));
    $pdo->commit();
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log('ICYLAB opportunity delete failed: ' . $e->getMessage());
    http_response_code(500);
    if ($isAjax) { echo json_encode(array('success' => false, 'error' => 'No fue posible eliminar la oportunidad.')); exit; }
    die('No fue posible eliminar la oportunidad.');
}

if ($isAjax) { echo json_encode(array('success' => true)); exit; }
header('Location: /modules/crm/');
exit;
