<?php

namespace App\Services;

use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\View;

class PdfExportService
{
    /**
     * Export report data to PDF
     */
    public function export(string $reportType, array $data, string $fileName): string
    {
        $html = $this->generateHtml($reportType, $data);
        
        $pdf = Pdf::loadHTML($html)
            ->setPaper('a4', 'portrait')
            ->setOptions([
                'isHtml5ParserEnabled' => true,
                'isRemoteEnabled' => true,
                'defaultFont' => 'sans-serif'
            ]);

        $filePath = storage_path('app/temp/' . $fileName);
        
        // Ensure temp directory exists
        if (!file_exists(dirname($filePath))) {
            mkdir(dirname($filePath), 0755, true);
        }

        $pdf->save($filePath);

        return $filePath;
    }

    /**
     * Generate HTML for the report
     */
    private function generateHtml(string $reportType, array $data): string
    {
        $title = $this->getReportTitle($reportType);
        
        return view('reports.pdf-template', [
            'title' => $title,
            'reportType' => $reportType,
            'data' => $data,
            'generatedAt' => now()->format('Y-m-d H:i:s')
        ])->render();
    }

    /**
     * Get report title
     */
    private function getReportTitle(string $reportType): string
    {
        return match ($reportType) {
            'sales-summary' => 'Sales Summary Report',
            'sales-by-customer' => 'Sales by Customer Report',
            'sales-by-product' => 'Sales by Product Report',
            'payment-received' => 'Payment Received Report',
            'purchase-summary' => 'Purchase Summary Report',
            'purchase-by-supplier' => 'Purchase by Supplier Report',
            'payment-made' => 'Payment Made Report',
            'stock-summary' => 'Stock Summary Report',
            'low-stock-alert' => 'Low Stock Alert Report',
            'stock-movement' => 'Stock Movement Report',
            'profit-loss' => 'Profit & Loss Statement',
            'cash-flow' => 'Cash Flow Report',
            'tax-summary' => 'Tax Summary Report',
            'outstanding-receivables' => 'Outstanding Receivables Report',
            'outstanding-payables' => 'Outstanding Payables Report',
            default => 'Report'
        };
    }
}