<?php

namespace App\Models;

/**
 * Split billing: one row per payer responsible for part of a folio's
 * total (e.g. guest pays room, company pays extras). A null
 * folio_line_item_id means the original folio-level behavior — this
 * amount comes off the folio's total, not any one charge. A set value
 * (see AddLineItemToFolioPayerAllocations) narrows that same amount to
 * one specific charge instead — both modes coexist on the same folio.
 */
class FolioPayerAllocationModel extends TenantModel
{
    protected $table            = 'folio_payer_allocations';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'folio_id',
        'folio_line_item_id',
        'payer_name',
        'payer_guest_id',
        'amount',
        'notes',
    ];

    protected $validationRules = [
        'folio_id'   => 'required|integer',
        'payer_name' => 'required|max_length[150]',
        'amount'     => 'required|decimal',
    ];

    public function forFolio(int $folioId): array
    {
        return $this->select('folio_payer_allocations.*, folio_line_items.description as line_item_description')
            ->join('folio_line_items', 'folio_line_items.id = folio_payer_allocations.folio_line_item_id', 'left')
            ->where('folio_payer_allocations.folio_id', $folioId)
            ->orderBy('folio_payer_allocations.id', 'asc')
            ->findAll();
    }

    public function totalAllocated(int $folioId): string
    {
        $result = $this->db->table('folio_payer_allocations')
            ->selectSum('amount')
            ->where('folio_id', $folioId)
            ->get()
            ->getRow();

        return $result->amount ?? '0.00';
    }
}
