<?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 Carbon\Carbon;

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

class DownloadController extends Controller
{
    public function allDate (Request $request) {
        if (!$user = $request->user()) {
            return response()->json(['error' => "Unauthorized: token is not existed."], 401);
        }
        // TODO 建議把日期區間做過濾，重覆日期不需要顯示，進而達到優化效果！

        $checks = CheckList::where('state','!=',0)
            ->whereNull('finish_user_id')
            ->where(function($query) {
                $userId = Auth::user()->id;
                $query->where('checker_id',$userId)
                    ->orWhere('creator',$userId);
            })
            ->select('startdate','enddate')
            ->get();
        
        $currentYear = date('Y');
        $allDate = $checks->filter(function ($check) use ($currentYear) {
                                $startYear = (new \DateTime($check['startdate']))->format('Y');
                                $endYear = (new \DateTime($check['enddate']))->format('Y');
                                return $startYear == $currentYear && $endYear == $currentYear;
                            })->map(function ($check) {
                                return [
                                    'start_date' => $check['startdate'],
                                    'end_date' => $check['enddate'],
                                ];
                            })->unique(function ($item) {
                                return $item['start_date'].$item['end_date'];
                            })->values();

        return response()->json(['data' => $allDate], 200);
    }

    // 抓取 startDate <= $date <= endDate 之間 且 狀態不為*已查核*的巡檢單
    public function getList(Request $request , $date){
        if (!$user = $request->user()) {
            return response()->json(['error' => "Unauthorized: token is not existed."], 401);
        }

        $cycleMap = [
            'daily'  => '日',
            'week'   => '週',
            'month'  => '月',
            'season' => '季',
            'year'   => '年',
        ];

        $user = Auth::user();

        $result = CheckList::with(['equipment.category','equipment.factory'])
                    ->whereDate('startdate', '<=', $date)
                    ->whereDate('enddate', '>=', $date)
                    ->where(function($query) use($user) {
                        $query->where('checker_id', $user->id)
                            ->orWhere('creator', $user->id);
                    })
                   ->where('state', '!=' , 0)
                   ->orderBy('id', 'ASC')
                   ->get();
                
        $data = $result->map(function($item) use($user, $cycleMap) {
            return [
                'id' => $item->id,
                'equipment_name' => $item->equipment->name,
                'category_name'  => $item->equipment->category->name,
                'factory_name'   => $item->equipment->factory->name,
                'department' => $item->equipment->department ?? "",
                'cycle' => $cycleMap[$item->cycle] ?? $item->cycle,
                'start_date' => $item->startdate->format('Y-m-d'),
                'end_date' => $item->enddate->format('Y-m-d'),
                'checker_id' => $user->id,
                'checker_name' => $user->name,
            ];
        });

        return response()->json(['data' => $data], 200);
    }
    
    public function getDetail(Request $request , $check_id){
        try {
            $result = CheckBankDetail::with('photos')->where('check_id', $check_id)->orderBy('id')->get();

            $riskList = ['', '進階改善', '優先改善', '立即改善'];

            $data = $result->map(function($item) use($riskList) {
                return [
                    'id' => $item->id,
                    'item' => $item->item,
                    'range' => isset($item->range) ? (double)$item->range : null,
                    'range2' => isset($item->range2) ? (double)$item->range2 : null,
                    'unit' => $item->unit,
                    'remark' => $item->remark,
                    'risk' => $riskList[$item->risk],
                    'option_state' => $item->option_state,
                    'option_input' => $item->option_input,
                    // 'photos' => $item->photos, // 這裡會保留所有圖片
                    'photos' => collect($item->photos)->map(function ($photo) {
                        return $photo->file_path;
                    })->toArray(),
                ];
            });

            return response()->json(['data' => $data] , 200);
        } catch (\Throwable $th) {
            throw $th;
        }
    }
}