<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
use ZipArchive;
use Illuminate\Support\Facades\Http;

class PreAuthController extends Controller
{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if (!session()->has('authenticated') || session()->get('authenticated') !== true) {
                $slug = session('customer', '');
                return redirect("/$slug");
            }
            return $next($request);
        });
    }

    public function preAuth()
    {
        if(in_array('PREAUTH', session('features', []))){
            return view('pre-auth');
        }else{
            return redirect()->route('dashboard');
        }
    }

    /**
     * Download the PDF file.
     */
    public function downloadPDF(Request $request)
    {
        $content = $request->input('content');

        if (empty($content)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Content is required.'
            ], 400);
        }

        $html = view('pdf.pdf-preview', compact('content'))->render();

        $pdf = Pdf::loadHTML($html);
        return response($pdf->output(), 200)
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', 'attachment; filename="Pre Auth.pdf"');
    }

    /**
     * Download the PDF file.
     */
    public function downloadBunchPDF(Request $request)
    {
        $content = $request->input('content');
        $files = $request->input('files');

        if (empty($content)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Content is required.'
            ], 400);
        }

        $html = view('pdf.pdf-preview', compact('content'))->render();
        $pdf = Pdf::loadHTML($html);
        $pdfOutput = $pdf->output();
        
        // Create a new ZipArchive
        $zip = new ZipArchive();
        $zipFileName = 'eligibility-bunch.zip';
        $tempZipPath = storage_path('app/temp/' . $zipFileName);
        // Ensure the temporary directory exists
        if (!file_exists(dirname($tempZipPath))) {
            mkdir(dirname($tempZipPath), 0755, true);
        }
        
        if ($zip->open($tempZipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
            $zip->addFromString('Prior Auth.pdf', $pdfOutput);
            foreach ($files as $url) {
                $apiendPoint = env('API_URL').session('currentEHR').'/report/details';
                $data = [
                    'reportId' => $request->input('patientId'),
                    'reportURL' => $url,
                    'timezone' => $request->input('timezone'),
                    'customer' => session('customer'),
                    'practitionerId' => session('PractitionerId')
                ];
                // Make the POST request using Laravel's HTTP client
                $response = Http::withHeaders([
                    'Authorization' => 'Bearer ' . session('accessToken') .', Medx '. session('jwt_token'),
                ])->asForm()->post($apiendPoint, $data);
                // Check if the request was successful
                if ($response->successful()) {
                    $responseData = $response->json();
                    // Extract the file content, content type, and file name from the response
                    $fileData = $responseData['data']['data'] ?? null;
                    $fileContentType = $responseData['data']['contentType'] ?? null;
                    if($fileData != null){
                        $decodedFileData = base64_decode($fileData);
                        $zip->addFromString(basename(parse_url($url, PHP_URL_PATH)), $decodedFileData);
                    }
                } else {
                    // Handle error or failure
                    \Log::info('File not found or downloaded from origin '.$url);
                }
            }
            $zip->close();
            // Return the ZIP file as a download
            return response()->download($tempZipPath)->deleteFileAfterSend(true);
        } else {
            return response()->json(['error' => 'Unable to create zip file.'], 500);
        }
    }
}
