<?php

namespace App\Core\Repositories;

use App\Models\Payment;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

/**
 * Payment Repository
 * Handles all database operations for payments
 */
class PaymentRepository
{
    /**
     * Get all payments
     */
    public function getAll(): Collection
    {
        return Payment::with(['invoice', 'customer'])->get();
    }

    /**
     * Get paginated payments
     */
    public function getPaginated(int $perPage = 15, array $filters = []): LengthAwarePaginator
    {
        $query = Payment::with(['invoice', 'customer']);

        // Apply filters
        if (isset($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        if (isset($filters['customer_id'])) {
            $query->where('customer_id', $filters['customer_id']);
        }

        if (isset($filters['invoice_id'])) {
            $query->where('invoice_id', $filters['invoice_id']);
        }

        if (isset($filters['date_from'])) {
            $query->where('payment_date', '>=', $filters['date_from']);
        }

        if (isset($filters['date_to'])) {
            $query->where('payment_date', '<=', $filters['date_to']);
        }

        return $query->orderBy('created_at', 'desc')->paginate($perPage);
    }

    /**
     * Get payment by ID
     */
    public function getById(int $id): ?Payment
    {
        return Payment::with(['invoice', 'customer'])->find($id);
    }

    /**
     * Get payment by payment number
     */
    public function getByPaymentNumber(string $paymentNumber): ?Payment
    {
        return Payment::where('payment_number', $paymentNumber)->first();
    }

    /**
     * Create a new payment
     */
    public function create(array $data): Payment
    {
        return Payment::create($data);
    }

    /**
     * Update a payment
     */
    public function update(Payment $payment, array $data): bool
    {
        return $payment->update($data);
    }

    /**
     * Delete a payment
     */
    public function delete(Payment $payment): bool
    {
        return $payment->delete();
    }
}
