<?php

namespace App\Repositories;

use App\Enumerations\CostUnitType;
use App\Enumerations\InvoiceStatus;
use App\Enumerations\InvoiceType;
use App\Enumerations\UserRole;
use App\Models\CostUnit;
use App\Providers\AuthCheckProvider;
use App\Resources\CostUnitResource;
use App\ValueObjects\Amount;
use Illuminate\Database\Capsule\Manager as Capsule;

class CostUnitRepository {
    public function getCostUnitsForNewInvoice(string $type) : array {
        return $this->getCostUnitsByCriteria([
            'allow_new' => true,
            'type' => $type,
            'archived' => false
        ], true, true);
    }




    public function getCurrentEvents(bool $disableAccessCheck = false) : array {
        return $this->getCostUnitsByCriteria([
            'allow_new' => true,
            'type' => CostUnitType::COST_UNIT_TYPE_EVENT,
            'archived' => false
        ],
        true,
        $disableAccessCheck);
    }

    public function getRunningJobs() : array {
        return $this->getCostUnitsByCriteria([
            'allow_new' => true,
            'type' => CostUnitType::COST_UNIT_TYPE_RUNNING_JOB,
            'archived' => false
        ]);
    }

    public function getArchivedCostUnits() : array {
        return $this->getCostUnitsByCriteria([
            'archived' => true,
            'allow_new' => false,
        ]);
    }

    public function getClosedCostUnits() : array{
        return $this->getCostUnitsByCriteria([
            'archived' => false,
            'allow_new' => false,
        ]);
    }

    public function getById(int $id, bool $disableAccessCheck = false) : ?CostUnit {
        $costUnits = self::getCostUnitsByCriteria(['id' => $id], false, $disableAccessCheck);
        if (count($costUnits) === 0) {
            return null;
        }
        return $costUnits[0];

    }

    public function getCostUnitsByCriteria(array $criteria, bool $forDisplay = true, $disableAccessCheck = false) : array {
        $user = Auth()->user();

        if ($disableAccessCheck) {
            $canSeeAll = true;
        } else {
            $canSeeAll = in_array(new AuthCheckProvider()->getUserRole(), [
                UserRole::USER_ROLE_ADMIN, UserRole::USER_ROLE_GROUP_LEADER
            ]);
        }

        $visibleCostUnits = [];
        /** @var CostUnit $costUnit */
        foreach (Costunit::where($criteria)->get() as $costUnit) {
            if ($canSeeAll || $costUnit->treasurers()->where('user_id', $user->id)->exists() ) {
                if ($forDisplay) {
                    $visibleCostUnits[] = new CostUnitResource($costUnit)->toArray(request());
                } else {
                    $visibleCostUnits[] = $costUnit;
                }

            }

        }

        return $visibleCostUnits;
    }

    public function listForSummary(int $maxCountCostUnits) : array {
        $costUnits = $this->getCostUnitsByCriteria([
            'archived' => false,
            'tenant' => app('tenant')->slug,
        ],false);

        foreach ($costUnits as &$cu) {
            $cu->new_invoices_count = $cu->invoices()->where('status', 'new')->count();
            $cu->approved_invoices_count = $cu->invoices()->where('status', 'approved')->count();
        }

        $costUnits = collect($costUnits)
            ->sortByDesc('approved_invoices_count')
            ->sortByDesc('new_invoices_count')
            ->take($maxCountCostUnits)
            ->values()
            ->all();

        $returnData = [];

        foreach ($costUnits as $costUnit) {
            if($costUnit->approved_invoices_count === 0 && $costUnit->new_invoices_count === 0) {
                continue;
            }

            if (strlen($costUnit->name) > 15) {
                $costUnit->name = substr($costUnit->name, 8, 13) . '...';
            }
            $costUnit->totalAmount = $this->sumupUnhandledAmounts($costUnit)->toString();
            $returnData[] = $costUnit;
        }

        return $returnData;
    }

