<?php

namespace App\Http\Controllers;

use App\Http\Requests\EventImprovedHealthCheckRequest;
use App\Http\Requests\EventImprovedHealthRequest;
use App\Models\EventImprovedHealth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Carbon\Carbon;
use App\Mail\EventNotifyMail;
use Illuminate\Support\Facades\Mail;
use App\Models\EventMetabolism;
use App\Models\EventRegistrationInfo;

use Exception;
use Illuminate\Support\Facades\Cache;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;

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

    public function index(Request $request)
    {
        $enable = true;
        $eventInfo = Cache::get('event-info-cache-2', function () {
            $entry = EventRegistrationInfo::where('id', 2)->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 = EventImprovedHealth::where('check_state', 2)->count();
            if ($passCount >= $eventInfo['limit']) {
                $enable = false;
            }
        }

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

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

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

    public function doPost(EventImprovedHealthRequest $request)
    {
        try 
        {
            $eventInfo = Cache::get('event-info-cache-2', function () {
                $entry = EventRegistrationInfo::where('id', 2)->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 = EventImprovedHealth::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 = EventImprovedHealth::where('twid', '=', $twid)->first();
            if (!$eventItem) {
                $eventItem = new EventImprovedHealth();
                $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/improved_health';
            $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('fileExamFileName');
            if ($fileName && $request->filled('fileExamBase64')) {
                $fileBase64 = $request->input('fileExamBase64');
                $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->exam_img_src) {
                    try {
                        Storage::disk('local')->delete($eventItem->exam_img_src);
                    } catch (\Exception $ex2) {

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

            $fileName = $request->input('fileExam2FileName');
            if ($fileName && $request->filled('fileExam2Base64')) {
                $fileBase64 = $request->input('fileExam2Base64');
                $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->exam2_img_src) {
                    try {
                        Storage::disk('local')->delete($eventItem->exam2_img_src);
                    } catch (\Exception $ex2) {

                    }
                }
                $fileName = $eventItem->twid . "_Exam2_" . $uploadTime . "." . $fileExt;
                Storage::disk('local')->put($uploadPath. '/' . $fileName, $fileData);
                $eventItem->exam2_img_src = $uploadPath.'/'.$fileName;
            }

            // $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('fileExam');
            // if ($file) {
            //     $fileExt = $file->getClientOriginalExtension();
            //     $fileName = $eventItem->twid . "_Exam." . $fileExt;
            //     $path = $file->storeAs($uploadPath, $fileName);
            //     $eventItem->exam_img_src = $uploadPath.'/'.$fileName;
            // } else {
            //     throw new \Exception('請上傳檢查報告。');
            // }

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

            DB::commit();

            try {
                
                Mail::to($request->input('email'))->send(new EventNotifyMail(
                    '桃園市政府衛生局114年桃園市健康管理計畫「健康達標GO，大獎汽車不是夢」登記成功信件',
                    [
                    "title" => "健康達標GO，大獎汽車不是夢 登記成功！",
                    "body" => "我們將於3個工作天內進行審核您的資料，並通知您審核結果，敬請留意收信。"
                                ."\n\n登記資料："
                                ."\n流水號： B-".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('improved_health_fill_form_ok');
    }

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

    public function doCheckPost(EventImprovedHealthCheckRequest $request)
    {
        $rejectReason = '';
        try 
        {
            
            $twid = Str::upper($request->input('twid'));
            $phone = $request->input('phone');
            $eventItem = EventImprovedHealth::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 = EventImprovedHealth::whereBetween('updated_at', [$from, $to])->skip(0)->take(40)->get();

        foreach($entries as $entry)
        {

            try {
                
                switch($entry->check_state) {
                    case '1': //待審
                    
                        Mail::to($entry->email)->send(new EventNotifyMail(
                            '桃園市政府衛生局114年桃園市健康管理計畫「健康達標GO，大獎汽車不是夢」登記成功信件',
                            [
                            "title" => "健康達標GO，大獎汽車不是夢 登記成功！",
                            "body" => "我們將於3個工作天內進行審核您的資料，並通知您審核結果，敬請留意收信。"
                                        ."\n\n登記資料："
                                        ."\n流水號： B-".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年桃園市健康管理計畫「健康達標GO，大獎汽車不是夢」審核通過信件。',
                            [
                                "title" => "健康達標GO，大獎汽車不是夢 審核通過！",
                                "body" => "登記資料："
                                        ."\n流水號： B-".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本活動將於10月抽出得獎名單並公告於「<a href=\"". route('news') ."\" target=\"_blank\">活動網站/最新消息</a>」及「<a href=\"https://dph.tycg.gov.tw/News.aspx?n=4219&sms=10121\" target=\"_blank\">桃園市政府衛生局網站/訊息公告/最新消息</a>」。"
                                        ,
                            ]));
                        
                    
                    break;
                    case '3': //未通過
                    
                        Mail::to($entry->email)->send(new EventNotifyMail(
                            '桃園市政府衛生局114年桃園市健康管理計畫「健康達標GO，大獎汽車不是夢」審核未通過信件。',
                            [
                                "title" => "健康達標GO，大獎汽車不是夢 審核未通過！",
                                "body" => "抱歉，您的審核未通過！請依以下理由重新上活動網站登記。"
                                        ."\n理由：".$entry->check_reson
                                        ."\n\n登記資料："
                                        ."\n流水號： B-".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;
    }
}
