<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TransactionController extends Controller
{
    public function index(Request $request)
    {
        $request->validate([
            'month' => 'nullable|integer|min:1|max:12',
            'year' => 'nullable|integer|min:2000|max:'.now()->year,
            'type' => 'nullable|in:credit,debit,all',
            'sort' => 'nullable|in:a-z,z-a,newest,oldest',
            'per_page' => 'nullable|integer|min:1|max:100',
        ]);

        $query = Auth::user()->transactions();

        // Filter by type (credit/debit); "all" or omitted = no filter
        if ($request->filled('type') && $request->type !== 'all') {
            $query->where('type', $request->type);
        }

        // Filter by month
        if ($request->filled('month')) {
            $query->whereMonth('created_at', $request->month);
        }

        // Filter by year
        if ($request->filled('year')) {
            $query->whereYear('created_at', $request->year);
        }

        // Sorting
        match ($request->input('sort', 'newest')) {
            'a-z' => $query->orderBy('channel', 'asc'),
            'z-a' => $query->orderBy('channel', 'desc'),
            'oldest' => $query->orderBy('created_at', 'asc'),
            default => $query->orderBy('created_at', 'desc'), // newest
        };

        $transactions = $query->paginate($request->input('per_page', 20));

        return response()->json([
            'status' => true,
            'data' => $transactions,
        ]);
    }
}