<?php

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

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

header('Content-Type: application/json; charset=utf-8');

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

csrf_require_valid_request();

try {
    $service = new OpportunityLifecycleService();
    $result = $service->reopen(
        $_POST['id'] ?? 0,
        $_POST['stage'] ?? '',
        $_POST['reason'] ?? '',
        $_POST['next_action'] ?? '',
        $_POST['next_action_date'] ?? '',
        current_user() ?: array(),
        !empty($_POST['allow_financial_reversal'])
    );

    echo json_encode(array('success' => true, 'result' => $result), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (OpportunityAuthorizationException $e) {
    http_response_code(403);
    echo json_encode(array('success' => false, 'error' => $e->getMessage()), JSON_UNESCAPED_UNICODE);
} catch (InvalidArgumentException $e) {
    http_response_code(422);
    echo json_encode(array('success' => false, 'error' => $e->getMessage()), JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    error_log('ICYLAB opportunity reopen failed: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(array('success' => false, 'error' => 'No fue posible reabrir la oportunidad.'), JSON_UNESCAPED_UNICODE);
}
