<?php

namespace App\Http\Controllers;

use App\Models\Receipt;
use Illuminate\Http\Request;

class ReceiptController extends Controller
{
    public function index(Request $request)
    {
        $query = Receipt::with('operator')->orderBy('date', 'desc');
        
        if ($request->has('type')) {
            $query->where('type', $request->type);
        }
        
        return $query->get();
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'date' => 'required|date',
            'amount' => 'required|numeric',
            'type' => 'required|string', // Income, Expense, Advance
            'recipient_type' => 'nullable|string',
            'operator_id' => 'nullable|exists:operators,id',
            'particulars' => 'nullable|string',
            'payment_mode' => 'required|string',
            'description' => 'nullable|string'
        ]);

        return Receipt::create($validated);
    }

    public function update(Request $request, Receipt $receipt)
    {
        $validated = $request->validate([
            'date' => 'date',
            'amount' => 'numeric',
            'type' => 'string',
            'particulars' => 'nullable|string',
            'payment_mode' => 'string',
        ]);

        $receipt->update($validated);
        return $receipt;
    }

    public function destroy(Receipt $receipt)
    {
        $receipt->delete();
        return response()->json(['success' => true]);
    }
}
