<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\NewUserSummaryService;
use App\Services\OnlineUserService;
use Exception;
use Illuminate\Validation\ValidationException;

class Online extends Controller
{
    /**
     * 在线用户列表
     */
    public function users()
    {
        try {
            $params = request()->validate([
                'page' => ['nullable', 'integer', 'min:1'],
                'limit' => ['nullable', 'integer', 'min:1', 'max:200'],
                'member_id' => ['nullable', 'string'],
                'first_name' => ['nullable', 'string'],
                'login_ip' => ['nullable', 'string'],
                'platform' => ['nullable', 'string'],
            ]);
            $result = OnlineUserService::list($params);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success($result);
    }

    /**
     * 新用户汇总（按天）
     */
    public function newUserSummary()
    {
        try {
            $params = request()->validate([
                'start_time' => ['nullable', 'date', 'date_format:Y-m-d'],
                'end_time' => ['nullable', 'date', 'date_format:Y-m-d', 'after_or_equal:start_time'],
            ]);
            $endDate = $params['end_time'] ?? date('Y-m-d');
            $startDate = $params['start_time'] ?? date('Y-m-d', strtotime($endDate . ' -6 days'));
            $result = NewUserSummaryService::summarize($startDate, $endDate);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success($result);
    }

    /**
     * 在线用户按端计数：苹果 APP / 安卓 APP / PC / 手机 H5
     * 唯一在线人数接口（勿挂到 paymentOrder/unProcessed）
     */
    public function platformCount()
    {
        try {
            $result = OnlineUserService::platformCounts();
        } catch (Exception $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->getMessage());
        }
        return $this->success($result);
    }
}
