<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\OPD;
use App\Models\Question;
use App\Models\Response;
use App\Models\AnswerOption;
use App\Services\SKMCalculationService;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\SKMExport;
use Dompdf\Dompdf;
use Dompdf\Options;

class ExportController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function exportExcel($opdId)
    {
        $opd = OPD::findOrFail($opdId);
        return Excel::download(new SKMExport($opdId), "skm-{$opd->code}.xlsx");
    }

    public function exportPdf($opdId)
    {
        $opd = OPD::findOrFail($opdId);
        $questions = Question::where('is_active', true)
            ->with('activeAnswerOptions')
            ->orderBy('order')
            ->get();
        $skmService = new SKMCalculationService();
        
        $skmData = $skmService->calculateSKM($opdId);
        $elementStats = $skmService->calculateElementStats($opdId);
        
        $results = [];
        foreach ($questions as $question) {
            $questionStats = $skmService->calculateQuestionStats($opdId, $question->id);
            
            $distribution = [];
            foreach ($question->activeAnswerOptions as $option) {
                $count = 0;
                if (isset($questionStats['answer_distribution'][$option->id])) {
                    $count = $questionStats['answer_distribution'][$option->id]['count'];
                }
                $distribution[$option->id] = [
                    'option' => $option,
                    'count' => $count,
                ];
            }
            
            $results[] = [
                'question' => $question,
                'stats' => $questionStats,
                'distribution' => $distribution,
            ];
        }
        
        $html = view('admin.pdf-report', compact('opd', 'results', 'skmData', 'elementStats'))->render();
        
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isRemoteEnabled', true);
        
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();
        
        return response()->streamDownload(function () use ($dompdf) {
            echo $dompdf->output();
        }, "skm-{$opd->code}.pdf", [
            'Content-Type' => 'application/pdf',
        ]);
    }
}

