<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\DispatchSet;
use App\Models\BankList;
use App\Models\BankDetail;
use App\Models\User;
use App\Models\CheckList;
use App\Models\CheckBankDetail;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;


function calculateNextDate(Carbon $start, string $cycle): Carbon
{
    return match ($cycle) {
        'daily'   => $start->copy()->addDay(),
        'week'    => $start->copy()->addWeek(),
        'month'   => $start->copy()->addMonthNoOverflow(),
        'season'  => $start->copy()->addMonthsNoOverflow(3),
        'year'    => $start->copy()->addYearNoOverflow(),
        default   => throw new Exception("無效的週期類型：{$cycle}"),
    };
}

class DispatchSetController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $result = DispatchSet::with(['banklist.equipment.category' , 'banklist.equipment.factory', 'checker'])->where("creator", Auth::user()->id)->get();
        return response()->json(['data' => $result ], 200);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $bank_id = $request->bank_id;
            $checker_id = $request->checker_id;
            $cycle = $request->cycle;
            $startdate = Carbon::parse($request->startdate);
            $nextdate = calculateNextDate($startdate, $cycle);
            $eq_id = BankList::with('equipment')->where('id' , $bank_id)->value('eq_id');

            // 新增(紀錄)派工單
            DispatchSet::create([
                'bank_id' => $bank_id,
                'startdate' => $startdate,
                'nextdate' => $nextdate, // 將下一次巡檢日期存入
                'cycle' => $cycle,
                'state' => 1,
                'checker_id' => $checker_id,
                'creator' => Auth::user()->id,
                'created_at' => now(),
            ]);

            // 將派工單的資訊寫入checkList
            $checkList = CheckList::create([ 
                'checker_id' => $checker_id,
                'eq_id' => $eq_id,
                'startdate' => $startdate,
                'enddate' => $nextdate,
                'cycle' => $cycle,
                'state' => 1,
                'finish_user_id' => null,
                'creator' => Auth::user()->id,
            ]);

            // 檢查項目資料
            $bankData = BankDetail::where('bank_id',$bank_id)->get();
            foreach ($bankData as $data) {
                CheckBankDetail::create([
                    'check_id' => $checkList->id,
                    'code' => $data->code,
                    'item' => $data->item,
                    'range' => $data->range,
                    'range2' => $data->range2,
                    'unit' => $data->unit,
                    'remark' => $data->remark,
                    'risk' => $data->risk,
                ]);     
            }
                                                                                
            
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(DispatchSet $dispatchSet)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(DispatchSet $dispatchSet)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
        DB::beginTransaction();
        try {
            $dispatch = DispatchSet::findOrFail($id);
            $dispatch->update([
                'cycle' => $request->cycle,
                'checker_id' => $request->checker_id,
                'state' => $request->state,
            ]);
            DB::commit();
            return response()->json(['data' => '修改成功'],200);
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(DispatchSet $dispatchSet)
    {
        //
    }

    //讀取上表格資料 (檢核表單 、 巡檢人員)
    public function getForm()
    {
        //後續再補巡檢人員名單
        $bank = BankList::with('equipment.category')->where('creator',Auth::user()->id)->get();
        $user = User::where('role','checker')->where('belongs_parent',Auth::user()->id)->get();
        return response()->json(['bankData' => $bank , 'userData' => $user], 200);
    }
    //讀取檢核表單底下的檢核項目資料
    public function getDispatch(Request $request)
    {
        $bankId = $request->query('dispatchId');
        $data = BankDetail::where('bank_id',$bankId)->where('creator',Auth::user()->id)->whereNull('deleted_at')->orderBy('id')->get();
        return response()->json(['data' => $data], 200);
    }
    
    public function getData(Request $request)
    {
        $id = $request->query('dispatchId');
        $data = DispatchSet::where('id', $id)->get();
        return response()->json(['data' => $data], 200);
    }
}