<?php
/**
 * Created by PhpStorm
 * DateTime: 2022/10/2 13:32
 *
 * @description
 */

namespace App\Http\Controllers\V1;

use App\Models\Product;
use App\Models\StatProduct;
use App\Models\StatProductDownload;
use Dingo\Api\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;

class ProductController extends Controller
{
    public function search(Request $request): JsonResponse
    {
        $limit = $request->input('limit');
        $keywords = $request->input('keywords', '');
        $page = request()->input('page',1);
        $offset = ($page - 1) * $limit;


        $lists = Product::withCount(['viewer'])->where('is_opened', 1)
            ->when($keywords, function ($query, $keywords) {
                /* @var Builder  $query*/
                return $query->where('name','like', "%$keywords%");
            })
            ->orderByDesc('viewer_count')
            ->orderByDesc('sort')
            ->limit($limit)
            ->offset($offset)
            ->get();

        return $this->success($lists);
    }

    public function detail($id): JsonResponse
    {
        $info = Product::with(['specs' => function($query) {
            $query->select(['id','product_id','name','specs'])
                ->where('is_opened', 1)
                ->orderByDesc('sort');
        }])
            ->where('id',$id)
            ->first();
        $info->files = $info;

        return $this->success($info);
    }

    public function viewer($id): JsonResponse
    {
        $stat = new StatProduct();
        $stat->product_id = $id;
        $stat->user_id = \user()->id;
        $stat->save();

        return $this->success();
    }

    public function download($id): JsonResponse
    {
        $stat = new StatProductDownload();
        $stat->product_id = $id;
        $stat->user_id = \user()->id;
        $stat->save();

        return $this->success();
    }

}
