<?php

use \ModulesGarden\Servers\OpenXchange\App\Models\MailboxDeleteList;
use \ModulesGarden\Servers\OpenXchange\App\Libs\RestApi;
use \ModulesGarden\Servers\OpenXchange\App\Helpers\Helper;

$hookManager->register(
    function ($args)
    {
        try
        {
            $deleteRequests = MailboxDeleteList::get();

            if (!empty($deleteRequests))
            {
                foreach ($deleteRequests as $deleteRequest)
                {
                    try
                    {
                        //request creation date
                        $createdDate = new \DateTime(date('Y-m-d', strtotime($deleteRequest->created_at)));

                        //todays date
                        $todayDate = new \DateTime(date('Y-m-d'));

                        //diff in days
                        $daysPassed = $createdDate->diff($todayDate)->days;

                        //check if configured number of days already passed
                        if ($daysPassed < (int) $deleteRequest->days_to_delete)
                        {
                            continue;
                        }

                        $params = Helper::moduleParams($deleteRequest->service_id);

                        if (empty($params))
                        {
                            throw new \Exception('Module params are empty for service ID: '. $deleteRequest->service_id);
                        }

                        $context        = new RestApi($params);
                        $userIdPunycode = Helper::convertEmailToPunnycode(
                            strip_tags(
                                html_entity_decode($deleteRequest->mailbox_name)
                            )
                        );

                        $result = $context->deleteUser($userIdPunycode);

                        if ($result == '')
                        {
                            //success remove the delete request to not check it again
                            MailboxDeleteList::where('id', '=', $deleteRequest->id)->delete();
                        }
                        else
                        {
                            //error create the proper log
                            logModuleCall("openxchange", 'DailyCronJobError', $userIdPunycode, $result);
                        }
                    }
                    catch (\Throwable $e)
                    {
                        logModuleCall("openxchange", 'DailyCronJobException', $deleteRequest->id ?? 'unknown', ['message' => $e->getMessage(), 'trace'   => $e->getTraceAsString()]);
                    }
                }
            }
        }
        catch (\Throwable $e)
        {
            logModuleCall("openxchange", 'DailyCronJobFatal', '', ['message' => $e->getMessage(), 'trace'   => $e->getTraceAsString()]);
        }
    },
    100
);