<?php

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Controller;
use App\Models\Store;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class StoreController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Store::with('region');

        if ($request->keyword) {
            $query->where('name', 'like', "%{$request->keyword}%");
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $stores = $query->orderByDesc('id')
            ->paginate($request->input('page_size', 20));

        return $this->paginate($stores);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'region_id' => 'nullable|exists:regions,id',
            'name' => 'required|string|max:100',
            'code' => 'nullable|string|max:20|unique:stores,code',
            'address' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'contact' => 'nullable|string|max:50',
            'capacity' => 'nullable|integer|min:0|max:9999',
            'description' => 'nullable|string|max:500',
            'status' => 'in:0,1',
        ]);

        // capacity 列有 NOT NULL + default(0)，空值时用默认值
        $data['capacity'] = $data['capacity'] ?? 0;

        $store = Store::create($data);
        return $this->success($store, '创建成功');
    }

    public function show(Store $store): JsonResponse
    {
        $store->load('region');
        return $this->success($store);
    }

    public function update(Request $request, Store $store): JsonResponse
    {
        $data = $request->validate([
            'region_id' => 'nullable|exists:regions,id',
            'name' => 'string|max:100',
            'code' => 'nullable|string|max:20|unique:stores,code,' . $store->id,
            'address' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'contact' => 'nullable|string|max:50',
            'capacity' => 'nullable|integer|min:0|max:9999',
            'description' => 'nullable|string|max:500',
            'status' => 'in:0,1',
        ]);

        if (array_key_exists('capacity', $data) && $data['capacity'] === null) {
            $data['capacity'] = 0;
        }

        $store->update($data);
        return $this->success($store, '更新成功');
    }

    public function destroy(Store $store): JsonResponse
    {
        if ($store->users()->exists()) {
            return $this->error('该门店下还有员工，无法删除');
        }
        $store->delete();
        return $this->success(null, '删除成功');
    }

    /**
     * 公开门店列表（注册页用，仅返回启用门店的 id/name）
     */
    public function publicList(): JsonResponse
    {
        $stores = Store::withoutGlobalScope('store')
            ->where('status', 1)
            ->orderByDesc('id')
            ->get(['id', 'name']);
        return $this->success($stores);
    }
}
