<?php

namespace Modules\POS\Models;

use core\Model;
use core\Database;

class Payment extends Model
{
    protected string $table = 'invoice_payments';
    protected string $primaryKey = 'id';
    protected array $fillable = [
        'invoice_id', 'payment_method', 'amount', 'reference_number',
        'created_at',
    ];
    protected array $guarded = ['id'];
    protected array $casts = [
        'amount' => 'float',
        'created_at' => 'datetime',
    ];

    public function getByInvoice(int $invoiceId): array
    {
        $db = Database::getInstance();
        return $db->table($this->table)
            ->where('invoice_id', $invoiceId)
            ->orderBy('created_at', 'ASC')
            ->get();
    }

    public function getTodayPayments(): array
    {
        $db = Database::getInstance();
        $today = date('Y-m-d');
        return $db->table($this->table)
            ->where('created_at', '>=', $today . ' 00:00:00')
            ->where('created_at', '<=', $today . ' 23:59:59')
            ->orderBy('created_at', 'DESC')
            ->get();
    }

    public function getByMethod(): array
    {
        $db = Database::getInstance();
        return $db->table($this->table)
            ->select('payment_method, COUNT(*) as count, SUM(amount) as total')
            ->groupBy('payment_method')
            ->get();
    }

    public function getTotalToday(): float
    {
        $db = Database::getInstance();
        $today = date('Y-m-d');
        return (float)$db->table($this->table)
            ->where('created_at', '>=', $today . ' 00:00:00')
            ->where('created_at', '<=', $today . ' 23:59:59')
            ->sum('amount');
    }
}
