<?php
/**
 * ICYLAB OS - Restauración de cotizaciones eliminadas
 */
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_restore_current_user_name()
{
    $user = current_user();
    if (!empty($user['name'])) return $user['name'];
    if (!empty($user['email'])) return $user['email'];
    return 'Sistema';
}

function quote_restore_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 restaurar la cotización.');
    }

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

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

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

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

try {
    $service = new QuoteLifecycleService(db());
    $result = $service->restore($id, array(
        'owner_name' => quote_restore_current_user_name()
    ));

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