<?php

namespace App\Http\Controllers;

use App\Services\SawCalculationService;
use App\Exceptions\SawCalculationException;
use App\Models\HasilPenilaian;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\HasilPerhitunganExport;

class SawController extends Controller
{
    protected $sawService;

    public function __construct(SawCalculationService $sawService)
    {
        $this->sawService = $sawService;
    }

    /**
     * Handle request untuk perhitungan SAW
     */
    public function hitungSAW(Request $request)
    {
        $request->validate([
            'jenis_pengajuan' => 'required|in:penurunan,pengangsuran'
        ]);

        try {
            $result = $this->sawService->prosesPerhitunganLengkap($request->jenis_pengajuan);
            
            return redirect()
                ->route('admin.hasil-perhitungan')
                ->with([
                    'success' => $result['message'],
                    'result' => $result
                ]);
                
        } catch (SawCalculationException $e) {
            return back()
                ->withInput()
                ->with('error', $e->getMessage());
        }
    }

    /**
     * Tampilkan hasil perhitungan
     */
    public function showHasil()
    {
        $results = HasilPenilaian::with(['pengajuan.mahasiswa.user'])
            ->orderBy('nilai_preferensi', 'desc')
            ->paginate(10);
            
        return view('admin.hasil-perhitungan', compact('results'));
    }

    /**
     * Download hasil perhitungan
     */
    public function downloadHasil(Request $request)
    {
        $request->validate([
            'jenis' => 'required|in:pdf,excel',
            'limit' => 'nullable|integer|min:1|max:1000'
        ]);
        
        $results = HasilPenilaian::with(['pengajuan.mahasiswa.user'])
            ->orderBy('nilai_preferensi', 'desc')
            ->limit($request->limit ?? 100)
            ->get();
            
        if ($request->jenis == 'pdf') {
            return $this->generatePDF($results);
        }
        
        return $this->generateExcel($results);
    }
    
    protected function generatePDF($data)
    {
        return Pdf::loadView('admin.exports.hasil-pdf', ['results' => $data])
            ->setPaper('a4', 'landscape')
            ->stream('hasil-saw-'.now()->format('Ymd').'.pdf');
    }
    
    protected function generateExcel($data)
    {
        return Excel::download(new HasilPerhitunganExport($data), 
            'hasil-saw-'.now()->format('Ymd').'.xlsx');
    }
}