<?php

namespace App\Http\Controllers;

use App\Services\Minimax\MinimaxInvoiceService;
use App\Services\PdfCacheService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;

class InvoiceController extends Controller
{
    public function __construct(
        private MinimaxInvoiceService $invoiceService,
        private PdfCacheService $pdfCache,
    ) {}

    /**
     * GET /api/getIssuedInvoices
     * Old app: task=getIssuedInvoices with filters JSON
     */
    public function getIssuedInvoices(Request $request): JsonResponse
    {
        $account = $request->input('account', 'insoft');

        $filters = $request->has('filters')
            ? json_decode($request->input('filters'), true) ?? []
            : $request->only(['DateIssuedFrom', 'DateIssuedTo', 'InvoiceNumber', 'Order', 'PageSize', 'CurrentPage', 'CustomerID', 'Status', 'SortField']);

        $filters = array_filter($filters);
        $data = $this->invoiceService->getIssuedInvoices($account, $filters);

        return response()->json($data);
    }

    /**
     * GET /api/getIssuedInvoiceAllData
     * Old app: task=getIssuedInvoiceAllData&issuedInvoiceId=X
     */
    public function getIssuedInvoiceAllData(Request $request): JsonResponse
    {
        $request->validate(['issuedInvoiceId' => 'required|integer']);

        $account = $request->input('account', 'insoft');
        $invoiceId = (int) $request->input('issuedInvoiceId');

        $data = $this->invoiceService->getIssuedInvoiceAllData($account, $invoiceId);

        return response()->json($data);
    }

    /**
     * GET /api/generateInvoicePdf
     * Old app: task=generateInvoicePdf&issuedInvoiceId=X
     * Fetches PDF from Minimax and returns it as binary.
     */
    public function generateInvoicePdf(Request $request): Response
    {
        $request->validate(['issuedInvoiceId' => 'required|integer']);

        $account = $request->input('account', 'insoft');
        $issuedInvoiceId = (int) $request->input('issuedInvoiceId');

        // Get full invoice data to find document and attachment IDs
        $data = $this->invoiceService->getIssuedInvoiceAllData($account, $issuedInvoiceId);

        if (empty($data['Document']['ID']) || empty($data['InvoiceAttachment']['ID'])) {
            return response('No PDF attachment found', 404);
        }

        $attachment = $this->invoiceService->getDocumentAttachment(
            $account,
            $data['Document']['ID'],
            $data['InvoiceAttachment']['ID']
        );

        if (empty($attachment['AttachmentData'])) {
            return response('Empty attachment', 404);
        }

        $pdfContent = base64_decode($attachment['AttachmentData']);
        $fileName = $attachment['FileName'] ?? 'invoice.pdf';

        return response($pdfContent, 200)
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', "inline; filename=\"{$fileName}\"");
    }

    /**
     * GET /api/GetInvoiceFilesList
     * Old app: task=GetInvoiceFilesList
     */
    public function GetInvoiceFilesList(Request $request): JsonResponse
    {
        $files = Storage::files('invoices');
        $months = [];

        foreach ($files as $file) {
            $basename = basename($file, '.json');
            if (preg_match('/^\d{4}-\d{2}$/', $basename)) {
                $months[] = $basename;
            }
        }

        rsort($months);
        return response()->json($months);
    }
}
