<?php

namespace PortalPeople\invoicing\services;

use backend\models\Cartsbe;
use Yii;

/**
 * Invoice Eligibility Service
 *
 * Determines which carts are eligible for invoice generation.
 */
class InvoiceEligibilityService
{
    /**
     * Check if a cart is eligible for invoice generation
     *
     * @param Cartsbe $cart
     * @param string|null $asOfDate Date to check against (YYYY-MM-DD), defaults to today
     * @return bool
     */
    public function isEligible(Cartsbe $cart, ?string $asOfDate = null): bool
    {
        $asOfDate = $asOfDate ?? date('Y-m-d');
        
        // Check cart status - must be confirmed/paid
        if (!in_array($cart->status, $this->getEligibleStatuses())) {
            return false;
        }

        // Check billingstatus - must not be already invoiced or cancelled
        if (!in_array($cart->billingstatus, $this->getEligibleBillingStatuses())) {
            return false;
        }

        // Check centrearrddate - must be in the past or today
        if (empty($cart->centrearrddate)) {
            return false;
        }

        $arrivalDate = date('Y-m-d', strtotime($cart->centrearrddate));
        if ($arrivalDate > $asOfDate) {
            return false;
        }

        return true;
    }

    /**
     * Get eligible cart statuses for invoicing
     *
     * @return array
     */
    protected function getEligibleStatuses(): array
    {
        return ['Completed', 'Confirmed', 'Paid'];
    }

    /**
     * Get eligible billing statuses for invoicing
     *
     * @return array
     */
    protected function getEligibleBillingStatuses(): array
    {
        return ['Pending', 'PartiallyPaid', 'Unpaid'];
    }

    /**
     * Query carts eligible for invoice generation
     *
     * @param string|null $asOfDate Date to filter by (YYYY-MM-DD)
     * @return \yii\db\ActiveQuery
     */
    public function getEligibleCartsQuery(?string $asOfDate = null): \yii\db\ActiveQuery
    {
        $asOfDate = $asOfDate ?? date('Y-m-d');
        
        $eligibleStatuses = $this->getEligibleStatuses();
        $eligibleBillingStatuses = $this->getEligibleBillingStatuses();

        return Cartsbe::find()
            ->where(['in', 'status', $eligibleStatuses])
            ->andWhere(['in', 'billingstatus', $eligibleBillingStatuses])
            ->andWhere(['<=', new \yii\db\Expression("DATE(FROM_UNIXTIME(centrearrddate))"), $asOfDate])
            ->andWhere(['!=', 'centrearrddate', null]);
    }
}
