<?php

namespace App\Services;

use App\Models\InvSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class InvSettingService
{
    /**
     * 郵便番号・電話番号・FAX番号整形
     */
    public function buildContactData(Request $request): array
    {
        return [
            'zipcode' => "{$request->zip1}-{$request->zip2}",
            'tel_num' => implode('-', array_filter([$request->tel1, $request->tel2, $request->tel3])),
            'fax_num' => implode('-', array_filter([$request->fax1, $request->fax2, $request->fax3])),
        ];
    }

    /**
     * 新規登録処理
     */
    public function create(Request $request): void
    {
        $data = array_merge(
            $request->only(['management_id', 't_number', 't_name', 'adrs', 'bldg']),
            $this->buildContactData($request)
        );

        if ($request->hasFile('company_image')) {
            $data['company_image_path'] = $request->file('company_image')->store('inv', 'public');
        }

        InvSetting::create($data);
    }

    /**
     * 更新処理
     */
    public function update(Request $request, InvSetting $record): void
    {
        $data = array_merge(
            $request->only(['management_id', 't_number', 't_name', 'adrs', 'bldg']),
            $this->buildContactData($request)
        );

        if ($request->hasFile('company_image')) {
            if ($record->company_image_path) {
                Storage::disk('public')->delete($record->company_image_path);
            }
            $data['company_image_path'] = $request->file('company_image')->store('inv', 'public');
        }

        $record->update($data);
    }

    /**
     * 削除処理（複数対応）
     */
    public function delete(array $ids): void
    {
        $records = InvSetting::whereIn('seq', $ids)->get();

        foreach ($records as $record) {
            if ($record->company_image_path) {
                Storage::disk('public')->delete($record->company_image_path);
            }
            $record->delete();
        }
    }
}
