<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\TartanApiService;
use App\Services\PdfReportService;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use ZipArchive;

class ReportController extends Controller
{
    protected $tartanApi;
    protected $pdfService;

    public function __construct(TartanApiService $tartanApi, PdfReportService $pdfService)
    {
        $this->tartanApi = $tartanApi;
        $this->pdfService = $pdfService;
    }

    public function showDashboard()
    {
        return view('dashboard');
    }

    public function generate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'request_type' => 'required|in:single,multiple',
            'uan_single' => 'required_if:request_type,single|nullable|string|digits:12',
            'uan_file' => 'required_if:request_type,multiple|nullable|file|mimes:txt',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => $validator->errors()->first()], 422);
        }

        $token = $this->tartanApi->getValidToken();
        if (!$token) {
            return response()->json(['success' => false, 'message' => 'Could not authenticate with the verification service.'], 500);
        }

        if ($request->input('request_type') === 'single') {
            return $this->handleSingleUanRequest($request, $token);
        } else {
            return $this->handleMultipleUanRequest($request, $token);
        }
    }

    private function handleSingleUanRequest(Request $request, string $token)
    {
        $uan = $request->input('uan_single');
        $data = $this->tartanApi->getVerificationDetails($token, $uan);

        if (!$data || isset($data['error']) || !isset($data['response']['employment_data'])) {
             $error = "API Error for UAN {$uan}: " . ($data['error']['message'] ?? 'Invalid response or no data found.');
             return response()->json(['success' => false, 'message' => $error], 422);
        }

        $this->pdfService->generate($data, $uan);
        $pdfContent = $this->pdfService->Output('S');
        
        $filename = "UAN_Report_{$uan}_" . now()->format('Ymd_His') . ".pdf";
        $tempPath = 'temp/' . $filename;
        Storage::disk('public')->put($tempPath, $pdfContent);

        return response()->json([
            'success' => true,
            'download_url' => Storage::url($tempPath),
            'file_name' => $filename // <-- ADDED THIS
        ]);
    }

    private function handleMultipleUanRequest(Request $request, string $token)
    {
        $file = $request->file('uan_file');
        $contents = file_get_contents($file->getRealPath());
        $uans = array_filter(array_map('trim', explode("\n", $contents)));

        if (empty($uans)) {
            return response()->json(['success' => false, 'message' => 'The uploaded file is empty or invalid.'], 422);
        }

        $jobId = uniqid('uan_batch_');
        $tempServerPath = storage_path("app/temp_server/{$jobId}");
        File::makeDirectory($tempServerPath, 0755, true);

        $successCount = 0;
        foreach ($uans as $uan) {
            if (!preg_match('/^\d{12}$/', $uan)) continue;
            $data = $this->tartanApi->getVerificationDetails($token, $uan);
            if ($data && isset($data['response']['employment_data']) && !empty($data['response']['employment_data'])) {
                $pdf = new PdfReportService();
                $pdf->generate($data, $uan);
                $pdf->Output('F', "{$tempServerPath}/UAN_Report_{$uan}.pdf");
                $successCount++;
            }
        }
        
        if ($successCount === 0) {
            File::deleteDirectory($tempServerPath);
            return response()->json(['success' => false, 'message' => 'Could not generate a report for any of the UANs provided.'], 422);
        }

        $zipFileName = "UAN_Reports_" . now()->format('Ymd_His') . ".zip";
        $zipServerPath = storage_path("app/temp_server/{$zipFileName}");
        $zip = new ZipArchive();

        if ($zip->open($zipServerPath, ZipArchive::CREATE) === TRUE) {
            $files = File::files($tempServerPath);
            foreach ($files as $file) {
                $zip->addFile($file->getRealPath(), $file->getFilename());
            }
            $zip->close();
        }
        File::deleteDirectory($tempServerPath);

        $publicZipPath = 'temp/' . $zipFileName;
        rename($zipServerPath, storage_path('app/public/' . $publicZipPath));

        return response()->json([
            'success' => true,
            'download_url' => Storage::url($publicZipPath),
            'file_name' => $zipFileName // <-- ADDED THIS
        ]);
    }
}