<?php

namespace App\Http\Controllers\EndoCAPTURE;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Mongo;
use ZipArchive;

// use App\Http\Controllers\Api\PDFController;
use App\Http\Controllers\Api\PDFController;
class PrintPDFController extends Controller
{
    public function index(Request $r)
    {

        $department = $r->department;

        $view['tb_case']    = $this->searchCases($r, false);
        $view['tb_caseyet'] = $this->searchCases($r, true);
        $view['department'] = $department;
        $view['search']     = $this->searchValues($r);
        return view("printpdf/index",$view);
    }

    public function show($id)
    {

        Mongo::table("tb_case")->where("_id", $id)->update([
            'statusprint' => true
        ]);
        return redirect("api/pdf/".$id);
    }

    public function store(Request $r)
    {

        if($r->event == "exportpdf"){
           return $this->exportPdf($r);
        }

        if($r->event == "search"){
           return $this->search($r);
        }
    }

    /**
     * ค้นหาแบบ AJAX (โฟลว์เดียวกับ job_all ของหน้า home)
     * คืน HTML ของ tbody ทั้งสองตารางพร้อมจำนวนรายการ
     */
    public function search(Request $r)
    {
        $tb_case    = $this->searchCases($r, false);
        $tb_caseyet = $this->searchCases($r, true);

        return response()->json([
            'wait'          => view('printpdf.table.wait',    ['tb_case'    => $tb_case])->render(),
            'printed'       => view('printpdf.table.printed', ['tb_caseyet' => $tb_caseyet])->render(),
            'wait_count'    => count($tb_case),
            'printed_count' => count($tb_caseyet),
        ]);
    }

    /**
     * ค่าค้นหาที่รับมาจากฟอร์ม (ล้างค่าให้ปลอดภัยก่อนใช้)
     */
    private function searchValues(Request $r)
    {
        return [
            'hn'       => trim((string) $r->input('search_hn')),
            'name'     => trim((string) $r->input('search_name')),
            'doctor'   => trim((string) $r->input('search_doctor')),
            'datefrom' => $this->cleanDate($r->input('search_datefrom')),
            'dateto'   => $this->cleanDate($r->input('search_dateto')),
        ];
    }

    private function cleanDate($v)
    {
        return preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $v) ? (string) $v : '';
    }

    /**
     * @param bool $printed true = รายการที่พิมพ์แล้ว, false = รายการรอพิมพ์
     */
    private function searchCases(Request $r, $printed)
    {
        $s = $this->searchValues($r);

        $w   = [];
        $w[] = array('statusjob', 'recovery');
        $w[] = array('department', $r->department);

        if ($s['hn'] !== '') {
            $w[] = array('case_hn', 'LIKE', '%' . $s['hn'] . '%');
        }
        if ($s['name'] !== '') {
            $w[] = array('patientname', 'LIKE', '%' . $s['name'] . '%');
        }
        if ($s['doctor'] !== '') {
            $w[] = array('doctorname', 'LIKE', '%' . $s['doctor'] . '%');
        }

        $query = Mongo::table("tb_case")->where($w);
        $query = $printed
            ? $query->where('statusprint', true)
            : $query->where('statusprint', null);

        // appointment_date เก็บเป็นสตริง Y-m-d จึงเทียบช่วงด้วย >= / <= ได้ตรงตัว
        if ($s['datefrom'] !== '' && $s['dateto'] !== '') {
            $query->where('appointment_date', '>=', $s['datefrom'])
                  ->where('appointment_date', '<=', $s['dateto']);
        } elseif ($s['datefrom'] !== '') {
            $query->where('appointment_date', '>=', $s['datefrom']);
        } elseif ($s['dateto'] !== '') {
            $query->where('appointment_date', '<=', $s['dateto']);
        } else {
            // ไม่ระบุช่วงวัน = ค่าเริ่มต้นเดิม คือตั้งแต่วันนี้เป็นต้นไป
            $query->where('appointment_date', '>=', date('Y-m-d'));
        }

        return $query->orderBy('appointment_date', 'DESC')->limit(500)->get();
    }


    public function exportPdf(Request $r)
    {

        $query = Mongo::table("tb_case")
        ->where('statusjob','recovery')
        ->where('department',$r->department);

        $exportDate = $r->filled('export_date') ? $r->export_date : date('Y-m-d');
        $query->where('appointment_date', $exportDate);

        $tb_case = $query->get();

        $startTs = time();
        foreach ($tb_case as $case) {
            $id = (string)$case['_id'];
            $this->temp_pdf($id,'pdf',$r->department);
        }

        // PDFController::get_pdffile จะ save ไว้ที่ D:/pdfall/<appointment_date>/*.pdf
        $pdfDir = 'D:/pdfall/' . $exportDate;
        if (!is_dir($pdfDir)) {
            return redirect()->back()->with('error', 'ไม่พบโฟลเดอร์ไฟล์ PDF ที่ export');
        }

        $pdfFiles = glob($pdfDir . '/*.pdf') ?: [];
        // เอาเฉพาะไฟล์ที่เพิ่งสร้างในรอบนี้ (กัน zip ไฟล์เก่าๆ ปน)
        $pdfFiles = array_values(array_filter($pdfFiles, function ($path) use ($startTs) {
            $mtime = @filemtime($path);
            return $mtime !== false && $mtime >= ($startTs - 2);
        }));

        if (count($pdfFiles) === 0) {
            return redirect()->back()->with('error', 'ไม่มีไฟล์ PDF ให้ดาวน์โหลด (อาจไม่มีเคสในวันที่เลือก)');
        }

        $zipBaseName = 'pdf_export_' . preg_replace('/[^A-Za-z0-9_-]+/', '_', (string) $r->department) . '_' . $exportDate . '_' . date('YmdHis');
        $zipFileName = $zipBaseName . '.zip';
        $zipPath = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $zipFileName;

        $zip = new ZipArchive();
        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
            return redirect()->back()->with('error', 'ไม่สามารถสร้างไฟล์ ZIP ได้');
        }

        foreach ($pdfFiles as $filePath) {
            $zip->addFile($filePath, basename($filePath));
        }
        $zip->close();

        return response()->download($zipPath, $zipFileName)->deleteFileAfterSend(true);
    }


    public function temp_pdf($id, $type,$department)
    {
        //มรดกไบร์ท
        $pdfcontroller = new PDFController();
        $r = new Request([
            'id' => $id,
            'type' => "procedure",
            'temp' => 'true',
            'department' => $department
        ]);
    return $pdfcontroller->exportpdf($id,$r);
    }

}
