<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Daily;
use App\Models\DailyPhoto;
use App\Models\User;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class DailyController extends Controller
{   
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $user = Auth::user();
        // 判斷目前登入者的公司主帳號 id (若自己就是主帳號，則用自己的 id)
        $companyId  = $user->belongs_parent ?? $user->id;
        // 抓出同公司所有帳號的 ID (主帳號 + 所有員工)
        $relativeUserId = User::where('id', $companyId)->orWhere('belongs_parent',$companyId)->pluck('id');
        // 抓出這些人建立的所有 Daily 資料
        $result = Daily::with(['photos','user'])->whereIn('creator',$relativeUserId)->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)
    {
        //
        $detailData = json_decode($request->input('details'), true); 
        DB::beginTransaction();
        try {
            //一般資訊
            foreach ($detailData as $key => $data) {
                $daily_id = Daily::create([
                    'remark' => $data['remark'],
                    'creator' => Auth::user()->id,
                ]);
            }

            for ($photoIndex = 0; $photoIndex < 3; $photoIndex++) {
                $photoKey = "photos_{$photoIndex}";
                if ($request->hasFile($photoKey)) {
                    $file = $request->file($photoKey);
                    $path = $file->store("daily_images/D_{$daily_id->id}", 'public');

                    $relativePath = "/storage/" . $path;
                    DailyPhoto::create([
                        'daily_id' => $daily_id->id,
                        'photo_index' => $photoIndex,
                        'file_path' => $relativePath,
                        'creator' => Auth::user()->id,
                    ]);
                }
            }

            DB::commit();
            return response()->json(['message' => '資料儲存成功']);
        } catch (\Throwable $th) {
            DB::rollback();
            throw $th;
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Daily $daily)
    {
        //
    }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Daily $daily)
    {
        //
    }

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