<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Models\Finance\PrepaidCard;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

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

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'face_value' => 'required|numeric|min:0',
            'sell_price' => 'required|numeric|min:0',
            'discount_rate' => 'sometimes|numeric|min:0|max:1',
            'validity_days' => 'sometimes|integer|min:1',
            'status' => 'sometimes|integer|in:0,1',
            'sort' => 'sometimes|integer',
        ]);

        return $this->success(PrepaidCard::create($validated));
    }

    public function show(PrepaidCard $prepaidCard): JsonResponse
    {
        return $this->success($prepaidCard);
    }

    public function update(Request $request, PrepaidCard $prepaidCard): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:100',
            'face_value' => 'sometimes|numeric|min:0',
            'sell_price' => 'sometimes|numeric|min:0',
            'discount_rate' => 'sometimes|numeric|min:0|max:1',
            'validity_days' => 'sometimes|integer|min:1',
            'status' => 'sometimes|integer|in:0,1',
            'sort' => 'sometimes|integer',
        ]);

        $prepaidCard->update($validated);

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

    public function destroy(PrepaidCard $prepaidCard): JsonResponse
    {
        $prepaidCard->delete();

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