<?php
/**
 * ICYLAB OS - Soft delete de cotizaciones
 */
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/permissions.php';
require_once '../../services/crm/QuoteLifecycleService.php';

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

function quote_delete_current_user_name()
{
    $user = current_user();
    if (!empty($user['name'])) return $user['name'];
    if (!empty($user['email'])) return $user['email'];
    return 'Sistema';
}

function quote_delete_respond($success, $payload = array())
{
    if (isset($_POST['ajax']) && (string)$_POST['ajax'] === '1') {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(array_merge(array('success' => $success), $payload), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    if (!$success) {
        die($payload['error'] ?? 'No fue posible eliminar la cotización.');
    }

    $redirect = $_POST['redirect'] ?? '/modules/crm/quotes.php';
    header('Location: ' . $redirect);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    quote_delete_respond(false, array('error' => 'Método no permitido.'));
}

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$reason = trim((string)($_POST['reason'] ?? ''));

if ($id <= 0) {
    quote_delete_respond(false, array('error' => 'ID inválido.'));
}

try {
    $service = new QuoteLifecycleService(db());
    $result = $service->softDelete($id, array(
        'owner_name' => quote_delete_current_user_name(),
        'reason' => $reason
    ));

    quote_delete_respond(true, array(
        'quote_id' => $id,
        'quote_number' => $result['quote_number'] ?? '',
        'already_deleted' => !empty($result['already_deleted'])
    ));
} catch (Throwable $e) {
    quote_delete_respond(false, array('error' => $e->getMessage()));
}
