<?php
/**
 * Desactiva un cliente mediante soft delete.
 * No elimina registros físicos ni rompe el historial comercial asociado.
 */
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/database.php';
require_once '../../services/crm/CustomerLifecycleService.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /modules/customers/index.php');
    exit;
}

$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
$reason = trim($_POST['reason'] ?? 'Desactivación manual desde módulo clientes');

if ($id <= 0) {
    die('ID de cliente inválido.');
}

try {
    $user = current_user();
    $userName = $user['name'] ?? ($user['email'] ?? 'Sistema');

    $lifecycle = new CustomerLifecycleService(db());
    $result = $lifecycle->softDelete($id, $userName, $reason);

    $suffix = !empty($result['already_deleted']) ? 'already_deleted=1' : 'deleted=1';
    header('Location: /modules/customers/index.php?' . $suffix);
    exit;
} catch (Throwable $e) {
    die('Error al desactivar el cliente: ' . $e->getMessage());
}
