<?php

namespace App\Http\Controllers;

use App\Models\CashMutation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CashMutationController extends Controller
{
    public function index(Request $request)
    {
        $perPage = $request->input('per_page', 15);

        $mutations = CashMutation::with('user')
            ->orderByDesc('mutation_date')
            ->orderByDesc('created_at')
            ->paginate($perPage);

        return view('pages.finance.mutations.index', [
            'title' => 'Log Mutasi Kas',
            'mutations' => $mutations,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'mutation_date' => 'required|date',
            'from_account' => 'required|in:petty,cash,bank',
            'to_account' => 'required|in:petty,cash,bank|different:from_account',
            'notes' => 'nullable|string|max:500',
        ]);

        $validated['user_id'] = Auth::id();

        DB::transaction(function () use ($validated) {
            CashMutation::create($validated);
        });

        return redirect()->route('finance.cash')
            ->with('success', 'Mutasi kas berhasil dicatat');
    }
}