<?php

namespace App\Http\Controllers\Endocapture;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Models\Mongo;
class ExportPdfController extends Controller
{
    // public function __construct()
    // {
    //     $this->middleware('auth');
    // }

    public function index(Request $r)
    {
        $view['hospital'] = Mongo::table('tb_department')
        ->where("department_name", "like", "%โรงพยาบาล%")
        ->get();


        return view('endoindex.exportpdf', $view);
    }
    public function show($hospital)
    {
        $tb_case = Mongo::table("tb_case")
        ->where("appointment_date" , "2025-05-02")
        ->where("department" , $hospital)->get();

        $pdf_files = [];
        foreach($tb_case as $case){
            $path_case = 'D:/laragon/htdocs/store/' . $case['hn'] . '/' . $case['appointment_date'] . '/' .'pdf';

            if (file_exists($path_case)) {
                $filepath = array_filter(scandir($path_case), function($file) {
                    return strpos($file, 9002) === 0 && pathinfo($file, PATHINFO_EXTENSION) === 'pdf';
                });

                if (!empty($filepath)) {
                    foreach ($filepath as $file) {
                        $pdf_files[] = [
                            'hn' => $case['hn'],
                            'appointment_date' => $case['appointment_date'],
                            'pdf_path' => $path_case . '/' . $file,
                            'pdf_name' => $file
                        ];
                    }
                }
            }
        }

        // Create zip archive
        $zip = new \ZipArchive();
        $zipName = 'pdf_files_' . date('Y-m-d_H-i-s') . '.zip';
        $zip->open($zipName, \ZipArchive::CREATE);

        // Add files to zip
        foreach ($pdf_files as $pdf_case) {
            if (file_exists($pdf_case['pdf_path'])) {
                $zip->addFile($pdf_case['pdf_path'], $pdf_case['pdf_name']);
            }
        }

        $zip->close();

        // Download zip file
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $zipName . '"');
        header('Content-Length: ' . filesize($zipName));
        readfile($zipName);
        unlink($zipName); // Delete temporary zip file
    }
}