<?php

namespace App\Services\Client;

use App\Models\CoachUser;
use App\Models\MemberUser;
use Illuminate\Support\Facades\Auth;

class CoachService
{
    /**
     * 获取技师列表
     */
    public function getCoachList($latitude, $longitude)
    {
        // 获取当前用户
        $user = Auth::user();

        // 检查用户状态
        if ($user->state !== 'enable') {
            throw new \Exception('用户状态异常');
        }

        // 获取附近的技师
        $coaches = CoachUser::query()
            ->where('state', 'enable')
            ->whereHas('info', function ($query) {
                $query->where('state', 'approved');
            })
            ->whereHas('real', function ($query) {
                $query->where('state', 'approved');
            })
            ->whereHas('qual', function ($query) {
                $query->where('state', 'approved');
            })
            ->with(['info:id,nickname,avatar,gender'])
            ->with(['locations'])
            ->whereHas('locations', function ($query) use ($latitude, $longitude) {
                $query->where('state', 'enable')
                    ->whereRaw(
                        '(6371 * acos(cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + sin(radians(?)) * sin(radians(latitude)))) < ?',
                        [$latitude, $longitude, $latitude, 40]
                    );
            })
            ->selectRaw(
                '*, (6371 * acos(cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + sin(radians(?)) * sin(radians(latitude)))) as distance',
                [$latitude, $longitude, $latitude]
            )
            ->paginate(10);

        return $coaches;
    }

    /**
     * 获取技师详情
     */
    public function getCoachDetail($coachId, $latitude, $longitude)
    {
        // 获取当前用户
        $userId = Auth::id();
        $user = MemberUser::findOrFail($userId);

        // 检查用户状态
        if ($user->state !== 'enable') {
            throw new \Exception('用户状态异常');
        }

        // 获取技师信息
        $coach = CoachUser::where('id', $coachId)
            ->where('state', 'enable')
            ->where('auth_state', 'passed')
            ->with(['user:id,nickname,avatar,gender'])
            ->with(['location'])
            ->firstOrFail();

        // TODO: 计算距离
        $distance = 0;
        if ($coach->location) {
            // 实现距离计算逻辑
        }

        $coach->distance = $distance;

        return $coach;
    }
}
