<?php

namespace App\Http\Controllers\Api\App;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Passport\Client;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Models\User;
use Exception;

use App\Models\CheckList;
use App\Models\CheckBankDetail;
use App\Models\CheckPhoto;

class UploadController extends Controller
{
    public function checkState(Request $request , $check_id){
        $checkList = CheckList::where('id', $check_id)->first();
        if(!$checkList){
            return response()->json(['state' => 4 , 'message' => '查無此巡檢單，無法上傳'], 200);    
        }
        
        $stats = $checkList->state;
        if($stats == 0){
            return response()->json(['state' => 0 , 'message' => '巡檢單於網頁中已提交，無法上傳'], 200);    
        }else if ($stats == 2){
            return response()->json(['state' => 2 , 'message' => '巡檢單於網頁中已有草稿，是否需要覆蓋？'], 200);    
        }
        return response()->json(['state' => 1 , 'message' => '無紀錄，可正常上傳'], 200);    
    }

    public function newUpload(Request $request , $checkId)
    {
        $appData = json_decode($request->data);

        DB::beginTransaction();
        try {
            $state = CheckList::where('id',$checkId)->value('state');

            if($state == 0){
                return response()->json(['message' => '巡檢單於網頁中已提交，無法上傳'], 200);
            }
            
            //List表，只需更改狀態即可
            $checkList = CheckList::findOrFail($checkId);
            $checkList->update([
                'state' => 2,
            ]);

            foreach ($appData->data as $data) {
                /*
                    上傳的資料如果
                        未處理option_state及option_input，則在這支API做處理，處理方法如下
                        於App有處理，下段程式碼則不需要，直接對detail表update即可
                */
                $result = null;
                if(is_numeric($data->option_input)){
                    //目前僅處理，有數值且有輸入的情況下，針對state做處理
                    if($data->range && $data->range2){
                        $result = ($data->option_input >= $data->range && $data->option_input <= $data->range2) ? 1 : 0;
                    }else if ($data->range){
                        $result = ($data->option_input > $data->range) ? 1 : 0;
                    }else if ($data->range2){
                        $result = ($data->option_input < $data->range2) ? 1 : 0;
                    }
                    $data->option_state = $result;
                }

                $checkDetail = CheckBankDetail::findOrFail($data->id);
                $checkDetail->update([
                    'remark' => $data->remark,
                    'option_state' => $data->option_state,
                    'option_input' => $data->option_input,
                ]);
            }
            DB::commit();
			return response()->json(['message' => '上傳成功'], 200);
        } catch (\Throwable $th) {
			//throw $th;
			Log::info($th);
			DB::rollback();
			return response()->json(['message' => '上傳失敗'], 500);
        }
    }

    public function uploadimg(Request $request , $checkId , $detailId)
    {
        // Log::info($request);
        // 頻寬(圖片張數大小過大)/流量(圖片張數過多)問題待後續處理
        $FilePaths = [];
        DB::beginTransaction();
        try {
            /*
              1. 抓出資料庫 DetailId 做刪除
              2. 收集所有要刪除的圖片檔案路徑
              3. 儲存新圖片
              4. 確保只有在資料庫成功提交後，才刪除 storage 中的舊圖
            */
            $PhotoData = CheckPhoto::where('check_detail_id', $detailId)->delete();
            $FilePaths = $PhotoData->pluck('file_path')->toArray();

            $state = CheckList::where('id',$checkId)->value('state');
            if($state == 0){
                //若在網頁中，該稽核單已被提交，避免重複上傳圖片的問題
                return response()->json(['message' => '巡檢單於網頁中已提交，無法上傳'], 200);
            }
            
            $files = $request->allFiles();
            foreach($files as $key => $file)
            {
                $parts = explode('_' , $key);
                if (count($parts) !== 3) continue;
                $detailId = $parts[1];
                $photoIndex = $parts[2];

                $path = $file->store("check_images/C{$checkId}/D{$detailId}", 'public');
                $relativePath = "/storage/" . $path;
                CheckPhoto::create([
                    'check_detail_id' => $detailId,
                    'photo_index' => $photoIndex,
                    'file_path' => $relativePath,
                ]);
            }
            DB::commit();
            $dbSuccess = true;
			// return response()->json(['message' => '上傳圖片成功'], 200);
        } catch (\Throwable $th) {
			//throw $th;
            Log::info($th);
			DB::rollback();
            $dbSuccess = false;
			// return response()->json(['message' => $th], 500);
        }
        if($dbSuccess && !empty($FilePaths)) {
            foreach ($FilePaths as $path) {
                $realPath = public_path($path);
                if(file_exists($realPath)) {
                    unlink($realPath);
                }
            }
        }
        return response()->json(['message' => $dbSuccess ? '上傳圖片成功' : '資料庫儲存失敗'], $dbSuccess ? 200 : 500);
    }
}