<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Park;
use App\Models\PriceA;
use App\Models\PriceB;

class PriceListController extends Controller
{
    /**
     * 料金一覧表 一覧ページ
     */
    public function list(Request $request)
    {
        $parkList = Park::orderBy('park_name')->get();
        $parkId = $request->input('park_id', '');

        $masterList = [
            [
                'name' => 'マスターA',
                'status' => '利用中',
                'groups' => [],
            ],
            [
                'name' => 'マスターB',
                'status' => '待作中',
                'groups' => [],
            ],
        ];

        if ($parkId) {
            // price_a に必要なマスタを JOIN
            $aRows = \DB::table('price_a')
                ->join('park', 'park.park_id', '=', 'price_a.park_id')
                ->leftJoin('ptype', 'price_a.ptype_id', '=', 'ptype.ptype_id')
                ->leftJoin('usertype', 'price_a.user_categoryid', '=', 'usertype.user_categoryid')
                ->leftJoin('pplace', 'price_a.pplace_id', '=', 'pplace.pplace_id')
                ->where('price_a.park_id', $parkId)
                ->select([
                    'price_a.*',
                    'ptype.ptype_subject',
                    'usertype.usertype_subject1',
                    'usertype.usertype_subject2',
                    'usertype.usertype_subject3',
                    'pplace.pplace_number'
                ])
                ->get();

            $aGrouped = $this->groupPriceRows($aRows);
            $masterList[0]['groups'] = $aGrouped;

            // マスターBも同様に取得・整形する場合はここに追加
        }

        return view('admin.PriceList.list', [
            'parkList' => $parkList,
            'parkId' => $parkId,
            'masterList' => $masterList,
        ]);
    }

    /**
     * 料金データを「駐輪分類ID-ユーザ分類ID-駐輪場ID」でグループ化
     */
    private function groupPriceRows($rows)
    {
        $result = [];
        foreach ($rows as $row) {
            // グループキーは分類ID+ユーザ分類ID+駐輪場ID
            $key = $row->ptype_id . '-' . $row->user_categoryid . '-' . $row->park_id;

            if (!isset($result[$key])) {
                $result[$key] = [
                    'id' => $row->price_parkplaceid,
                    'classification' => $row->ptype_subject ?? '',
                    'room_number' => $row->pplace_number ?? '',
                    'category1' => $row->usertype_subject1 ?? '',
                    'category2' => $row->usertype_subject2 ?? '',
                    'category3' => $row->usertype_subject3 ?? '',
                    'bike_1m' => '', 'bike_2m' => '', 'bike_3m' => '', 'bike_6m' => '', 'bike_12m' => '',
                    'moped_1m' => '', 'moped_2m' => '', 'moped_3m' => '', 'moped_6m' => '', 'moped_12m' => '',
                    'motorcycle_1m' => '', 'motorcycle_2m' => '', 'motorcycle_3m' => '', 'motorcycle_6m' => '', 'motorcycle_12m' => '',
                    'car_1m' => '', 'car_2m' => '', 'car_3m' => '', 'car_6m' => '', 'car_12m' => '',
                ];
            }

            $month = $row->price_month;
            $price = $row->price;
            switch ($row->psection_id) {
                case 1:
                    $result[$key]["bike_{$month}m"] = $price;
                    break;
                case 2:
                    $result[$key]["moped_{$month}m"] = $price;
                    break;
                case 3:
                    $result[$key]["motorcycle_{$month}m"] = $price;
                    break;
                case 4:
                    $result[$key]["car_{$month}m"] = $price;
                    break;
            }
        }
        return array_values($result);
    }

public function update(Request $request)
{
    foreach ($request->input('rows', []) as $row) {
        $id = $row['id'] ?? null;
        if (!$id) continue;

        $vehicleTypes = [
            'bike' => 1,
            'moped' => 2,
            'motorcycle' => 3,
            'car' => 4,
        ];

        $months = [1, 2, 3, 6, 12];

        foreach ($vehicleTypes as $prefix => $psectionId) {
            foreach ($months as $month) {
                $field = "{$prefix}_{$month}m";
                if (isset($row[$field])) {
                    $value = $row[$field];

                    // バリデーション：空欄はスキップ
                    if (!ctype_digit((string)$value)) {
                        return back()->withErrors([
                            "{$field}" => "金額は整数で入力してください。"
                        ]);
                    }

                    //  バリデーション：最大値を超えないこと
                    if ((int)$value > 9999999999) {
                        return back()->withErrors([
                            "{$field}" => "金額は最大 9,999,999,999 までです。"
                        ]);
                    }

                    $item = PriceA::where('price_parkplaceid', $id)
                        ->where('price_month', $month)
                        ->where('psection_id', $psectionId)
                        ->first();
                    if ($item) {
                        $item->price = $value;
                        $item->save();
                    }
                }
            }
        }
    }
    return back()->with('success', '金額を更新しました');
}

    public function insert(Request $request)
    {
        if ($request->filled('bike_2m')) {
            $row = new PriceA();
            $row->park_id = $request->input('park_id');
            $row->price = $request->input('bike_2m');
            $row->price_month = 2;
            $row->psection_id = 1; // 自転車
            $row->save();
        }
        return back()->with('success', '金額を追加しました');
    }
}