<?php

namespace App\Http\Controllers;

use App\Models\BasicSettings;
use App\Models\MongoDB\Project;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    //
    public function index(Request $request)
    {
        return response(Project::all());
    }

    public function show(Request $request)  // 傳入$_id參數
    {
        $_id = $request->input('project_number');
        $pmis_project = $this->getProject($_id);
        if ($pmis_project) {
            return response()->json($pmis_project);  // 如果項目存在，返回JSON格式的項目
        } else {
            return response()->json(['message' => 'Project not found'], 404);  // 如果找不到項目，返回404錯誤
        }
    }

    static public function getProject($id)
    {
        $pmis_project = Project::where('_id', $id)->first(['name', 'no', 'expectedBeginAt', 'work_duration']);  // 使用first()來取得單一紀錄
        if ($pmis_project) {
            $pmis_project->work_duration = $pmis_project->work_duration ?? 1000;  // 如果 work_duration 是 null，設定預設值為 1000
            $beginAt = json_decode($pmis_project->expectedBeginAt);
            $timestampInSeconds = $beginAt / 1000;
            $expectedBeginDate = date("Y-m-d", $timestampInSeconds);
            $pmis_project->expectedBeginAt = $expectedBeginDate;
            return $pmis_project;
        }

        return null;  // 如果找不到項目，返回 null
    }
}
