<?php

namespace App\Services;

use App\Models\AnalysisResult;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use ZipArchive;

class ReportGeneratorService
{
    protected $zScoreService;

    public function __construct(AltmanZScoreService $zScoreService)
    {
        $this->zScoreService = $zScoreService;
    }

    /**
     * Generate PDF report for analysis result
     * 
     * @param AnalysisResult $analysis
     * @return \Barryvdh\DomPDF\PDF
     */
    public function generatePDF(AnalysisResult $analysis)
    {
        $financialData = $analysis->financial_data;
        $components = [
            'x1' => $analysis->x1,
            'x2' => $analysis->x2,
            'x3' => $analysis->x3,
            'x4' => $analysis->x4,
            'x5' => $analysis->x5,
        ];
        
        $interpretation = $this->zScoreService->getInterpretation(
            $analysis->z_score, 
            $analysis->z_category
        );
        
        $componentAnalysis = $this->zScoreService->getComponentAnalysis($components);

        $data = [
            'analysis' => $analysis,
            'financial' => $financialData,
            'components' => $components,
            'interpretation' => $interpretation,
            'componentAnalysis' => $componentAnalysis,
            'generated_at' => now()->format('d F Y H:i:s'),
            'generated_by' => auth()->user()->name ?? 'System',
        ];

        $pdf = Pdf::loadView('report.pdf', $data);
        $pdf->setPaper('A4', 'portrait');
        $pdf->setOptions([
            'defaultFont' => 'sans-serif',
            'isHtml5ParserEnabled' => true,
            'isRemoteEnabled' => true
        ]);

        return $pdf;
    }

    /**
     * Generate custom PDF with selected options
     * 
     * @param AnalysisResult $analysis
     * @param array $options
     * @return \Barryvdh\DomPDF\PDF
     */
    public function generateCustomPDF(AnalysisResult $analysis, array $options = [])
    {
        $financialData = $analysis->financial_data;
        $components = [
            'x1' => $analysis->x1,
            'x2' => $analysis->x2,
            'x3' => $analysis->x3,
            'x4' => $analysis->x4,
            'x5' => $analysis->x5,
        ];

        $data = [
            'analysis' => $analysis,
            'financial' => $financialData,
            'components' => $components,
            'options' => $options,
            'generated_at' => now()->format('d F Y H:i:s'),
        ];

        // Include or exclude sections based on options
        if (!($options['include_charts'] ?? true)) {
            $data['hide_charts'] = true;
        }
        
        if (!($options['include_recommendations'] ?? true)) {
            $data['hide_recommendations'] = true;
        }
        
        if (!($options['include_detailed_calculations'] ?? true)) {
            $data['hide_calculations'] = true;
        }

        $view = $options['template'] ?? 'report.custom';
        
        $pdf = Pdf::loadView($view, $data);
        $pdf->setPaper('A4', 'portrait');

        return $pdf;
    }

    /**
     * Generate comparison PDF for multiple analyses
     * 
     * @param \Illuminate\Support\Collection $analyses
     * @return \Barryvdh\DomPDF\PDF
     */
    public function generateComparisonPDF($analyses)
    {
        $data = [
            'analyses' => $analyses,
            'generated_at' => now()->format('d F Y H:i:s'),
            'total_analyses' => $analyses->count(),
        ];

        $pdf = Pdf::loadView('report.comparison', $data);
        $pdf->setPaper('A4', 'landscape');

        return $pdf;
    }

    /**
     * Generate PDF with template
     * 
     * @param AnalysisResult $analysis
     * @param string $templateId
     * @param array $options
     * @return \Barryvdh\DomPDF\PDF
     */
    public function generateWithTemplate(AnalysisResult $analysis, string $templateId, array $options = [])
    {
        $template = $this->getTemplate($templateId);
        
        $data = [
            'analysis' => $analysis,
            'financial' => $analysis->financial_data,
            'components' => [
                'x1' => $analysis->x1,
                'x2' => $analysis->x2,
                'x3' => $analysis->x3,
                'x4' => $analysis->x4,
                'x5' => $analysis->x5,
            ],
            'template' => $template,
            'options' => $options,
        ];

        $pdf = Pdf::loadView("report.templates.{$template['view']}", $data);
        $pdf->setPaper($template['paper'] ?? 'A4', $template['orientation'] ?? 'portrait');

        return $pdf;
    }

