<?php
declare(strict_types=1);

namespace App\Models;

use Core\DB;
use Core\Model;

final class Payment extends Model
{
    protected string $table = 'payments';
    protected string $primaryKey = 'payment_id';

    public static function listForInvoice(int $invoiceId): array
    {
        return DB::all(
            'SELECT p.*, u.username AS created_by_name
               FROM payments p
          LEFT JOIN users u ON u.user_id = p.created_by
              WHERE p.invoice_id = :iid
              ORDER BY p.payment_date DESC, p.payment_id DESC',
            ['iid' => $invoiceId]
        );
    }

    public static function findInTenant(int $tenantId, int $id): ?array
    {
        return DB::one(
            'SELECT p.* FROM payments p WHERE p.tenant_id = :t AND p.payment_id = :id',
            ['t' => $tenantId, 'id' => $id]
        );
    }

    public static function create(int $tenantId, int $invoiceId, array $data, int $userId): int
    {
        $paymentMethod = in_array($data['payment_method'] ?? '', Invoice::PAYMENT_METHODS, true)
            ? $data['payment_method'] : 'bank_transfer';
        $paymentId = (int) DB::insert('payments', [
            'tenant_id'        => $tenantId,
            'invoice_id'       => $invoiceId,
            'amount'           => (float) $data['amount'],
            'payment_method'   => $paymentMethod,
            'reference_number' => $data['reference_number'] ?? null,
            'payment_date'     => $data['payment_date'] ?? date('Y-m-d'),
            'notes'            => $data['notes'] ?? null,
            'created_by'       => $userId > 0 ? $userId : null,
        ]);

        // Recalculate invoice balance
        Invoice::recalculateBalance($invoiceId);

        return $paymentId;
    }

    public static function delete(int $tenantId, int $id): void
    {
        $payment = self::findInTenant($tenantId, $id);
        if (!$payment) return;

        DB::run('DELETE FROM payments WHERE payment_id = :id AND tenant_id = :t', ['id' => $id, 't' => $tenantId]);

        // Recalculate after deletion
        Invoice::recalculateBalance((int) $payment['invoice_id']);
    }
}