<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Pembayaran;
use Illuminate\Http\Request;

class PembayaranApiController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        $query = Pembayaran::where('user_id', $user->id);

        // cek apakah ada parameter search nama
        if ($request->filled('search')) {
            $query->where('nama', 'like', '%' . $request->search . '%');
        }

        $pembayaran = $query->get();

        return response()->json($pembayaran);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'tanggal' => 'required|date',
            'jenis_pembayaran' => 'required|string',
            'jumlah' => 'required|integer|min:0',
            'keterangan' => 'nullable|string',
            'status' => 'required|in:lunas,belum_lunas',
            'bukti' => 'nullable|file|mimes:jpeg,png,jpg,gif,webp,pdf|max:2048',
        ]);
        $validated['user_id'] = $request->user()->id;
        if ($request->hasFile('bukti')) {
            $validated['bukti'] = $request->file('bukti')->store('bukti_pembayaran', 'public');
        }
        $pembayaran = Pembayaran::create($validated);
        return response()->json($pembayaran, 201);
    }
}