<?php

namespace App\Http\Controllers\Admin\Crm;

use App\Http\Controllers\Controller;
use App\Models\Crm\Channel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ChannelController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Channel::query();
        $query->when($request->name, fn($q, $v) => $q->where('name', 'like', "%{$v}%"));
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));

        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'type' => 'required|integer|in:1,2,3',
            'status' => 'sometimes|integer|in:0,1',
        ]);

        $channel = Channel::create($validated);

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

    public function show(Channel $channel): JsonResponse
    {
        return $this->success($channel->load('leads'));
    }

    public function update(Request $request, Channel $channel): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:50',
            'type' => 'sometimes|integer|in:1,2,3',
            'status' => 'sometimes|integer|in:0,1',
        ]);

        $channel->update($validated);

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

    public function destroy(Channel $channel): JsonResponse
    {
        $channel->delete();

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