<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Contract\GenerateContractRequest;
use App\Services\ContractDirector;
use Illuminate\Http\JsonResponse;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Exception;

class ContractController extends Controller
{
    public function __construct(protected ContractDirector $contractDirector)
    {
    }

    public function generate(GenerateContractRequest $request): JsonResponse
    {
        $response = $this->contractDirector->buildContract(
            $request->input('contrato'),
            $request->input('variables')
        );

        if (!$response->success) {
            return response()->json([
                'success' => false,
                'error' => $response->error,
                'context' => $response->context,
            ], 422);
        }

        try {

            $html = $response->result->toHtml();

            // // Crear un objeto PhpWord
            // $phpWord = new PhpWord();
            // $section = $phpWord->addSection();

            // // Agregar HTML al documento
            // \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false);

            // // Guardar temporalmente
            // $fileName = 'Contrato_' . Str::random(6) . '.docx';
            // $tempFile = storage_path('app/public/' . $fileName);

            // $writer = IOFactory::createWriter($phpWord, 'Word2007');
            // $writer->save($tempFile);

            // Devolver URL de descarga
            return response()->json([
                // 'docx_url' => asset('storage/' . $fileName),
                'success' => true,
                'html' => $html,
                'sections' => $response->result->toArray(),
            ], 200, [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        } catch (Exception $e) {
            Log::error('Error al construir contrato word', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            return response()->json([
                'success' => false,
            ], 422);
        }
    }
}