<?php
require_once __DIR__ . '/../../config/bootstrap.php';

use App\Services\SignatureService;
use App\Services\ContractService;
use App\Services\PDFService;
use App\Services\EmailService;

header('Content-Type: application/json');

// Solo aceptar POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método no permitido']);
    exit;
}

// Leer datos JSON
$json = file_get_contents('php://input');
$data = json_decode($json, true);

if (!$data) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Datos inválidos']);
    exit;
}

try {
    $signatureService = new SignatureService();
    $contractService = new ContractService();

    // Procesar firma
    $result = $signatureService->sign($data['token'], $data);

    if ($result['success']) {
        $contract = $result['contract'];
        $signatureId = $result['signature_id'];

        try {
            // Obtener firma guardada
            $signature = $signatureService->getByContract($contract['id']);

            // Generar PDF
            $pdfService = new PDFService();
            $pdfPathRelative = $pdfService->generateSignedContract($contract, $signature);

            // Convertir a path absoluto para adjuntar al email
            $pdfPathAbsolute = storage_path($pdfPathRelative);

            // Enviar email de confirmación con PDF adjunto (no bloquear si falla)
            try {
                $emailService = new EmailService();
                if ($emailService->isEnabled() && !empty($contract['cliente_email'])) {
                    // Adjuntar PDF del contrato firmado (path absoluto)
                    $emailService->sendSignatureConfirmation($contract, $signature, $pdfPathAbsolute);
                }
            } catch (Exception $emailError) {
                // Log error but don't fail the whole process
                error_log('Email error: ' . $emailError->getMessage());
            }

            echo json_encode([
                'success' => true,
                'message' => 'Contrato firmado exitosamente',
                'contract_id' => $contract['id'],
                'signature_id' => $signatureId
            ]);
        } catch (Exception $e) {
            error_log('Error processing signature: ' . $e->getMessage());
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'message' => 'Error al procesar la firma: ' . $e->getMessage()
            ]);
        }
    } else {
        http_response_code(400);
        echo json_encode($result);
    }
} catch (Exception $e) {
    error_log('Error in signature API: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error del servidor. Por favor, contacte al administrador.'
    ]);
}
