<?php

namespace Shm\ShmAdmin\AdminRPC;

use Shm\Shm;
use Shm\ShmAdmin\AdminPanel;
use Shm\ShmAdmin\SchemaCollections\ShmExportCollection;
use Shm\ShmAdmin\SchemaCollections\ShmexportsField;
use Shm\ShmAuth\Auth;
use Shm\ShmRPC\ShmRPC;
use Shm\ShmUtils\Inflect;
use Shm\ShmUtils\I18n;
use Shm\ShmUtils\Response;
use Shm\ShmUtils\ShmInit;

class AdminRPCMakeStatementExport
{
    public static function rpc()
    {

        return ShmRPC::lazy(function () {

            return [
                'type' => Shm::bool(),
                'args' => Shm::structure([
                    'currency' => Shm::nonNull(Shm::string()),
                    'range' => Shm::structure([
                        'from' => Shm::unixdatetime(),
                        'to' => Shm::unixdatetime(),
                    ]),
                ]),
                'resolve' => function ($root, $args) {



                    Auth::authenticateOrThrow(...AdminPanel::$authStructures);


                    $currentExport = ShmExportCollection::findOne([
                        ShmexportsField::TYPE => ShmexportsField::TYPE_ENUM_STATEMENT,
                        ShmexportsField::STATUS => ['$in' => [ShmexportsField::STATUS_ENUM_PENDING, ShmexportsField::STATUS_ENUM_PROCESSING]]
                    ]);

                    if ($currentExport) {
                        Response::validation(I18n::get('statement_export_active_wait'));
                    }


                    $timezone = date_default_timezone_get();

                    $fileName = 'export_payment_report_' . $timezone . '_' . date('d_m_Y_H_i') . '_' . $args['currency'] . '.xlsx';


                    //Remove special chars from filename $fileName
                    $fileName = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $fileName);

                    $filePathDir = ShmInit::$rootDir . '/storage/exports';
                    if (!file_exists($filePathDir)) {
                        mkdir($filePathDir, 0755, true);
                    }


                    $key = Inflect::singularize(Auth::getAuthCollection());


                    $pipeline = [
                        [
                            '$match' =>  [
                                'currency' => $args['currency'],
                                '$or' => [
                                    [
                                        'manager' => Auth::getAuthID()
                                    ],
                                    [
                                        $key => Auth::getAuthID()
                                    ],
                                ]
                            ]
                        ]
                    ];

                    $range = $args['range'] ?? null;
                    $rangeFrom = is_array($range) ? ($range['from'] ?? null) : null;
                    $rangeTo = is_array($range) ? ($range['to'] ?? null) : null;

                    $docTitle = 'Ведомость расчетов в ' . $args['currency'] . ' на ' . date('d.m.Y H:i');

                    $statementRange = null;
                    if ($rangeFrom && $rangeTo) {
                        $docTitle .= ' с ' . date('d.m.Y H:i', $rangeFrom) . ' по ' . date('d.m.Y H:i', $rangeTo);
                        $statementRange = [
                            'from' => $rangeFrom,
                            'to' => $rangeTo,
                        ];
                    }

                    $pipeline[] =  [
                        '$sort' => ["created_at" => 1]
                    ];

                    ShmExportCollection::insertOne([
                        ShmexportsField::TYPE => ShmexportsField::TYPE_ENUM_STATEMENT,
                        ShmexportsField::TIMEZONE => $timezone,
                        'statementRange' => $statementRange,
                        ShmexportsField::FILE_PATH => $filePathDir . '/' . $fileName,
                        ShmexportsField::FILE_NAME => $fileName,
                        ShmexportsField::TITLE => $docTitle,
                        'token' => Auth::$currentRequestToken,
                        ShmexportsField::PIPELINE => $pipeline,
                        ShmexportsField::STATUS => ShmexportsField::STATUS_ENUM_PENDING,
                    ]);




                    return true;
                }

            ];
        });
    }
}
