<?php

namespace App\Models;

/**
 * Minimal — "just enough to attach folios to" (Phase 3 brief). Not linked
 * to Phase 2's event_clients; a company can be both without those being
 * merged into one record.
 */
class CorporateAccountModel extends TenantModel
{
    protected $table            = 'corporate_accounts';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'company_name',
        'contact_name',
        'billing_address',
        'phone',
        'email',
        'default_rate_plan_id',
    ];

    protected $validationRules = [
        'company_name' => 'required|max_length[150]',
        'email'        => 'permit_empty|valid_email',
    ];

    public function search(string $term)
    {
        return $this->groupStart()->like('company_name', $term)->orLike('contact_name', $term)->groupEnd();
    }

    /**
     * Every folio tagged to this account with a line-item charge dated
     * within [monthStart, monthEnd) — what the monthly statement PDF
     * aggregates. "Charges across the month," not "folios opened in the
     * month" (Phase 3 brief) — a long-running folio's charges from this
     * month count even if the folio itself opened earlier.
     */
    public function chargesForMonth(int $accountId, string $monthStart, string $monthEnd): array
    {
        return $this->db->table('folio_line_items fli')
            ->select('fli.*, folios.id as folio_id, guests.full_name as guest_name')
            ->join('folios', 'folios.id = fli.folio_id')
            ->join('guests', 'guests.id = folios.guest_id')
            ->where('folios.corporate_account_id', $accountId)
            ->where('fli.item_date >=', $monthStart)
            ->where('fli.item_date <', $monthEnd)
            ->orderBy('fli.item_date')
            ->get()
            ->getResult();
    }
}
