<?php

namespace App\Http\Controllers;

use App\Http\Requests\EventHealthAllowanceCheckRequest;
use App\Http\Requests\EventHealthAllowanceRequest;
use App\Models\EventHealthAllowance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Carbon\Carbon;
use App\Models\EventMetabolism;
use App\Mail\EventNotifyMail;
use App\Models\EventRegistrationInfo;
use Illuminate\Support\Facades\Mail;
use Exception;
use Illuminate\Support\Facades\Cache;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;

class HealthAllowanceFillFormController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request)
    {
        //
    }

    public function index(Request $request)
    {
        $enable = true;
        $eventInfo = Cache::get('event-info-cache-3', function () {
            $entry = EventRegistrationInfo::where('id', 3)->first();
            if ($entry) {
                return ['enable' => $entry->enable,'limit' => $entry->limit, 'start_at' => $entry->event_start_date, 'end_at' => $entry->event_end_date ];
            }
            return null;
        });

        if ($eventInfo) {
            if ($eventInfo['enable'] != "1") {
                $enable = false;
            }
            $date_now = new \DateTime("now");
            $date_start = new \DateTime($eventInfo['start_at']);
            $date_end = new \DateTime($eventInfo['end_at']);

            if ($date_now > $date_start && $date_end > $date_now ) {
                // 
            } else {
                $enable = false;
            }

            $passCount = EventHealthAllowance::where('check_state', 2)->count();
            if ($passCount >= $eventInfo['limit']) {
                $enable = false;
            }
        }

        return view('health_allowance', [
            'enable' => $enable
        ]);
    }

    public function doGet(Request $request)
    {
        return view('health_allowance_fill_form');
    }

    public function doPostOk(Request $request)
    {
        return view('health_allowance_fill_form_ok');
    }

    public function doPost(EventHealthAllowanceRequest $request)
    {
        try 
        {
            $eventInfo = Cache::get('event-info-cache-3', function () {
                $entry = EventRegistrationInfo::where('id', 3)->first();
                if ($entry) {
                    return ['enable' => $entry->enable,'limit' => $entry->limit, 'start_at' => $entry->event_start_date, 'end_at' => $entry->event_end_date ];
                }
                return null;
            });

            if ($eventInfo) {
                if ($eventInfo['enable'] != "1") {
                    throw new \Exception('活動已截止。');
                }
                $date_now = new \DateTime("now");
                $date_start = new \DateTime($eventInfo['start_at']);
                $date_end = new \DateTime($eventInfo['end_at']);

                if ($date_now > $date_start && $date_end > $date_now ) {
                    // 
                } else {
                    throw new \Exception('活動已截止。');
                }

                $passCount = EventHealthAllowance::where('check_state', 2)->count();
                if ($passCount >= $eventInfo['limit']) {
                    throw new \Exception('活動已截止。');
                }
            }

            DB::beginTransaction();
            
            //$checkPhone = EventMetabolism::where('phone', '=', $request->input('phone'))->first();
            //if ($checkPhone) {
            //    throw new \Exception('本電話號碼已經登記。');
            //}
            $twid = Str::upper($request->input('twid'));
            $eventItem = EventHealthAllowance::where('twid', '=', $twid)->first();
            if (!$eventItem) {
                $eventItem = new EventHealthAllowance();
                $eventItem->twid = $twid;
            }
            if ($eventItem->check_state == 1) {
                throw new \Exception('您已經登記審查，請等待審查完成。');
            }
            if ($eventItem->check_state == 2) {
                throw new \Exception('您已經登記審查通過。');
            }
            $eventItem->disease_type = $request->input('disease_type');
            $eventItem->hospital_name = $request->input('hospital_name');
            $eventItem->name = $request->input('name');
            $eventItem->phone = $request->input('phone');
            $eventItem->email = $request->input('email');
            $eventItem->address = $request->input('address');

            $uploadPath = 'uploads/health_allowance';
            $acceptExt = ['jpg', 'jpeg', 'png', 'pdf'];
            $finfo = new \finfo(FILEINFO_MIME_TYPE);
            $allowedMimeTypes = [
                'image/png',      // PNG
                'image/jpeg',     // JPG/JPEG
                'application/pdf' // PDF
            ];
            $manager = new ImageManager(Driver::class);
            $uploadTime = time();
            
            $fileName = $request->input('fileRecordCardFileName');
            if ($fileName && $request->filled('fileRecordCardBase64')) {
                $fileBase64 = $request->input('fileRecordCardBase64');
                $fileData = base64_decode($fileBase64);
                $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
                if (!in_array($fileExt, $acceptExt)) {
                    throw new \Exception('記錄小卡檔案 副檔名錯誤，只接受.jpg/.jpeg/.png/.pdf');
                }
                $mimeType = $finfo->buffer($fileData);
                if (!in_array($mimeType, $allowedMimeTypes)) {
                    throw new \Exception('記錄小卡檔案 檔案類型錯誤，只接受.jpg/.jpeg/.png/.pdf');
                }
                if ($mimeType != 'application/pdf') {
                    $image = $manager->read($fileData);
                    $image->scaleDown(2048, 2048);
                    $fileData = $image->toJpeg(50);
                    $fileExt = 'jpg';
                }
                if ($eventItem->record_card_img_src) {
                    try {
                        Storage::disk('local')->delete($eventItem->record_card_img_src);
                    } catch (\Exception $ex2) {

                    }
                }
                $fileName = $eventItem->twid . "_RecordCard_" . $uploadTime . "." . $fileExt;
                Storage::disk('local')->put($uploadPath. '/' . $fileName, $fileData);
                $eventItem->record_card_img_src = $uploadPath.'/'.$fileName;
            } else {
                throw new \Exception('請上傳記錄小卡。');
            }

            $fileName = $request->input('fileTwidFrontFileName');
            if ($fileName && $request->filled('fileTwidFrontBase64')) {
                $fileBase64 = $request->input('fileTwidFrontBase64');
                $fileData = base64_decode($fileBase64);
                $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
                if (!in_array($fileExt, $acceptExt)) {
                    throw new \Exception('身份證正面檔案 副檔名錯誤，只接受.jpg/.jpeg/.png/.pdf');
                }
                $mimeType = $finfo->buffer($fileData);
                if (!in_array($mimeType, $allowedMimeTypes)) {
                    throw new \Exception('身份證正面檔案 檔案類型錯誤，只接受.jpg/.jpeg/.png/.pdf');
                }
                if ($mimeType != 'application/pdf') {
                    $image = $manager->read($fileData);
                    $image->scaleDown(2048, 2048);
                    $fileData = $image->toJpeg(50);
                    $fileExt = 'jpg';
                }
                if ($eventItem->twid_front_img_src) {
                    try {
                        Storage::disk('local')->delete($eventItem->twid_front_img_src);
                    } catch (\Exception $ex2) {

                    }
                }
                $fileName = $eventItem->twid . "_TwidFront_" . $uploadTime . "." . $fileExt;
                Storage::disk('local')->put($uploadPath. '/' . $fileName, $fileData);
                $eventItem->twid_front_img_src = $uploadPath.'/'.$fileName;
            } else {
                throw new \Exception('請上傳身份證正面。');
            }

            $fileName = $request->input('fileTwidBackFileName');
            if ($fileName && $request->filled('fileTwidBackBase64')) {
                $fileBase64 = $request->input('fileTwidBackBase64');
                $fileData = base64_decode($fileBase64);
                $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
                if (!in_array($fileExt, $acceptExt)) {
                    throw new \Exception('身份證背面檔案 副檔名錯誤，只接受.jpg/.jpeg/.png/.pdf');
                }
                $mimeType = $finfo->buffer($fileData);
                if (!in_array($mimeType, $allowedMimeTypes)) {
                    throw new \Exception('身份證背面檔案 檔案類型錯誤，只接受.jpg/.jpeg/.png/.pdf');
                }
                if ($mimeType != 'application/pdf') {
                    $image = $manager->read($fileData);
                    $image->scaleDown(2048, 2048);
                    $fileData = $image->toJpeg(50);
                    $fileExt = 'jpg';
                }
                if ($eventItem->twid_back_img_src) {
                    try {
                        Storage::disk('local')->delete($eventItem->twid_back_img_src);
                    } catch (\Exception $ex2) {

                    }
                }
                $fileName = $eventItem->twid . "_TwidBack_" . $uploadTime . "." . $fileExt;
                Storage::disk('local')->put($uploadPath. '/' . $fileName, $fileData);
                $eventItem->twid_back_img_src = $uploadPath.'/'.$fileName;
            } else {
                throw new \Exception('請上傳身份證背面。');
            }

            $fileName = $request->input('fileExam1stFileName');
            if ($fileName && $request->filled('fileExam1stBase64')) {
                $fileBase64 = $request->input('fileExam1stBase64');
                $fileData = base64_decode($fileBase64);
                $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
                if (!in_array($fileExt, $acceptExt)) {
                    throw new \Exception('檢驗檢查報告1檔案 副檔名錯誤，只接受.jpg/.jpeg/.png/.pdf');
                }
                $mimeType = $finfo->buffer($fileData);
                if (!in_array($mimeType, $allowedMimeTypes)) {
                    throw new \Exception('檢驗檢查報告1檔案 檔案類型錯誤，只接受.jpg/.jpeg/.png/.pdf');
                }
                if ($mimeType != 'application/pdf') {
                    $image = $manager->read($fileData);
                    $image->scaleDown(2048, 2048);
                    $fileData = $image->toJpeg(50);
                    $fileExt = 'jpg';
                }
                if ($eventItem->exam_1st_img_src) {
                    try {
                        Storage::disk('local')->delete($eventItem->exam_1st_img_src);
                    } catch (\Exception $ex2) {

                    }
                }
                $fileName = $eventItem->twid . "_Exam1st_" . $uploadTime . "." . $fileExt;
                Storage::disk('local')->put($uploadPath. '/' . $fileName, $fileData);
                $eventItem->exam_1st_img_src = $uploadPath.'/'.$fileName;
            } else {
                throw new \Exception('請上傳檢驗檢查報告1。');
            }

            $fileName = $request->input('fileExam2ndFileName');
            if ($fileName && $request->filled('fileExam2ndBase64')) {
                $fileBase64 = $request->input('fileExam2ndBase64');
                $fileData = base64_decode($fileBase64);
                $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
                if (!in_array($fileExt, $acceptExt)) {
                    throw new \Exception('檢驗檢查報告2檔案 副檔名錯誤，只接受.jpg/.jpeg/.png/.pdf');
                }
                $mimeType = $finfo->buffer($fileData);
                if (!in_array($mimeType, $allowedMimeTypes)) {
                    throw new \Exception('檢驗檢查報告2檔案 檔案類型錯誤，只接受.jpg/.jpeg/.png/.pdf');
                }
                if ($mimeType != 'application/pdf') {
                    $image = $manager->read($fileData);
                    $image->scaleDown(2048, 2048);
                    $fileData = $image->toJpeg(50);
                    $fileExt = 'jpg';
                }
                if ($eventItem->exam_2nd_img_src) {
                    try {
                        Storage::disk('local')->delete($eventItem->exam_2nd_img_src);
                    } catch (\Exception $ex2) {

                    }
                }
                $fileName = $eventItem->twid . "_Exam2nd_" . $uploadTime . "." . $fileExt;
                Storage::disk('local')->put($uploadPath. '/' . $fileName, $fileData);
                $eventItem->exam_2nd_img_src = $uploadPath.'/'.$fileName;
            } else {
                throw new \Exception('請上傳檢驗檢查報告2。');
            }

            // $file = $request->file('fileRecordCard');
            // if ($file) {
            //     $fileExt = $file->getClientOriginalExtension();
            //     $fileName = $eventItem->twid . "_RecordCard." . $fileExt;
            //     $path = $file->storeAs($uploadPath, $fileName);
            //     $eventItem->record_card_img_src = $uploadPath.'/'.$fileName;
            // } else {
            //     throw new \Exception('請上傳記錄小卡。');
            // }

            // $file = $request->file('fileTwidFront');
            // if ($file) {
            //     $fileExt = $file->getClientOriginalExtension();
            //     $fileName = $eventItem->twid . "_TwidFront." . $fileExt;
            //     $path = $file->storeAs($uploadPath, $fileName);
            //     $eventItem->twid_front_img_src = $uploadPath.'/'.$fileName;
            // } else {
            //     throw new \Exception('請上傳身份證正面。');
            // }

            // $file = $request->file('fileTwidBack');
            // if ($file) {
            //     $fileExt = $file->getClientOriginalExtension();
            //     $fileName = $eventItem->twid . "_TwidBack." . $fileExt;
            //     $path = $file->storeAs($uploadPath, $fileName);
            //     $eventItem->twid_back_img_src = $uploadPath.'/'.$fileName;
            // } else {
            //     throw new \Exception('請上傳身份證背面。');
            // }

            // $file = $request->file('fileExam1st');
            // if ($file) {
            //     $fileExt = $file->getClientOriginalExtension();
            //     $fileName = $eventItem->twid . "_Exam1st." . $fileExt;
            //     $path = $file->storeAs($uploadPath, $fileName);
            //     $eventItem->exam_1st_img_src = $uploadPath.'/'.$fileName;
            // } else {
            //     throw new \Exception('請上傳檢驗檢查報告1。');
            // }

            // $file = $request->file('fileExam2nd');
            // if ($file) {
            //     $fileExt = $file->getClientOriginalExtension();
            //     $fileName = $eventItem->twid . "_Exam2nd." . $fileExt;
            //     $path = $file->storeAs($uploadPath, $fileName);
            //     $eventItem->exam_2nd_img_src = $uploadPath.'/'.$fileName;
            // } else {
            //     throw new \Exception('請上傳檢驗檢查報告2。');
            // }

            $eventItem->check_state = 1;
            $eventItem->save();

            DB::commit();

            try {
                Mail::to($request->input('email'))->send(new EventNotifyMail(
                    '桃園市政府衛生局114年桃園市健康管理計畫「翻轉代謝新人生，皮蛇疫苗加碼補」登記成功信件',
                    [
                    "title" => "翻轉代謝新人生，皮蛇疫苗加碼補 登記成功！",
                    "body" => "我們將於3個工作天內進行審核您的資料，並通知您審核結果，敬請留意收信。"
                                ."\n\n登記資料："
                                ."\n流水號： C-".str_pad($eventItem->id, 6, '0', STR_PAD_LEFT)
                                ."\n就醫院所：".$request->input('hospital_name')
                                ."\n姓名：".(mb_strlen($request->input('name')) > 2 ? mb_substr($request->input('name'),0,1)."*".mb_substr($request->input('name'),-1) : mb_substr($request->input('name'),0,1)."*")
                                ."\n身份證字號：".substr($request->input('twid'),0,2)."****".substr($request->input('twid'),-4)
                                ."\n電話號碼：".substr($request->input('phone'),0,2)."****".substr($request->input('phone'),-4)
                                ,
                    ]));
                
            } catch (Exception $ex) {

            }
        }
        catch (\Exception $ex) {
            DB::rollBack();
            return redirect()->back()->withErrors([$ex->getMessage()])->withInput(Request()->all());
        }
        //return redirect()->back()->with('success', '登記成功！');
        return view('health_allowance_fill_form_ok');
    }

    public function doCheckGet(Request $request)
    {
        return view('health_allowance_check');
    }

    public function doCheckPost(EventHealthAllowanceCheckRequest $request)
    {
        $rejectReason = '';
        try 
        {
            
            $twid = Str::upper($request->input('twid'));
            $phone = $request->input('phone');
            $eventItem = EventHealthAllowance::where('twid', 'like', '%'.$twid)->where('phone', 'like', '%'.$phone)->first();
            if (!$eventItem) {
                throw new \Exception('找不到您登記的資料，請確認是否資訊正確。');
            }
            if ($eventItem->check_state == 1) {
                throw new \Exception('您已經登記審查，請等待審查完成。');
            }
            if ($eventItem->check_state != 2) {
                $rejectReason = $eventItem->check_reson;
                throw new \Exception('您的審查未通過，請依以下原因說明重新登記。');
            }
            
        }
        catch (\Exception $ex) {
            return redirect()->back()->withErrors([$ex->getMessage(), $rejectReason])->withInput(Request()->all());
        }
        return redirect()->back()->with('success', '您已審格通過！');
    }

    public function doResendNotifyGet(Request $request) 
    {
        $result = [];

        $from = date('2025-06-26 16:43:00');
        $to = date('2025-07-13 11:07:00');
        $entries = EventHealthAllowance::whereBetween('updated_at', [$from, $to])->skip(0)->take(50)->get();

        foreach($entries as $entry)
        {

            try {
                
                switch($entry->check_state) {
                    case '1': //待審
                    
                        Mail::to($entry->email)->send(new EventNotifyMail(
                            '桃園市政府衛生局114年桃園市健康管理計畫「翻轉代謝新人生，皮蛇疫苗加碼補」登記成功信件',
                            [
                            "title" => "翻轉代謝新人生，皮蛇疫苗加碼補 登記成功！",
                            "body" => "我們將於3個工作天內進行審核您的資料，並通知您審核結果，敬請留意收信。"
                                        ."\n\n登記資料："
                                        ."\n流水號： C-".str_pad($entry->id, 6, '0', STR_PAD_LEFT)
                                        ."\n就醫院所：".$entry->hospital_name
                                        ."\n姓名：".(mb_strlen($entry->name) > 2 ? mb_substr($entry->name,0,1)."*".mb_substr($entry->name,-1) : mb_substr($entry->name,0,1)."*")
                                        ."\n身份證字號：".substr($entry->twid,0,2)."****".substr($entry->twid,-4)
                                        ."\n電話號碼：".substr($entry->phone,0,2)."****".substr($entry->phone,-4)
                                        ,
                            ]));
                        
                    
                    break;
                    case '2': //過通
                    
                        Mail::to($entry->email)->send(new EventNotifyMail(
                            '桃園市政府衛生局114年桃園市健康管理計畫「翻轉代謝新人生，皮蛇疫苗加碼補」審核通過信件。',
                            [
                                "title" => "翻轉代謝新人生，皮蛇疫苗加碼補 審核通過！",
                                "body" => "一、登記資料："
                                        ."\n流水號： C-".str_pad($entry->id, 6, '0', STR_PAD_LEFT)
                                        ."\n就醫院所：".$entry->hospital_name
                                        ."\n姓名：".(mb_strlen($entry->name) > 2 ? mb_substr($entry->name,0,1)."*".mb_substr($entry->name,-1) : mb_substr($entry->name,0,1)."*")
                                        ."\n身份證字號：".substr($entry->twid,0,2)."****".substr($entry->twid,-4)
                                        ."\n電話號碼：".substr($entry->phone,0,2)."****".substr($entry->phone,-4)
                                        ."\n\n二、補助通知："
                                        ."\n感謝您參與「114年桃園市健康管理計畫－翻轉代謝新人生 皮蛇疫苗加碼補」。"
                                        ."\n請至本局指定醫療院所完成疫苗接種，並備妥以下資料申請經費補助："
                                        ."\n1.活動審核通過通知信"
                                        ."\n2.帶狀皰疹疫苗接種收據或紀錄"
                                        ."\n3.本人帳戶影本（如非臺灣銀行帳戶，將扣除30元匯費）"
                                        ."\n4.切結書"
                                        ."\n\n三、為確保資源分配公平，提醒您「翻轉代謝新人生 皮蛇疫苗加碼補」活動與「114年桃園市帶狀疱疹疫苗接種補助計畫」不可重複申請，應擇一參加。如經查證您已參加「114年桃園市帶狀疱疹疫苗接種補助計畫」，本活動所接受之經費補助將不予補助，並需退還已補助之費用5,000元。"
                                        ."\n\n四、備妥以上資料於114年12月5日前以掛號方式寄至桃園市政府衛生局健康促進科（桃園市桃園區縣府路55號），信封註明114年桃園市健康管理計畫帶狀疱疹疫苗補助。"
                                        ."\n\n敬請配合，以利後續作業。"
                                        ,
                            ]));
                        
                    
                    break;
                    case '3': //未通過
                    
                        Mail::to($entry->email)->send(new EventNotifyMail(
                            '桃園市政府衛生局114年桃園市健康管理計畫「翻轉代謝新人生，皮蛇疫苗加碼補」審核未通過信件。',
                            [
                                "title" => "翻轉代謝新人生，皮蛇疫苗加碼補 審核未通過！",
                                "body" => "抱歉，您的審核未通過！請依以下理由重新上活動網站登記。"
                                        ."\n理由：".$entry->check_reson
                                        ."\n\n登記資料："
                                        ."\n流水號： C-".str_pad($entry->id, 6, '0', STR_PAD_LEFT)
                                        ."\n就醫院所：".$entry->hospital_name
                                        ."\n姓名：".(mb_strlen($entry->name) > 2 ? mb_substr($entry->name,0,1)."*".mb_substr($entry->name,-1) : mb_substr($entry->name,0,1)."*")
                                        ."\n身份證字號：".substr($entry->twid,0,2)."****".substr($entry->twid,-4)
                                        ."\n電話號碼：".substr($entry->phone,0,2)."****".substr($entry->phone,-4)
                                        ,
                            ]));
                    
                    break;
                }
                

                $entry->updated_at = \Carbon\Carbon::now();
                $entry->save();

                $result[] = ['id' => $entry->id, 'email' => $entry->email, 'state' => $entry->check_state, 'reason' => $entry->check_reson];
            } catch (Exception $ex) {
                $result[] = ['id' => $entry->id, 'email' => $entry->email, 'state' => $entry->check_state, 'reason' => $entry->check_reson, 'err' => $ex->getMessage()];
            }
        }

        
        return $result;
    }
}
