<?php

require_once __DIR__ . '/BillingHelpers.php';

class BillingPaymentTermsService
{
    public function normalizeToFacto($value, $customDays = null)
    {
        $value = strtolower(trim((string) $value));
        $value = str_replace(array(' ', '-', 'dias', 'dias.', 'credito_', 'credito', 'crédito'), array('_', '_', '', '', '', '', ''), $value);
        $value = trim($value, '_');

        if ($value === '' || $value === 'contado' || $value === '0' || $value === 'prepago') {
            return '0';
        }

        if (in_array($value, array('7', '15', '30', '45'), true)) {
            return $value;
        }

        if ($customDays !== null && $customDays !== '') {
            $days = (int) $customDays;
            if ($days >= 0 && $days <= 365) {
                return (string) $days;
            }
        }

        return '0';
    }

    public function daysFromFacto($factoPaymentConditions)
    {
        $factoPaymentConditions = trim((string) $factoPaymentConditions);
        if ($factoPaymentConditions === '') {
            return 0;
        }

        $parts = array_filter(array_map('trim', explode(',', $factoPaymentConditions)), 'strlen');
        if (empty($parts)) {
            return 0;
        }

        return max(array_map('intval', $parts));
    }

    public function dueDate($issueDate, $factoPaymentConditions)
    {
        $days = $this->daysFromFacto($factoPaymentConditions);
        $ts = strtotime($issueDate ?: date('Y-m-d'));
        if (!$ts) {
            $ts = time();
        }
        return date('Y-m-d', strtotime('+' . $days . ' days', $ts));
    }
}