    public function sumupAmounts(CostUnit $costUnit, bool $donatedAmount = false) : Amount {
        $amount = new Amount(0, '');

        foreach ($costUnit->invoices()->get() as $invoice) {
            if ($invoice->status === InvoiceStatus::INVOICE_STATUS_DENIED) {
                continue;
            }

            if (
                ($donatedAmount && !$invoice->donation) ||
                (!$donatedAmount && $invoice->donation)
            ) {
                    continue;
            }

            $amount->addAmount(Amount::fromString($invoice->amount));
        }
        return $amount;
    }

    public function sumupByInvoiceType(CostUnit $costUnit, InvoiceType $invoiceType) : Amount {
        $amount = new Amount(0, 'Euro');

        foreach ($costUnit->invoices()->get() as $invoice) {
            if (
                $invoice->status === InvoiceStatus::INVOICE_STATUS_DENIED ||
                $invoice->donation ||
                $invoice->type !== $invoiceType->slug
            ) {
                continue;
            }

            $amount->addAmount(Amount::fromString($invoice->amount));
        }
        return $amount;
    }

    public function sumupEstimatedByInvoiceType(CostUnit $costUnit, InvoiceType $invoiceType) : Amount {
        $amount = new Amount(0, 'Euro');
        foreach ($costUnit->estimates()->get() as $estimate) {
            if ($estimate->type !== $invoiceType->slug) {
                continue;
            }

            $amount->addAmount($estimate->calculateAmount());
        }
        return $amount;
    }

    public function sumupUnhandledAmounts(CostUnit $costUnit, bool $donatedAmount = false) : Amount {
        $amount = new Amount(0, '');

        foreach ($costUnit->invoices()->get() as $invoice) {
            if (!in_array($invoice->status,
                [InvoiceStatus::INVOICE_STATUS_NEW, InvoiceStatus::INVOICE_STATUS_APPROVED])) {
                continue;
            }

            if (
                ($donatedAmount && !$invoice->donation) ||
                (!$donatedAmount && $invoice->donation)
            ) {
                continue;
            }

            $amount->addAmount(Amount::fromString($invoice->amount));
        }
        return $amount;
    }

    public function countInvoices(CostUnit $costUnit) : array {
        $returnData = [
            InvoiceStatus::INVOICE_STATUS_NEW => 0,
            InvoiceStatus::INVOICE_STATUS_APPROVED => 0,
            InvoiceStatus::INVOICE_STATUS_DENIED => 0,
            InvoiceStatus::INVOICE_META_STATUS_NO_PAYOUT => 0,
            InvoiceStatus::INVOICE_META_STATUS_DONATED => 0
        ];

        foreach ($costUnit->invoices()->get() as $invoice) {
            if ($invoice->status === InvoiceStatus::INVOICE_STATUS_DELETED) {
                continue;
            }

            if( $invoice->status === InvoiceStatus::INVOICE_STATUS_DENIED) {
                $returnData[InvoiceStatus::INVOICE_STATUS_DENIED]++;
                continue;
            }

            switch ($invoice->status) {
                case InvoiceStatus::INVOICE_STATUS_NEW:
                    $returnData[InvoiceStatus::INVOICE_STATUS_NEW]++;
                    break;
                case InvoiceStatus::INVOICE_STATUS_APPROVED:
                    $returnData[InvoiceStatus::INVOICE_STATUS_APPROVED]++;
                    break;
                case InvoiceStatus::INVOICE_STATUS_EXPORTED:
                    if ($invoice->donation) {
                        $returnData[InvoiceStatus::INVOICE_META_STATUS_DONATED]++;
                    } else {
                        if ($invoice->contact_bank_iban === null) {
                            $returnData[InvoiceStatus::INVOICE_META_STATUS_NO_PAYOUT]++;
                        }
                    }
                    break;
            }
        }

        return $returnData;
    }

}