    /**
     * Send report via email
     * 
     * @param AnalysisResult $analysis
     * @param string $email
     * @param string|null $message
     * @return void
     */
    public function sendEmail(AnalysisResult $analysis, string $email, ?string $message = null)
    {
        $pdf = $this->generatePDF($analysis);
        $pdfContent = $pdf->output();

        $data = [
            'analysis' => $analysis,
            'user_message' => $message,
            'sender_name' => auth()->user()->name,
        ];

        Mail::send('emails.report', $data, function ($mail) use ($analysis, $email, $pdfContent) {
            $mail->to($email)
                ->subject('Laporan Analisis Keuangan: ' . $analysis->company_name)
                ->attachData($pdfContent, 'analisis-' . $analysis->company_name . '.pdf', [
                    'mime' => 'application/pdf',
                ]);
        });
    }

    /**
     * Generate batch PDF (merge multiple PDFs)
     * 
     * @param \Illuminate\Support\Collection $analyses
     * @return \Barryvdh\DomPDF\PDF
     */
    public function generateBatchPDF($analyses)
    {
        // This is simplified - in production you might want to use a PDF merger
        $data = [
            'analyses' => $analyses,
            'generated_at' => now()->format('d F Y H:i:s'),
        ];

        $pdf = Pdf::loadView('report.batch', $data);
        $pdf->setPaper('A4', 'portrait');

        return $pdf;
    }

    /**
     * Generate batch ZIP file
     * 
     * @param \Illuminate\Support\Collection $analyses
     * @return string Path to ZIP file
     */
    public function generateBatchZip($analyses)
    {
        $zip = new ZipArchive();
        $zipFileName = 'reports-' . now()->format('Y-m-d-His') . '.zip';
        $zipPath = storage_path('app/temp/' . $zipFileName);

        // Create temp directory if not exists
        if (!file_exists(storage_path('app/temp'))) {
            mkdir(storage_path('app/temp'), 0755, true);
        }

        if ($zip->open($zipPath, ZipArchive::CREATE) === true) {
            foreach ($analyses as $analysis) {
                $pdf = $this->generatePDF($analysis);
                $pdfContent = $pdf->output();
                
                $fileName = str_replace(' ', '-', $analysis->company_name) 
                          . '-' . $analysis->period . '.pdf';
                
                $zip->addFromString($fileName, $pdfContent);
            }
            
            $zip->close();
        }

        return $zipPath;
    }

    /**
     * Get available templates
     * 
     * @return array
     */
    public function getTemplates(): array
    {
        return [
            [
                'id' => 'standard',
                'name' => 'Standar',
                'description' => 'Laporan analisis standar dengan semua komponen',
                'icon' => 'fa-file-pdf',
                'view' => 'standard',
                'paper' => 'A4',
                'orientation' => 'portrait'
            ],
            [
                'id' => 'executive',
                'name' => 'Ringkas',
                'description' => 'Laporan ringkas untuk eksekutif (1 halaman)',
                'icon' => 'fa-file-lines',
                'view' => 'executive',
                'paper' => 'A4',
                'orientation' => 'portrait'
            ],
            [
                'id' => 'detailed',
                'name' => 'Detail',
                'description' => 'Laporan detail dengan perhitungan lengkap',
                'icon' => 'fa-file-lines',
                'view' => 'detailed',
                'paper' => 'A4',
                'orientation' => 'portrait'
            ],
            [
                'id' => 'presentation',
                'name' => 'Presentasi',
                'description' => 'Format siap presentasi dengan grafik',
                'icon' => 'fa-chart-pie',
                'view' => 'presentation',
                'paper' => 'A4',
                'orientation' => 'landscape'
            ],
        ];
    }

    /**
     * Get template by ID
     * 
     * @param string $templateId
     * @return array|null
     */
    public function getTemplate(string $templateId): ?array
    {
        $templates = $this->getTemplates();
        
        foreach ($templates as $template) {
            if ($template['id'] === $templateId) {
                return $template;
            }
        }
        
        return $templates[0]; // Return default template
    }
}