Duffer Derek

Current Path : /var/www/podiomigration.bitkit.dk/httpdocs/src/classes/Repository/Utils/
Upload File :
Current File : /var/www/podiomigration.bitkit.dk/httpdocs/src/classes/Repository/Utils/TestingRepo.php

<?php

/**
 * Created by PhpStorm.
 * User: jis
 * Date: 30/3/17
 * Time: 12:14 PM
 */

namespace App\Repository\Utils;

use App\Repository\Copy\FileCopyRepo;
use App\Repository\Copy\AppCopyRepo;
use App\Repository\Copy\TasksCopyRepo;
use App\Repository\Create\AppCreateRepo;
use App\Repository\Create\CommentsCreateRepo;
use App\Repository\Create\ItemCreateRepo;
use App\Repository\Create\TaskCreateRepo;
use App\Repository\General\Async;
use App\Repository\General\AuthRepo;
// use App\Repository\General\Config;
use App\Repository\General\DB;
use App\Repository\General\Log;
use App\Config\Config;

use Exception;
use PDO;
use Podio;
use PodioApp;
use PodioAppField;
use PodioBadRequestError;
use PodioEmbed;
use PodioFile;
use PodioFlow;
use PodioItem;
use PodioItemField;
use PodioSearchResult;
use PodioSpace;
use PodioSpaceMember;
use PodioStatus;
use PodioTask;
use PodioUserStatus;
use PodioView;
use PodioWidget;
use Traversable;
use PodioContact;

class TestingRepo
{
    private $customPodioAPI;

    /**
     * TestRepo constructor.
     */
    public function __construct()
    {
        $this->customPodioAPI = new CustomPodioAPI();
    }

    public function testAuth()
    {
        echo "<pre>";
        echo "Here";
        try {
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(1)) {
                // if ($repo->authenticateSF(6)) {
                print_r(PodioUserStatus::get());
            } else {
                print_r("asdasd");
            }
        } catch (Exception $e) {
            print_r($e);
        }
    }

    // http://logmein//testing/{type}
    public
    function testProcess($type, $param)
    {
        echo "Testing";
        //        exit;
        $authRepo = new AuthRepo();
        //        if ($authRepo->podioAuthPers()) {
        Log::log("testProcess " . $type, $param);
        echo "<pre>";

        switch ($type) {
            case "test":
                // $this->getUserReport();
                $this->testAuth();
                break;
            case "testCaseByChinnu":
                $this->testCaseByChinnu();
                break;
            case "calculation":
                $this->addCalculation();
                break;
            case "recreate-views":
                $this->recreateAppViews();
                break;
            case "create-space-widget":
                $this->updateSpaceWidget();
                break;
            case "flows":
                $this->addFlows();
                break;
            case 'invite-user':
                $this->inviteSpaceUsers();
                break;
            case 'update-task-responsible':
                $this->updateTaskResponsible();
                break;
            case 'update-relation':
                $this->updateAppRelation();
                break;
            case 'update-contact':
                $this->updateContact();
                break;
            case 'delete-items':
                $this->deleteItems();
                break;
            case 'create-item-tasks':
                $this->createItemTasks();
                break;
            case 'save-item-files':
                $this->saveItemFiles();
                break;
            case 'save-comment-files':
                $this->saveCommentFiles();
                break;


                //            case "limit":
                //                $this->checkLimit();
                //                break;
                //            case "limit-test":
                //                $this->createItems();
                //                break;
                //            case "limit-get":
                //                $this->getItems();
                //                break;
                //            case "save-space-contact-app":
                //                $this->createItems();
                //                break;
                //            case "update-views":
                //                $this->updateAppViews();
                //                break;
                //            case "delete-views":
                //                $this->deleteAppViews();
                //                break;
                //            case "delete-flows":
                //                $this->deleteFlows();
                //                break;
                //            case "link":
                //                $this->updateSpaceWidgetLink();
                //                break;
                //            case "warning":
                //                $this->addWarningWidget();
                //                break;
                //            case "views":
                //                $this->saveAppViews();
                //                break;
                //            case "status":
                //                $this->addStatusToAllSpace();
                //                break;
                //
                //            case "deletes":
                //                $this->DeleteMultipleSpaceWidget();
                //                break;
                //            case "webform":
                //                exit;
                //                $this->updateWebForms();
                //                break;
                //            case "attach":
                //                $this->attachFile();
                //                break;
                //            case 'get':
                //                $this->getFile();
                //                break;
                //            case "form":
                //                $this->getWebForms();
                //                break;
                //            case "add":
                //                exit;
                //                $this->addWebForms();
                //                break;
                //            case 'update-field':
                //                $this->updateAppFields();
                //                break;
                ////            case "add":
                ////                $this->addWebForms();
                ////                break;
                ////            }
                //            case 'remove-users':
                //                $this->removeUsersFromWS();
                //                break;

        }
    }

    private function removeUsersFromWS()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        try {
            if ($repo->authenticate(20)) {
                $name = array("Administrationsgruppe IN", "Kopi og print 50.10 -2018", "Signalanlæg - 2017", "Sprogtolkning - 2018", "Rakat", "Brøndsug - 2018", "Ballerup - Udbud og kontraktstyring");
                $sql = "SELECT `src_space_id`,`src_name` FROM `work_spaces` WHERE `src_name`NOT IN ( '" . implode("', '", $name) . "' )";
                $STH = DB::prepare($sql);
                $STH->execute(array("name" => $name));
                $spaces = $STH->fetchAll(PDO::FETCH_ASSOC);
                foreach ($spaces as $space) {
                    $limit = 100;
                    $offset = 0;
                    $attributes = array("limit" => $limit);
                    do {
                        $attributes['offset'] = $offset;
                        $count = 0;
                        $workSpaceMembers = $this->customPodioAPI->podioGet("/space/" . $space['src_space_id'] . "/member/", $attributes);
                        if ($workSpaceMembers && is_array($workSpaceMembers) && count($workSpaceMembers) > 0) {
                            $count = count($workSpaceMembers);
                            foreach ($workSpaceMembers as $contact) {
                                if ($contact['user']['mail'] != "podio@in-kommuner.dk")
                                    PodioSpaceMember::delete($space['src_space_id'], $contact['profile']['user_id']);
                                else
                                    echo "YESSSSSSSSSSSSSSSSSS <br>";
                            }
                            $offset += $limit;
                        }
                    } while ($count > 0);
                    //                exit;
                }
            }
        } catch (Exception $e) {
            print_r($space['src_name'] . "<br>");
            array_push($name, $space['src_name']);
            //            exit;
        }
    }


    private function getFiles()
    {
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(8)) {
            try {
                $sql1 = "select `src_ref_id` from `files` where `new_file_id` is null";
                $STH1 = DB::prepare($sql1);
                $STH1->execute();
                $result = $STH1->fetchAll(PDO::FETCH_ASSOC);
                if ($result && count($result) > 0) {
                    foreach ($result as $app) {
                        $item = PodioItem::get($app['src_ref_id']);
                        print_r($item->link);
                        echo "<br>";
                    }
                }
            } catch (Exception $e) {
                print_r($e);
            }
        }
    }

    private function updateDestApps()
    {
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(9)) { // if ($repo->authenticateSF(6)) {
            $sql1 = "select * from items where dest_item_id=:dest_item_id";
            $STH1 = DB::prepare($sql1);
            $sql2 = "select dest_app_id  from `apps`";
            $STH2 = DB::prepare($sql2);
            $STH2->execute();
            $result = $STH2->fetchAll(PDO::FETCH_ASSOC);
            $YesCount = 0;
            $NoCount = 0;
            if ($result && count($result) > 0) {
                foreach ($result as $app) {
                    $offset = 0;
                    $limit = 75;
                    $attributes = array(
                        'filters' => array(),
                        'sort_by' => 'created_on',
                        'sort_desc' => false
                    );
                    $attributes['limit'] = $limit;
                    do {
                        $attributes['offset'] = $offset;
                        $iterationCount = 0;
                        $filterItems = $this->customPodioAPI->filterPodioItems($app['dest_app_id'], $attributes);
                        if ($filterItems) {
                            $iterationCount = count($filterItems['items']);
                            if ($iterationCount > 0) {
                                foreach ($filterItems['items'] as $item) {
                                    $itemId = $item['item_id'];
                                    $STH1->execute(array("dest_item_id" => $itemId));
                                    $items = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                    if ($items && count($items) > 0) {
                                        $YesCount++;
                                    } else {
                                        PodioItem::delete($itemId);
                                        $NoCount++;
                                    }
                                }
                            }
                        }
                        $offset += $limit;
                    } while ($iterationCount > 0);
                }
            }
            print_r("----" . $YesCount . "--------" . $NoCount);
        }
    }

    private
    function checkLimit()
    {
        try {
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(1)) {
                PodioItem::get(1072635933);
                $limit = Podio::rate_limit_remaining();
                echo $limit;
            }
        } catch (Exception $e) {
            print_r($e);
        }
    }

    private function createItems()
    {
        try {
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(2)) {
                for ($i = 0; $i < 900; $i++) {
                    $limit = Podio::rate_limit_remaining();
                    $podioField = array("title" => $limit);
                    $podioFields = array("fields" => $podioField);
                    PodioItem::create(18928538, $podioFields);
                }
            }
        } catch (Exception $e) {
            print_r($e);
        }
    }

    private function getItems()
    {
        try {
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(2)) {
                for ($i = 0; $i < 1; $i++) {
                    $offset = 0;
                    $limit = 10;
                    $totalCount = 0;
                    $attributes = array(
                        'filters' => array(),
                        'sort_by' => 'created_on',
                        'sort_desc' => false
                    );
                    $attributes['limit'] = $limit;
                    do {
                        $attributes['offset'] = $offset;
                        $iterationCount = 0;
                        $filterItems = $this->customPodioAPI->filterPodioItems(18928538, $attributes);
                        echo "<pre>";
                        print_r($filterItems);
                        echo count($filterItems['items']) . "<br>";
                        if ($filterItems) {
                            $iterationCount = count($filterItems['items']);
                            $totalCount += $iterationCount;
                        }
                        $offset += $limit;
                        $limit = Podio::rate_limit_remaining();
                        echo $iterationCount . "<br>";
                        echo $totalCount . "<br>";
                        echo "<br>";
                    } while ($iterationCount > 0);
                }
            }
        } catch (Exception $e) {
            print_r($e);
        }
    }

    private
    function updateAppFields()
    {
        echo "<pre>";
        try {
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(9)) { // if ($repo->authenticateSF(6)) {
                $sql = "select `src_field_config`,`dest_app_id`,`dest_field_id` from `app_fields` WHERE status = 'active' AND field_type = 'app' AND dest_field_id IS NOT NULL AND ref_updated IS NULL";
                $STH = DB::prepare($sql);
                $STH->execute();
                $result = $STH->fetchAll(PDO::FETCH_ASSOC);
                $sql1 = "select dest_app_id  from `apps` 
             where src_app_id=:src_app_id limit 1";
                $STH1 = DB::prepare($sql1);
                $sql2 = "SELECT created_view_id FROM app_views WHERE src_view_d = :src_view_id";
                $STH2 = DB::prepare($sql2);
                $sql3 = "UPDATE app_fields SET ref_updated=:ref_updated WHERE dest_field_id=:dest_field_id";
                $STH3 = DB::prepare($sql3);
                if ($result && count($result) > 0) {
                    foreach ($result as $field) {
                        $srcFieldConfig = json_decode($field['src_field_config']);
                        $srcFieldConfig = (array)$srcFieldConfig;

                        $config = array(
                            'label' => $srcFieldConfig['label'],
                            'visible' => $srcFieldConfig['visible'],
                            'delta' => $srcFieldConfig['delta'],
                            'mapping' => $srcFieldConfig['mapping'],
                            'default_value' => $srcFieldConfig['default_value'],
                            'required' => $srcFieldConfig['required'],
                            'description' => $srcFieldConfig['description']
                        );
                        if (isset($srcFieldConfig['hidden']))
                            $config['hidden'] = $srcFieldConfig['hidden'];

                        $oldRelationApps = array();
                        if (isset($srcFieldConfig['settings']->apps)) {
                            foreach ($srcFieldConfig['settings']->apps as $refApp) {
                                $oldRelationApps[] = intval($refApp->app_id);
                            }
                        }

                        $oldRelationViews = array();
                        if (isset($srcFieldConfig['settings']->referenced_apps)) {
                            foreach ($srcFieldConfig['settings']->referenced_apps as $refApp) {
                                $oldRelationViews[$refApp->app_id] = $refApp->view_id;
                            }
                        }

                        $newRelationViews = array();
                        if (count($oldRelationViews) > 0) {
                            foreach ($oldRelationViews as $app => $oldRelationView) {
                                $STH1->execute(array(
                                    'src_app_id' => $app,
                                ));
                                $newApp = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                if ($newApp && count($newApp) > 0) {
                                    $refApp = $newApp[0];
                                    if (isset($oldRelationView)) {
                                        $STH2->execute(array(
                                            'src_view_id' => $oldRelationView,
                                        ));
                                        $newView = $STH2->fetchAll(PDO::FETCH_ASSOC);
                                        if ($newView && count($newView) > 0) {
                                            $newRelationViews[] = array(
                                                "view_id" => intval($newView[0]['created_view_id']),
                                                "app_id" => intval($refApp['dest_app_id'])
                                            );
                                        }
                                    } else {
                                        $newRelationViews[] = array(
                                            "app_id" => intval($refApp['dest_app_id'])
                                        );
                                    }
                                }
                            }
                        }

                        $newRelationApps = array();
                        if (count($oldRelationApps) > 0) {
                            foreach ($oldRelationApps as $oldRelationApp) {
                                $STH1->execute(array(
                                    'src_app_id' => $oldRelationApp,
                                ));

                                $result = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                if ($result && count($result) > 0) {
                                    $refApp = $result[0];
                                    $newRelationApps[] = intval($refApp['dest_app_id']);
                                }
                            }
                        }
                        $config['settings'] = array('referenceable_types' => $newRelationApps, 'referenced_apps' => $newRelationViews);
                        echo "<br>";
                        //                        print_r($config);
                        try {
                            PodioAppField::update($field['dest_app_id'], $field['dest_field_id'], $config);
                            $STH3->execute(array(
                                'dest_field_id' => $field['dest_field_id'],
                                'ref_updated' => 1
                            ));
                        } catch (Exception $e) {
                            $STH3->execute(array(
                                'dest_field_id' => $field['dest_field_id'],
                                'ref_updated' => 2
                            ));
                        }
                    }
                }
            }
        } catch (Exception $e) {
            print_r($e);
        }
    }

    private
    function getFileData()
    {
        try {
            $repo = new PodioAuthRepo();
            if ($repo->authenticateSF(1)) {
                $fileID = 273999059;
                $file = Podio::get("/file/$fileID/")->json_body();
                echo "<pre>";
                print_r($file['external_file_id']);
            }
        } catch (Exception $e) {
            print_r($e);
        }
    }

    private
    function getFile()
    {
        try {
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(9)) { // if ($repo->authenticateSF(6)) {
                $file = Podio::post("/file/linked_account/846554/", array("external_file_id" => "st00b83d-116b-4b72-9ed0-0d3f198f04ec"))->json_body();
                echo "<pre>";
                print_r($file['file_id']);
            }
        } catch (Exception $e) {
            print_r($e);
        }
    }

    private
    function attachFile()
    {
        try {
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(9)) { // if ($repo->authenticateSF(6)) {
                $file = Podio::post("/file/364087090/attach/", array("ref_type" => "task", "ref_id" => 71643024));
                echo "<pre>";
                print_r($file);
            }
        } catch (Exception $e) {
            print_r($e);
        }
    }

    private
    function getEnableAppComments()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $appId = '';
            $appDetails = Podio::get("/app/$appId")->json_body();
            if ($appDetails['config']['allow_comments']) {
                $newAppDetails['config'] = $appDetails['config'];
                $newAppDetails['config']['allow_comments'] = false;
                try {
                    $resp = PodioApp::update($appId, $newAppDetails);
                } catch (Exception $e) {
                }
            }
        }
    }


    private
    function archieveApps()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $apps = array();
            foreach ($apps as $app) {
                try {
                    PodioApp::deactivate($app);
                } catch (Exception $e) {
                }
            }
        }
    }

    private
    function webFromCount()
    {
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $sql = "select `src_app_id`,src_app_url,`dest_app_id` from `apps`";
            $STH = DB::prepare($sql);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $app) {
                    $appId = $app['src_app_id'];
                    $forms = Podio::get("/form/app/$appId/")->json_body();
                    if (count($forms) > 0) {
                        echo $app['src_app_url'] . "<br>";
                    }
                }
            }
        }
    }

    private
    function updateWebForms()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $sql = "select `src_app_id`,`dest_app_id` from `apps` WHERE `webform_updated`IS NULL";
            $STH = DB::prepare($sql);
            $STH->execute();
            $sql1 = "UPDATE apps set webform_updated =:webform_updated where src_app_id =:src_app_id";
            $STH1 = DB::prepare($sql1);
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $app) {
                    $appId = $app['src_app_id'];
                    try {
                        $forms = Podio::get("/form/app/$appId/")->json_body();
                        if (count($forms) > 0) {
                            foreach ($forms as $form) {
                                if ($form['status'] == "active") {
                                    $destAppId = $app['dest_app_id'];
                                    $settings = $form['settings'];
                                    $newforms = Podio::get("/form/app/$destAppId/")->json_body();
                                    if (is_null($settings['css']) || $settings['css'] == "") {
                                        if (count($newforms) > 0) {
                                            $newFormId = $newforms[0]['form_id'];
                                            $settings['css'] = "#webforms__fields-container {\n  display: none;\n}\n.btn-primary {\n  display: none;\n}";
                                            $settings['text']['description'] = 'This webform is migrated to new URL under LogMeIn organization.<br /><br />Please use the link <a href="https://podio.com/webforms/' . $destAppId . '/' . $newFormId . '">https://podio.com/webforms/' . $destAppId . '/' . $newFormId . '</a><br /><br />Please contact <a href="mailto:helpdesk@logmein.com">helpdesk@logmein.com</a> with URL of this page if you have any questions.';
                                            try {
                                                \PodioForm::update($form['form_id'], array("settings" => $settings, "domains" => $form['domains'], "fields" => $form['fields'], "attachments" => $form['attachments']));
                                                $data = array("src_app_id" => $appId, "webform_updated" => 1);
                                                $STH1->execute($data);
                                            } catch (Exception $e) {
                                                $data = array("src_app_id" => $appId, "webform_updated" => 2);
                                                $STH1->execute($data);
                                            }
                                        } else {
                                            $data = array("src_app_id" => $appId, "webform_updated" => 3);
                                            $STH1->execute($data);
                                        }
                                    } else {
                                        if (count($newforms) > 0) {
                                            $newFormId = $newforms[0]['form_id'];
                                            $settings['css'] .= "#webforms__fields-container {\n  display: none;\n}\n.btn-primary {\n  display: none;\n}";
                                            $settings['text']['description'] = 'This webform is migrated to new URL under LogMeIn organization.<br /><br />Please use the link <a href="https://podio.com/webforms/' . $destAppId . '/' . $newFormId . '">https://podio.com/webforms/' . $destAppId . '/' . $newFormId . '</a><br /><br />Please contact <a href="mailto:helpdesk@logmein.com">helpdesk@logmein.com</a> with URL of this page if you have any questions.';
                                            try {
                                                \PodioForm::update($form['form_id'], array("settings" => $settings, "domains" => $form['domains'], "fields" => $form['fields'], "attachments" => $form['attachments']));
                                                $data = array("src_app_id" => $appId, "webform_updated" => 1);
                                                $STH1->execute($data);
                                            } catch (Exception $e) {
                                                $data = array("src_app_id" => $appId, "webform_updated" => 2);
                                                $STH1->execute($data);
                                            }
                                        } else {
                                            $data = array("src_app_id" => $appId, "webform_updated" => 3);
                                            $STH1->execute($data);
                                        }
                                    }
                                } else {
                                    $data = array("src_app_id" => $appId, "webform_updated" => 1);
                                    $STH1->execute($data);
                                }
                            }
                        } else {
                            $data = array("src_app_id" => $appId, "webform_updated" => 1);
                            $STH1->execute($data);
                        }
                    } catch (Exception $e) {
                        $data = array("src_app_id" => $appId, "webform_updated" => 4);
                        $STH1->execute($data);
                    }
                }
            }
        }
    }

    private
    function addWebForms()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(12)) {
            $sql = "select `src_app_id`,`dest_app_id`,`src_app_url`,`dest_app_url` from `apps` WHERE `webform_updated` IS NULL";
            $STH = DB::prepare($sql);
            $STH->execute();
            $sql1 = "UPDATE apps set webform_updated =:webform_updated where src_app_id =:src_app_id";
            $STH1 = DB::prepare($sql1);
            $sql2 = "SELECT dest_field_id FROM app_fields WHERE src_field_id=:src_field_id";
            $STH2 = DB::prepare($sql2);
            $sql3 = "SELECT dest_app_id FROM apps WHERE src_app_id=:src_app_id";
            $STH3 = DB::prepare($sql3);
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $app) {
                    $appId = $app['src_app_id'];
                    try {
                        //                        $repo->authenticate(1);
                        $forms = Podio::get("/form/app/$appId/")->json_body();
                        if (count($forms) > 0) {
                            foreach ($forms as $form) {
                                if ($form['status'] == "active") {
                                    $newSettings = array();
                                    print_r($app['src_app_url']);
                                    echo "<br>";
                                    print_r($app['dest_app_url']);
                                    echo "<br>";
                                    $newSettings['settings'] = $form['settings'];
                                    $newSettings['domains'] = $form['domains'];
                                    $newSettings['attachments'] = $form['attachments'];
                                    $newSettings['fields'] = array();
                                    foreach ($form['fields'] as $fields) {
                                        $srcFieldId = $fields['field_id'];
                                        $STH2->execute(array(
                                            "src_field_id" => $srcFieldId
                                        ));
                                        $result1 = $STH2->fetchAll(PDO::FETCH_ASSOC);
                                        if ($result1 && count($result1) > 0 && !is_null($result1[0]['dest_field_id'])) {
                                            if (is_array($fields['settings'])) {
                                                $newFieldSettings = array();
                                                $newFieldSettings['references'] = array();
                                                foreach ($fields['settings'] as $setting) {
                                                    if (isset($setting['subfields'])) {
                                                        foreach ($setting['subfields'] as $ref) {
                                                            $STH2->execute(array(
                                                                "src_field_id" => $ref
                                                            ));
                                                            $result2 = $STH2->fetchAll(PDO::FETCH_ASSOC);
                                                            if ($result2 && count($result2) > 0 && !is_null($result2[0]['dest_field_id'])) {
                                                                $newFieldSettings['references']['subfields'][] = $result2[0]['dest_field_id'];
                                                            }
                                                        }
                                                    }
                                                    if (isset($setting['app_id'])) {
                                                        $STH3->execute(array(
                                                            "src_app_id" => $setting['app_id']
                                                        ));
                                                        $newApp = $STH3->fetchAll(PDO::FETCH_ASSOC);
                                                        if ($newApp && count($newApp) > 0 && !is_null($newApp[0]['dest_app_id'])) {
                                                            $newFieldSettings['references']['app_id'] = $newApp[0]['dest_app_id'];
                                                        }
                                                    }
                                                    if (isset($setting['method']))
                                                        $newFieldSettings['references']['method'] = $setting['method'];
                                                }
                                            }
                                            $newSettings['fields'][] = array(
                                                "field_id" => (int)$result1[0]['dest_field_id'],
                                                "settings" => $fields["settings"]
                                            );
                                        }
                                    }
                                    //                                    print_r($newSettings);
                                    //                                    exit;
                                    //                                    Podio::shutdown();
                                    //                                    $resp = $repo->authenticateSF(6);
                                    //                                    print_r($resp);
                                    echo "<br>";
                                    echo "<br>";
                                    $dest = $app['dest_app_id'];
                                    $newForms = Podio::get("/form/app/$dest/")->json_body();
                                    if (count($newForms) > 0) {
                                        foreach ($newForms as $newForm) {
                                            $formId = $newForm['form_id'];
                                            \PodioForm::update($formId, $newSettings);
                                            $STH1->execute(array("src_app_id" => $appId, "webform_updated" => 5));
                                        }
                                    } else {
                                        \PodioForm::create($app['dest_app_id'], $newSettings);
                                        $STH1->execute(array("src_app_id" => $appId, "webform_updated" => 1));
                                    }
                                    //                                    exit;
                                } else {
                                    $STH1->execute(array("src_app_id" => $appId, "webform_updated" => 3));
                                }
                            }
                        } else {
                            $STH1->execute(array("src_app_id" => $appId, "webform_updated" => 2));
                        }
                    } catch (Exception $e) {
                        $STH1->execute(array("src_app_id" => $appId, "webform_updated" => 4));
                        //                        print_r($e);
                        //                        exit;
                    }
                }
            }
        } else {
            echo "No auth";
        }
    }

    private
    function getWebForms()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $sql = "select `src_app_url`,`src_app_id`,`dest_app_id` from `apps`";
            $STH = DB::prepare($sql);
            $STH->execute();
            $sql1 = "UPDATE apps set webform_updated =1 where src_app_id =:src_app_id";
            $STH1 = DB::prepare($sql1);
            $sql2 = "SELECT dest_field_id FROM app_fields WHERE src_field_id=:src_field_id";
            $STH2 = DB::prepare($sql2);
            $sql3 = "SELECT dest_app_id FROM apps WHERE src_app_id=:src_app_id";
            $STH3 = DB::prepare($sql3);
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $app) {
                    $repo->authenticate(1);
                    $appId = $app['src_app_id'];
                    try {
                        $forms = Podio::get("/form/app/$appId/")->json_body();
                        if (count($forms) > 0) {
                            echo $appId . "<br>";
                            foreach ($forms as $form) {
                                if ($form['status'] == "active") {
                                    $newSettings = array();
                                    //                                    print_r($appId);
                                    //                                    print_r($form);
                                    $newSettings['settings'] = $form['settings'];
                                    $newSettings['domains'] = $form['domains'];
                                    $newSettings['attachments'] = $form['attachments'];
                                    $newSettings['fields'] = array();
                                    foreach ($form['fields'] as $fields) {
                                        $srcFieldId = $fields['field_id'];
                                        $STH2->execute(array(
                                            "src_field_id" => $srcFieldId
                                        ));
                                        $result1 = $STH2->fetchAll(PDO::FETCH_ASSOC);
                                        if ($result1 && count($result1) > 0 && !is_null($result1[0]['dest_field_id'])) {
                                            if (is_array($fields['settings'])) {
                                                $newFieldSettings = array();
                                                $newFieldSettings['references'] = array();
                                                foreach ($fields['settings'] as $setting) {
                                                    if (isset($setting['subfields'])) {
                                                        foreach ($setting['subfields'] as $ref) {
                                                            $STH2->execute(array(
                                                                "src_field_id" => $ref
                                                            ));
                                                            $result2 = $STH2->fetchAll(PDO::FETCH_ASSOC);
                                                            if ($result2 && count($result2) > 0 && !is_null($result2[0]['dest_field_id'])) {
                                                                $newFieldSettings['references']['subfields'][] = $result2[0]['dest_field_id'];
                                                            }
                                                        }
                                                    }
                                                    if (isset($setting['app_id'])) {
                                                        $STH3->execute(array(
                                                            "src_app_id" => $setting['app_id']
                                                        ));
                                                        $newApp = $STH3->fetchAll(PDO::FETCH_ASSOC);
                                                        if ($newApp && count($newApp) > 0 && !is_null($newApp[0]['dest_app_id'])) {
                                                            $newFieldSettings['references']['app_id'] = $newApp[0]['dest_app_id'];
                                                        }
                                                    }
                                                    $newFieldSettings['references']['method'] = $setting['method'];
                                                }
                                                $newSettings['fields'][] = array(
                                                    "field_id" => (int)$result1[0]['dest_field_id'],
                                                    "settings" => $newFieldSettings
                                                );
                                            } else
                                                $newSettings['fields'][] = array(
                                                    "field_id" => (int)$result1[0]['dest_field_id'],
                                                    "settings" => $fields["settings"]
                                                );
                                        }
                                    }
                                    //                                    print_r($newSettings);
                                    //                                    exit;
                                    //                                    Podio::shutdown();
                                    $resp = $repo->authenticateSF(2);
                                    //                                    print_r($resp);
                                    \PodioForm::create($app['dest_app_id'], $newSettings);
                                    $STH1->execute(array("src_app_id" => $appId));
                                    //                                    exit;
                                }
                            }
                        }
                    } catch (Exception $e) {
                        print_r($e);
                        //                        exit;
                    }
                }
            }
        } else {
            echo "No auth";
        }
    }


    private
    function addFlows()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();

        $z = 0;
        $sql = "select `dest_space_id`,`src_app_id`,`src_space_id`,`dest_app_url`,`flows`,`dest_app_id` from `apps` WHERE `flows` !=:val";
        $STH = DB::prepare($sql);
        $STH->execute(array("val" => "[]"));
        $result = $STH->fetchAll(PDO::FETCH_ASSOC);
        $sql1 = "select `dest_app_id`,`dest_field_id`,`src_field_external_id`,`dest_field_external_id`,`status` from `app_fields` WHERE `src_field_id`=:src_field_id";
        $STH1 = DB::prepare($sql1);
        $sql2 = "select `dest_field_external_id`,`status` from `app_fields` WHERE `src_field_external_id`=:src_field_external_id AND `src_app_id`=:src_app_id";
        $STH2 = DB::prepare($sql2);
        $repo->authenticateSF(2);
        if ($result && count($result) > 0) {
            foreach ($result as $app) {
                $z++;
                Log::log("addFlows  - $z", $app);
                $appId = $app['src_app_id'];
                $destAppId = $app['dest_app_id'];
                //                $repo->authenticate(1);
                //                $flows = $this->customPodioAPI->podioGet("/flow/app/$appId/");
                $flows = json_decode($app['flows'], true);
                if (count($flows) > 0) {
                    //                    $newFlows = PodioFlow::get_flows('app', $destAppId);
                    //                    if ($newFlows != null)
                    //                        foreach ($newFlows as $newFlow) {
                    //                            $flowId = $newFlow['flow_id'];
                    //                            PodioFlow::delete($flowId);
                    //                        }
                    foreach ($flows as $flow) {
                        echo "<pre>";
                        //                        print_r($flow);
                        $newFlow = array();
                        $newFlow['type'] = $flow['type'];
                        $newFlow['name'] = $flow['name'];
                        $newFlow['config'] = array();
                        if (!empty($flow['config']['field_ids'])) {
                            if (is_array($flow['config']['field_ids']) or ($flow['config']['field_ids'] instanceof Traversable)) {
                                $newFlow['config']['field_ids'] = array();
                                foreach ($flow['config']['field_ids'] as $fieldId) {
                                    try {
                                        $data = array("src_field_id" => $fieldId);
                                        $STH1->execute($data);
                                        $fieldResults = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                        $newFieldId = $fieldResults[0]['dest_field_id'];
                                        if ($fieldResults[0]['status'] == "active")
                                            array_push($newFlow['config']['field_ids'], $newFieldId);
                                    } catch (Exception $e) {
                                        Log::logError($e . "", array('app' => $appId, 'space' => $app['src_space_id']), "flowClone");
                                        //                                            print_r($appId . "FLOW ERROR");
                                        //                                            echo "<br>";
                                    }
                                }
                            }
                        }
                        if (!empty($flow['config']['conditions'])) {
                            if (is_array($flow['config']['conditions']) or ($flow['config']['conditions'] instanceof Traversable)) {
                                $newFlow['config']['conditions'] = array();
                                foreach ($flow['config']['conditions'] as $condition) {
                                    try {
                                        $data = array("src_field_id" => $fieldId);
                                        $STH1->execute($data);
                                        $fieldResults = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                        $newFieldId = $fieldResults[0]['dest_field_id'];
                                        $condition['field_id'] = $newFieldId;
                                        if ($fieldResults[0]['status'] == "active")
                                            array_push($newFlow['config']['conditions'], $condition);
                                    } catch (Exception $e) {
                                        Log::logError($e . "", array('app' => $appId, 'space' => $app['src_space_id']), "flowClone");
                                        //                                            print_r($appId . "FLOW ERROR");
                                        //                                            echo "<br>";
                                    }
                                }
                            }
                        }
                        $newFlow['effects'] = array();
                        foreach ($flow['effects'] as $effect) {
                            $addEffect = true;
                            $newEffect = array();
                            $newEffect['type'] = $effect['type'];
                            $newEffect['attributes'] = $effect['attributes'];
                            if ($newEffect['type'] == "task.create") {
                                $assignedUser = $effect['attributes'][1]['value'];
                                $linkRepo = new LinkReplaceRepo();
                                $assignedUser = $linkRepo->getNewUser($assignedUser);
                                $newEffect['attributes'][1]['value'] = $assignedUser;
                                if (is_numeric($assignedUser)) {
                                    try {
                                        $spaceUser = PodioSpaceMember::get($app['dest_space_id'], $assignedUser);
                                        if (is_null($spaceUser->role)) {
                                            $newEffect['attributes'][1] = array(
                                                "nullable" => false,
                                                "required" => false,
                                                "value" => "{{global.auth}}",
                                                "label" => "Assign to",
                                                "attribute_id" => "task.responsible",
                                                "substitutions" => array(
                                                    "{{global.auth}}" => "Current user or app"
                                                ),
                                                "type" => "user"
                                            );
                                        }
                                    } catch (Exception $e) {
                                        Log::logError($e . "", array('app' => $appId, 'space' => $app['src_space_id']), "flowClone");
                                        print_r($appId . "FLOW ERROR");
                                        echo "<br>";
                                        $newEffect['attributes'][1] = array(
                                            "nullable" => false,
                                            "required" => false,
                                            "value" => "{{global.auth}}",
                                            "label" => "Assign to",
                                            "attribute_id" => "task.responsible",
                                            "substitutions" => array(
                                                "{{global.auth}}" => "Current user or app"
                                            ),
                                            "type" => "user"
                                        );
                                    }
                                }
                            }
                            foreach ($newEffect['attributes'] as $arrayIndex => $attribute) {
                                foreach ($attribute as $index => $value) {
                                    if ($value == "" || (is_array($value) && count($value) == 0)) {
                                        if ($index == "nullable" || $index == "required")
                                            $newEffect['attributes'][$arrayIndex][$index] = 0;
                                        elseif ($index != "substitutions" && $index != "value")
                                            unset($newEffect['attributes'][$arrayIndex][$index]);
                                    }
                                    if (!is_array($value) && strpos($value, 'item.field') !== false) {
                                        if (preg_match_all("(item.field.([a-z-\d]*))", $value, $matches)) {
                                            foreach ($matches[1] as $matchIndex => $match) {
                                                $data = array("src_field_external_id" => $match, "src_app_id" => $appId);
                                                if ($newEffect['type'] == "item.create" && $index == "attribute_id") {
                                                    $data = array("src_field_external_id" => $match, "src_app_id" => $effect['config']['app']['app_id']);
                                                }
                                                $STH2->execute($data);
                                                $fieldResults = $STH2->fetchAll(PDO::FETCH_ASSOC);
                                                if (isset($fieldResults[0]) && $fieldResults[0]['dest_field_external_id'] != "") {
                                                    $newFieldId = $fieldResults[0]['dest_field_external_id'];
                                                    $newEffect['attributes'][$arrayIndex][$index] = str_replace($match, $newFieldId, $newEffect['attributes'][$arrayIndex][$index]);
                                                } else {
                                                    $data = array("src_field_external_id" => $match, "src_app_id" => $effect['config']['app']['app_id']);
                                                    $STH2->execute($data);
                                                    $fieldResults = $STH2->fetchAll(PDO::FETCH_ASSOC);
                                                    if (isset($fieldResults[0]) && $fieldResults[0]['dest_field_external_id'] != "") {
                                                        $newFieldId = $fieldResults[0]['dest_field_external_id'];
                                                        $newEffect['attributes'][$arrayIndex][$index] = str_replace($match, $newFieldId, $newEffect['attributes'][$arrayIndex][$index]);
                                                    } else {
                                                        unset($newEffect['attributes'][$arrayIndex]);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (is_array($value)) {
                                        foreach ($value as $index1 => $string) {
                                            if (strpos($index1, 'item.field') !== false) {
                                                if (preg_match_all("(item.field.([a-z-\d]*))", $index1, $matches)) {
                                                    foreach ($matches[1] as $matchIndex => $match) {
                                                        $data = array("src_field_external_id" => $match, "src_app_id" => $appId);
                                                        $STH2->execute($data);
                                                        $fieldResults = $STH2->fetchAll(PDO::FETCH_ASSOC);
                                                        $newFieldId = $fieldResults[0]['dest_field_external_id'];
                                                        if ($fieldResults[0]['dest_field_external_id'] != "") {
                                                            $newEffect['attributes'][$arrayIndex][$index]['{{item.field.' . $newFieldId . '}}'] = $newEffect['attributes'][$arrayIndex][$index][$index1];
                                                            if ($newFieldId != $match)
                                                                unset($newEffect['attributes'][$arrayIndex][$index][$index1]);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if ($index == "field_id") {
                                        $data = array("src_field_id" => $value);
                                        $STH1->execute($data);
                                        $fieldResults = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                        if ($fieldResults[0]['status'] == "active")
                                            $newEffect['attributes'][$arrayIndex][$index] = $fieldResults[0]['dest_field_id'];
                                    }
                                }
                                //                                print_r($newEffect);
                            }
                            //                            exit;
                            $newEffect['attributes'] = array_values($newEffect['attributes']);
                            if (array_key_exists('config', $effect) && $effect['config'] != null) {
                                $newEffect['config'] = $effect['config'];
                                if (is_array($newEffect['config'])) {
                                    $oldRefFieldId = $newEffect['config']['field']['field_id'];
                                    $newFieldId = "";
                                    $appIdToUse = "";
                                    try {
                                        $data = array("src_field_id" => $oldRefFieldId);
                                        $STH1->execute($data);
                                        $fieldResults = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                        $newFieldId = $fieldResults[0]['dest_field_id'];
                                        $appIdToUse = $fieldResults[0]['dest_app_id'];


                                        //                                            $newAppDetails = PodioApp::get($app['dest_app_id'], array('type' => 'Mini'));
                                        $destAppIdtoUse = $app['dest_app_id'];
                                        $newAppDetails = $this->customPodioAPI->podioGet("/app/$appIdToUse/");
                                        //                                            $newFieldDetails = PodioAppField::get($appIdToUse, $newFieldId);
                                        $newFieldDetails = $this->customPodioAPI->podioGet("/app/{$appIdToUse}/field/{$newFieldId}");
                                        $newEffect['config']['field'] = array(
                                            "type" => $newFieldDetails["type"],
                                            "config" => array(
                                                "label" => $newFieldDetails["config"]["label"],
                                                "settings" => array(
                                                    "referenced_apps" => array(
                                                        array(
                                                            "view_id" => $newFieldDetails["config"]["settings"]["referenced_apps"][0]["view_id"],
                                                            "app_id" => $newFieldDetails["config"]["settings"]["referenced_apps"][0]["app_id"]
                                                        )

                                                    ),
                                                    "referenceable_types" => $newFieldDetails["config"]["settings"]["referenceable_types"]

                                                )
                                            ),
                                            "external_id" => $newFieldDetails["external_id"],
                                            "field_id" => $newFieldDetails["field_id"],
                                            "label" => $newFieldDetails["label"]
                                        );
                                        $newEffect['config']['app'] = array(
                                            "status" => $newAppDetails["status"],
                                            "sharefile_vault_url" => $newAppDetails["sharefile_vault_url"],
                                            "default_view_id" => $newAppDetails["default_view_id"],
                                            "url_label" => $newAppDetails["url_label"],
                                            "space_id" => $newAppDetails["space_id"],
                                            "link_add" => $newAppDetails["link_add"],
                                            "app_id" => $newAppDetails["app_id"],
                                            "current_revision" => $newAppDetails["current_revision"],
                                            "is_default" => $newAppDetails["is_default"],
                                            "link" => $newAppDetails["link"],
                                            "url" => $newAppDetails["url"],
                                            "item_accounting_info" => $newAppDetails["item_accounting_info"],
                                            "config" => array(
                                                "item_name" => $newAppDetails["config"]["item_name"],
                                                "icon_id" => $newAppDetails["config"]["icon_id"],
                                                "type" => $newAppDetails["config"]["type"],
                                                "name" => $newAppDetails["config"]["name"],
                                                "icon" => $newAppDetails["config"]["icon"]
                                            ),
                                        );
                                        $newEffect['config']["field_id"] = $newFieldDetails["field_id"];
                                        $newEffect['config']["app_id"] = $newAppDetails["app_id"];
                                    } catch (Exception $e) {
                                        Log::logError($e . "", array('app' => $appId, 'space' => $app['src_space_id']), "flowClone");
                                        //                                            print_r($appId . "FLOW ERROR");
                                        //                                            echo "<br>";
                                        //                                            print_r($e);
                                        //                                            exit;
                                        $addEffect = false;
                                    }
                                }
                            }
                            if ($addEffect)
                                array_push($newFlow['effects'], $newEffect);
                        }

                        if (isset($newFlow)) {
                            if (array_key_exists('ref', $flow) && $flow['ref'] != null) {
                                //                                    $newFlow['ref'] = array(
                                //                                        "type" => "app",
                                //                                        "id" => $newFieldDetails["config"]["settings"]["referenced_apps"][0]["app_id"]
                                //                                    );
                            }
                            $newFlow = (array)$newFlow;
                            $newFlow = array_filter($newFlow);
                            $newFlow = (array)$newFlow;
                            try {
                                //                                    print_r($newFlow);
                                //                                print_r(PodioUserStatus::get());
                                //                                    exit;
                                //                                    print_r($newFlow);
                                //                                    print_r($flow);
                                $resp = PodioFlow::create('app', $app['dest_app_id'], $newFlow);
                                //                                print_r($flow);
                                //                                    print_r($newFlow);
                                //                                    print_r("Updated app flow " . $app['dest_app_id']);
                                echo "<br>";
                            } catch (Exception $e) {
                                Log::logError($e . "", array('app' => $appId, 'space' => $app['src_space_id']), "flowClone");
                                //                                    print_r($newFlow);
                                print_r($app["dest_app_url"] . "FLOW ERROR" . $newFlow['name']);
                                echo "<br>";
                            }
                        }
                        //                        }
                    }
                }
                //                Podio::shutdown();
                //                exit;
            }
        }
    }


    private
    function updateSpaceWidget()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            // if ($repo->authenticateSF(2)) {
            $sql = "select `src_space_id`,`widgets`,`dest_space_id` from `work_spaces` WHERE `widgets_created` IS NULL ";
            $STH = DB::prepare($sql);
            $STH->execute();
            $sql1 = "UPDATE work_spaces set widgets_created =1 where src_space_id =:src_space_id";
            $STH1 = DB::prepare($sql1);
            $allowedTypes = array("link", "text", "files", "events", "tasks", "image");
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $space) {
                    try {
                        $spaceId = $space['src_space_id'];
                        $destSpaceId = $space['dest_space_id'];
                        $widgets = $space['widgets'];
                        $widgets = json_decode($widgets);
                        $newWidgets = $this->customPodioAPI->podioGet("/widget/space/" . $destSpaceId);
                        foreach ($newWidgets as $newWidget) {
                            //                            if ($newWidget['type'] == "tasks" || $newWidget['type'] == "events")
                            PodioWidget::delete($newWidget['widget_id']);
                        }
                        if (count($widgets) > 0)
                            foreach ($widgets as $widget) {
                                $widget = (array)$widget;
                                if (in_array($widget['type'], $allowedTypes)) {
                                    if ($widget['type'] == "image") {

                                        $fileDetails = PodioFile::get($widget['config']->file_id);

                                        $destinationPath = '/var/www/podiomigration.bitkit.dk/httpdocs/public/assets/' . $fileDetails->name;
                                        $fileContent = $fileDetails->get_raw();
                                        file_put_contents($destinationPath, $fileContent);

                                        $podioFileCreateResponse = PodioFile::upload($destinationPath,  basename($destinationPath));
                                        $newFileId = $podioFileCreateResponse->file_id;

                                        $newWidgetConfig = array();
                                        $newWidgetConfig = [
                                            'type' => 'image',
                                            'title' => $widget['title'],
                                            'config' => [
                                                'file_id' => $newFileId
                                            ],
                                        ];

                                        unlink($destinationPath);
                                    } else {
                                        $newWidgetConfig = array();
                                        $newWidgetConfig['type'] = $widget['type'];
                                        $newWidgetConfig['title'] = $widget['title'];
                                        $newWidgetConfig['config'] = $widget['config'];
                                    }
                                    try {
                                        Podio::post("/widget/space/$destSpaceId", $newWidgetConfig);
                                    } catch (Exception $e) {
                                        Log::logError($e . "", $newWidgetConfig, "Widget Creation Error");
                                    }
                                }
                            }
                        $data = array("src_space_id" => $spaceId);
                        $STH1->execute($data);
                    } catch (Exception $e) {
                        Log::logError($e . "", null, "Widget Creation Error");
                    }
                }
            }
        }
    }

    private
    function DeleteMultipleSpaceWidget()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $sql = "select `src_space_id`,`widgets`,`dest_space_id` from `work_spaces` WHERE `alert_status_added` IS NOT NULL ";
            $STH = DB::prepare($sql);
            $STH->execute();
            $allowedTypes = array("image");
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $space) {
                    try {
                        $spaceId = $space['src_space_id'];
                        $newWidgets = $this->customPodioAPI->podioGet("/widget/space/" . $spaceId);
                        if ($newWidgets[0]['title'] == "IMPORTANT NOTIFICATION")
                            PodioWidget::delete($newWidgets[0]['widget_id']);
                    } catch (Exception $e) {
                    }
                }
            }
        }
    }

    private
    function addWarningWidget()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(20)) {
            $sql = "select `src_space_id`,`widgets`,`src_space_url` from `work_spaces` WHERE `id`!=1";
            $STH = DB::prepare($sql);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {

                foreach ($result as $space) {
                    try {
                        $newWidgetOrder = array();
                        $spaceId = $space['src_space_id'];
                        $widgetsNew = PodioWidget::get_for('space', $spaceId);
                        foreach ($widgetsNew as $newWidget) {
                            $newWidgetOrder[] = $newWidget->widget_id;
                        }
                        $attributes = array();
                        $attributes['type'] = "image";
                        $attributes['title'] = "IMPORTANT NOTIFICATION";
                        $fileId = PodioFile::upload('/var/www/podiomigration.bitkit.dk/httpdocs/public/assets/unnamed.png', "warning.png");
                        $fileCopy = PodioFile::copy($fileId->file_id);
                        $attributes['config']['file_id'] = $fileCopy->file_id;
                        $resp = Podio::post("/widget/space/$spaceId/", $attributes);
                        $widgetBody = json_decode($resp->body);
                        array_unshift($newWidgetOrder, $widgetBody->widget_id);
                        print_r($space['src_space_url']);
                        echo "<br>";
                        PodioWidget::update_order("space", $spaceId, $newWidgetOrder);
                    } catch (Exception $e) {
                        print_r($e);
                    }
                }
            }
        }
    }

    private
    function addStatusToAllSpace()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(20)) {
            $sql = "select `src_space_id`,`src_name` from `work_spaces` WHERE `id`!=1";
            $STH = DB::prepare($sql);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {

                foreach ($result as $space) {
                    try {
                        $streamAttributes['value'] = "Hej IN bruger @[" . $space['src_name'] . "](space:" . $space['src_space_id'] . ")
IN's Podio-løsning er ved at blive opdateret og ændringer foretaget i mellemtiden vil ikke blive gemt. 
Undlad at bruge Podio indtil opdateringen er gennemført. Vi kommunikerer til alle, når vi er klar.
Podio projektgruppen";
                        $statusID = PodioStatus::create($space['src_space_id'], $streamAttributes);
                    } catch (Exception $e) {
                        print_r($e);
                    }
                }
            }
        }
    }


    private
    function updateSpaceWidgetLink()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        $linkRepo = new LinkReplaceRepo();
        //        if ($repo->authenticate(9)) {//
        if ($repo->authenticateSF(21)) {
            $sql = "select `src_space_id`,`widgets`,`dest_space_id` from `work_spaces` WHERE `widgets_created` IS NOT NULL ";
            $STH = DB::prepare($sql);
            $STH->execute();
            $allowedTypes = array("link", "text");
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $space) {
                    try {
                        $destSpaceId = $space['dest_space_id'];
                        $newWidgets = $this->customPodioAPI->podioGet("/widget/space/" . $destSpaceId);
                        foreach ($newWidgets as $newWidget) {
                            $newAttributes = array();
                            if (in_array($newWidget['type'], $allowedTypes)) {
                                $newAttributes['title'] = $newWidget['title'];
                                $newAttributes['config'] = $newWidget['config'];
                                switch ($newWidget['type']) {
                                    case "text":
                                        $newAttributes['config']['text'] = $linkRepo->replaceLinks($newAttributes['config']['text'], 1);
                                        break;
                                    case "link":
                                        foreach ($newAttributes['config']['links'] as $k => $link) {
                                            $newAttributes['config']['links'][$k]['url'] = $linkRepo->replaceLinks($link['url'], 1);
                                        }
                                        break;
                                }
                                PodioWidget::update($newWidget['widget_id'], $newAttributes);
                            }
                        }
                    } catch (Exception $e) {
                        print_r($e);
                    }
                }
            }
        }
    }

    private
    function saveSpaceContacts($spaceId)
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $sql = "INSERT INTO `workspace_contacts` (`src_space_id`,`profile_id`,`fields`) VALUES (:src_space_id, :profile_id,
             :fields)";

            $STH = DB::prepare($sql);
            $contacts = Podio::get("/contact/space/$spaceId/?contact_type=space&exclude_self=true&order=name")->json_body();
            foreach ($contacts as $contact) {
                $profile_id = '';
                $src_space_id = '';
                foreach ($contact as $type => $values) {
                    switch ($type) {
                        case "profile_id":
                            $profile_id = $values;
                            break;
                        case "space_id":
                            $src_space_id = (int)$values;
                            break;
                    }
                }
                $data = array("src_space_id" => $src_space_id, "profile_id" => $profile_id, "fields" => $contacts);
                $STH->execute($data);
            }
            $STH = NULL;
        }
    }

    private
    function createSpaceContacts($spaceId, $targetSpaceId)
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        $spaceContactAppId = 18365579;
        if ($repo->authenticate(1)) {
            $resp = PodioApp::install($spaceContactAppId, $attributes = array(
                "space_id" => $targetSpaceId,
                "features" => array('filters')
            ));
            $sql = "select `id`,`fields` from `workspace_contacts` WHERE `src_space_id`=:src_space_id";
            $STH = DB::prepare($sql);
            $sql1 = "UPDATE workspace_contacts set item_id =:item_id where id =:id";
            $STH1 = DB::prepare($sql1);
            $data = array("src_space_id" => $spaceId);
            $STH->execute($data);
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $contacts) {
                    foreach ($contacts as $contact) {
                        $podioFields = array();
                        foreach ($contact['fields'] as $type => $values) {
                            switch ($type) {
                                case "mail":
                                    foreach ($values as $value) {
                                        $podioFields['email-address'][] = array("type" => "work", "value" => $value);
                                    }
                                    break;
                                case "phone":
                                    foreach ($values as $value) {
                                        $podioFields['phone-number'][] = array("type" => "work", "value" => $value);
                                    }
                                    break;
                                case "image":
                                    try {
                                        $fileID = PodioFile::copy($values->file_id);
                                        if (isset($fileID))
                                            $podioFields["photo"][] = array("value" => $fileID->file_id);
                                    } catch (Exception $e) {
                                        log::error("No rights to add prev file");
                                    }
                                    break;
                                case "profile_id":
                                    $podioFields["profile-id"] = $values;
                                    break;
                                case "skype":
                                    $podioFields["skype-id"] = $values;
                                    break;
                                case "city":
                                    $podioFields["city"] = $values;
                                    break;
                                case "name":
                                    $podioFields["name"] = $values;
                                    break;
                                case "zip":
                                    $podioFields["post-code"] = $values;
                                    break;
                                case "state":
                                    $podioFields["stateprovince"] = $values;
                                    break;
                                case "country":
                                    $podioFields["country"] = $values;
                                    break;
                                case "about":
                                    $podioFields["notes"] = $values;
                                    break;
                                case "space_id":
                                    $podioFields["source-space-id"] = (int)$values;
                                    break;
                                case "link":
                                    $podioFields["source-profile-link"] = $values . '';
                                    break;
                                case "url":
                                    foreach ($values as $value) {
                                        try {
                                            $fileID = PodioEmbed::create($attributes = array("url" => $value));
                                            if (isset($fileID))
                                                $podioFields["website"][] = array("embed" => $fileID->embed_id);
                                        } catch (Exception $e) {
                                            log::error("No rights to add prev file");
                                        }
                                    }
                                    break;
                                case "title":
                                    $text = "";
                                    foreach ($values as $value) {
                                        $text .= $value . PHP_EOL;
                                    }
                                    $podioFields["job-title"] = $text;
                                    break;
                                case "address":
                                    foreach ($values as $value) {
                                        $podioFields['address'][] = $value;
                                    }
                                    break;
                                case "organization":
                                    $podioFields['organisation'][] = $values;
                                    break;
                            }
                        }
                        $podioAttributes = array('fields' => $podioFields);
                        $response = PodioItem::create($resp->app_id, $podioAttributes, array('silent' => true));
                        $item_id = $response->item_id;
                        $STH1->execute(array("id" => $contact['id'], "item_id" => $item_id));
                    }
                }
            }
        }
    }

    private
    function saveAppViews()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(8)) {
            $sql = "select `src_app_id` from `apps`";
            $STH = DB::prepare($sql);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $app) {
                    $appId = $app['src_app_id'];
                    $sql1 = "INSERT INTO `app_views` (`src_app_id`,`src_view_d`,`fields`,`view_type`) VALUES (:src_app_id, :src_view_d,:fields,
             :view_type)";
                    $STH1 = DB::prepare($sql1);
                    $views = Podio::get("/view/app/{$appId}/")->json_body();
                    foreach ($views as $view) {
                        $data = array("src_app_id" => $appId, "src_view_d" => $view['view_id'], "fields" => json_encode($view), "view_type" => $view["type"]);
                        $STH1->execute($data);
                    }
                    $STH1 = NULL;
                }
            }
        }
    }

    private
    function deleteAppViews()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        //        if ($repo->authenticate(2)) {
        if ($repo->authenticateSF(2)) {
            $sql = "select `dest_app_id` from `apps`";
            $STH = DB::prepare($sql);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $app) {
                    $appId = $app['dest_app_id'];
                    $views = Podio::get("/view/app/{$appId}/")->json_body();
                    foreach ($views as $view) {
                        PodioView::delete($view['view_id']);
                    }
                }
            }
        }
    }

    private
    function deleteFlows()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        //        if ($repo->authenticate(2)) {
        if ($repo->authenticateSF(2)) {
            $sql = "select `dest_app_id` from `apps`";
            $STH = DB::prepare($sql);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $app) {
                    $appId = $app['dest_app_id'];
                    $flows = $this->customPodioAPI->podioGet("/flow/app/$appId/");
                    if (count($flows) > 0)
                        foreach ($flows as $flow) {
                            PodioFlow::delete($flow['flow_id']);
                        }
                }
            }
        }
    }

    private
    function updateAppViews()
    {
        echo "<pre>";
        $sql = "select `src_app_id`,`dest_app_id` from `apps`";
        $STH = DB::prepare($sql);
        $STH->execute();
        $result = $STH->fetchAll(PDO::FETCH_ASSOC);
        $sql1 = "UPDATE `app_views` SET `dest_app_id`=:dest_app_id WHERE src_app_id=:src_app_id";
        $STH1 = DB::prepare($sql1);
        echo "<pre>";
        //        print_r($result);
        //        exit;
        if ($result && count($result) > 0) {
            foreach ($result as $app) {
                $appId = $app['src_app_id'];
                $destAppId = $app['dest_app_id'];
                $STH1->execute(array("src_app_id" => $appId, "dest_app_id" => $destAppId));
            }
        }
        $STH1 = NULL;
    }

    private
    function recreateAppViews()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            // if ($repo->authenticateSF(2)) { // if ($repo->authenticateSF(6)) {
            $sql = "select `id`,`fields`,`src_app_id`,`dest_app_id` from `app_views` WHERE created_view_id IS NULL AND view_type != 'private'"; //WHERE created_view_id IS NULL
            $STH = DB::prepare($sql);
            $sql1 = "select `dest_field_id`,`field_type` from `app_fields` WHERE `src_field_id`=:src_field_id";
            $STH1 = DB::prepare($sql1);
            $sql2 = "UPDATE app_views set created_view_id =:created_view_id where id =:id";
            $STH2 = DB::prepare($sql2);
            $sql3 = "UPDATE app_views set error =:error where id =:id";
            $STH3 = DB::prepare($sql3);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $dbView) {
                    try {
                        $dbId = $dbView['id'];
                        $targetAppId = $dbView['dest_app_id'];
                        $view = (array)json_decode($dbView['fields']);
                        $createView = true;
                        unset($view['view_id']);
                        unset($view['created_by']);
                        unset($view['created_on']);
                        unset($view['filter_id']);
                        unset($view['groupings']);
                        unset($view['items']);
                        $view = array_filter($view);
                        if (isset($view['sort_by'])) {
                            $data = array("src_field_id" => $view['sort_by']);
                            $STH1->execute($data);
                            $fieldResults = $STH1->fetchAll(PDO::FETCH_ASSOC);
                            if (isset($fieldResults[0])) {
                                $view['sort_by'] = $fieldResults[0]['dest_field_id'];
                            }
                        }
                        if (isset($view['fields']) && !empty($view['fields']) && count($view['fields']) > 0) {
                            $view['fields'] = (array)$view['fields'];
                            $view['newFields'] = array();
                            foreach ($view['fields'] as $key => $fields) {
                                $data = array("src_field_id" => $key);
                                $STH1->execute($data);
                                $fieldResults = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                if (isset($fieldResults[0]['dest_field_id'])) {
                                    $destField = $fieldResults[0]['dest_field_id'];
                                    $view['newFields'][$destField] = $fields;
                                } else {
                                    //                                    echo "No dest field"."<br>";
                                }
                            }
                            $view['fields'] = $view['newFields'];
                        }
                        if (isset($view['grouping']) && !empty($view['grouping'])) {
                            $view['grouping'] = (array)$view['grouping'];
                            echo $view['grouping']['type'] . "<br>";
                            if ($view['grouping']['type'] == "voting") {
                                $createView = false;
                            } else if (isset($view['grouping']['value']) && is_numeric($view['grouping']['value'])) {
                                $data = array("src_field_id" => $view['grouping']['value']);
                                $STH1->execute($data);
                                $fieldResults = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                if (isset($fieldResults[0]['dest_field_id'])) {
                                    $view['grouping']['value'] = $fieldResults[0]['dest_field_id'];
                                } else {
                                    $createView = false;
                                }
                            }
                        }
                        if (isset($view['filters']) && !empty($view['filters'])) {
                            foreach ($view['filters'] as $k => $filter) {
                                $filter = (array)$filter;
                                if (isset($filter['key']) && is_numeric($filter['key'])) {
                                    $data = array("src_field_id" => $filter['key']);
                                    $STH1->execute($data);
                                    $fieldResults = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                    if (isset($fieldResults[0]['dest_field_id'])) {
                                        if ($fieldResults[0]['field_type'] != 'app' && $fieldResults[0]['field_type'] != 'calculation') {
                                            $view['filters'][$k]->key = $fieldResults[0]['dest_field_id'];
                                        } else
                                            unset($view['filters'][$k]);
                                    } else {
                                        unset($view['filters'][$k]);
                                    }
                                } elseif (strpos($filter['key'], "voting") !== false) {
                                    unset($view['filters'][$k]);
                                }
                            }
                            $view['filters'] = array_values($view['filters']);
                            if (!isset($view['grouping'])) {
                                $view['grouping'] = array();
                            }
                        }
                        if ($createView) {
                            if (!isset($view['sort_desc']))
                                $view['sort_desc'] = false;
                            $resp = PodioView::create($targetAppId, $view);
                            $viewId = $resp;
                            $STH2->execute(array("id" => $dbId, "created_view_id" => $viewId));
                        } else {
                            if (isset($dbId)) {
                                $STH3->execute(array("id" => $dbId, "error" => "Deleted/Complex fields in view"));
                            }
                        }
                    } catch (Exception $e) {
                        if (isset($dbId)) {
                            $STH3->execute(array("id" => $dbId, "error" => $e));
                        }
                    }
                }
            }
        }
    }

    private
    function addStatus()
    {
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $sql = "select `id`,`src_space_id`,`dest_space_url` from `work_spaces` WHERE alert_status_added IS NULL";
            $STH = DB::prepare($sql);
            $sql1 = "UPDATE work_spaces set alert_status_added =1 where id =:id";
            $STH1 = DB::prepare($sql1);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            $options = array('silent' => false, 'hook' => false);
            if ($result && count($result) > 0) {
                foreach ($result as $space) {
                    try {
                        $dbId = $space['id'];
                        $sourceSpaceId = $space['src_space_id'];
                        $destSpaceUrl = $space['dest_space_url'];
                        $status = array(
                            "value" => "A copy of this workspace is now created under LogMeIn organization. You can access the workspace using the link $destSpaceUrl. All the LogMeIn employees needs to use the new workspace under LogMeIn organization."
                        );
                        $statusID = PodioStatus::create($sourceSpaceId, $status, $options);
                        $STH1->execute(array("id" => $dbId));
                    } catch (Exception $e) {
                    }
                }
            }
        }
    }

    public
    function dateValue()
    {
        echo "<pre>";
        $sql = "SELECT * FROM `item_field_values` WHERE `type`=:type";
        $STH = DB::prepare($sql);
        $STH->execute(array(
            'type' => 'date'
        ));
        $result = $STH->fetchAll(PDO::FETCH_ASSOC);
        $sql1 = "SELECT dest_item_id FROM items WHERE src_item_id=:src_item_id";
        $STH1 = DB::prepare($sql1);
        $sql2 = "SELECT dest_field_external_id FROM app_fields WHERE src_field_id=:src_field_id";
        $STH2 = DB::prepare($sql2);
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(9)) { // if ($repo->authenticateSF(6)) {
            if ($result && count($result) > 0) {
                $fields = array();
                $repo = new ItemCreateRepo();
                foreach ($result as $field) {
                    list($value, $itemNeedToBeUpdated) = $repo->getFieldValue($field);
                    $STH1->execute(array(
                        'src_item_id' => $field['src_item_id']
                    ));
                    $result1 = $STH1->fetchAll(PDO::FETCH_ASSOC);
                    $STH2->execute(array(
                        'src_field_id' => $field['src_field_id']
                    ));
                    $result2 = $STH2->fetchAll(PDO::FETCH_ASSOC);
                    if ($result2 && count($result2) > 0) {
                        if ($result1 && count($result1) > 0) {
                            if ($value) {
                                $fields[$result2[0]['dest_field_external_id']] = $value;
                            }
                            //                            echo $result1[0]['dest_item_id'] . "<br>";
                            //                        print_r($fields);
                            try {
                                PodioItem::update($result1[0]['dest_item_id'], array("fields" => $fields));
                            } catch (Exception $e) {
                                echo $result1[0]['dest_item_id'] . "<br>";
                            }
                        }
                    }
                    //                    exit;
                }
            }
        } else {

            echo "No auth";
        }
    }

    private
    function updateAppConfig()
    {
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $sql = "SELECT src_app_id FROM apps";
            $STH = DB::prepare($sql);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            $sql1 = "UPDATE apps SET src_config=:src_config WHERE src_app_id=:src_app_id";
            $STH1 = DB::prepare($sql1);
            if ($result && count($result) > 0) {
                foreach ($result as $app) {
                    $appData = $this->customPodioAPI->podioGet("/app/" . $app['src_app_id'] . "/");
                    $data = array();
                    $data["src_app_id"] = $app['src_app_id'];
                    $data["src_config"] = json_encode($appData['config']);
                    $STH1->execute($data);
                }
            }
        }
    }

    private
    function setAppConfig()
    {
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(9)) { // if ($repo->authenticateSF(6)) {
            $sql = "SELECT src_config,dest_app_id,dest_app_url FROM apps";
            $STH = DB::prepare($sql);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $app) {
                    $config = json_decode($app['src_config']);
                    echo $app['dest_app_url'];
                    PodioApp::update($app['dest_app_id'], array("config" => $config));
                }
            }
        }
    }

    private
    function addCalculation()
    {
        try {
            echo "<pre>";
            $sql = "SELECT id,src_field_config,dest_app_id,label,src_delta FROM app_fields WHERE status=:status AND field_type=:field_type AND dest_field_id IS NULL";
            $STH = DB::prepare($sql);
            $STH->execute(array(
                "status" => "active",
                "field_type" => "calculation"
            ));
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            $sql1 = "SELECT dest_field_id,field_type FROM app_fields WHERE src_field_id=:src_field_id";
            $STH1 = DB::prepare($sql1);
            $sql2 = "UPDATE app_fields SET dest_delta=:dest_delta,dest_field_config=:dest_field_config,dest_field_external_id=:dest_field_external_id,dest_field_id=:dest_field_id WHERE id=:id";
            $STH2 = DB::prepare($sql2);
            $repo = new PodioAuthRepo();


            if ($repo->authenticate(1)) {
                // if ($repo->authenticateSF(2)) { // if ($repo->authenticateSF(6)) {
                if ($result && count($result) > 0) {
                    foreach ($result as $key => $calculation) {
                        //                        $sql3 = "SELECT dest_app_url FROM apps WHERE dest_app_id=:dest_app_id";
                        //                        $STH3 = DB::prepare($sql);
                        //                        $STH3->execute(array(
                        //                            "dest_app_id" => $calculation['dest_app_id'],
                        //                        ));
                        //                        $result3 = $STH->fetchAll(PDO::FETCH_ASSOC);
                        //                        if ($result3 && count($result3) > 0) {
                        //                            foreach ($result3 as $appURL) {
                        //                                echo $appURL . "</br>";
                        //                            }
                        //                        }
                        $config = json_decode($calculation['src_field_config']);
                        $settings = (array)$config->settings;
                        $script = $settings['script'];
                        $update = false;
                        if (preg_match_all("(([\d]+))", $script, $matches)) {
                            $update = true;
                            foreach ($matches[0] as $match) {
                                $fieldId = $match;
                                $STH1->execute(array(
                                    "src_field_id" => $fieldId
                                ));
                                $result1 = $STH1->fetchAll(PDO::FETCH_ASSOC);
                                if ($result1 && count($result1) > 0 && !is_null($result1[0]['dest_field_id'])) {
                                    $script = strtr($script, array($fieldId => $result1[0]['dest_field_id']));
                                } else {
                                    //                                    $update = false;
                                    echo "Error on calculation " . $key . "-------" . $fieldId . "----" . $result1[0]['field_type'];
                                    echo "<br>";
                                }
                            }
                            ////                            if ($update) {
                            //                            echo "<pre>";
                            //                            print_r($script);
                            //                            echo "<br>";
                            //                            echo "-------------------";
                            //                            echo "<br>";
                            if ($update) {
                                $attributes = array("type" => 'calculation', 'config' => array(
                                    'label' => $calculation['label'],
                                    'delta' => (int)$calculation['src_delta'],
                                    'settings' => array('script' => $script)
                                ));
                                try {

                                    $resp = PodioAppField::create($calculation['dest_app_id'], $attributes);
                                    $destField = intval($resp);
                                    $destFiledDetails = $this->customPodioAPI->podioGet("/app/" . $calculation['dest_app_id'] . "/field/" . $destField);
                                    $STH2->execute(array(
                                        "dest_field_id" => $destField,
                                        "dest_field_external_id" => $destFiledDetails['external_id'],
                                        "dest_field_config" => json_encode($destFiledDetails['config']),
                                        "dest_delta" => $destFiledDetails['config']['delta'],
                                        "id" => $calculation['id']
                                    ));
                                } catch (Exception $e) {
                                    //                                print_r($e);
                                    //                                    exit;
                                }
                            }
                            //                            }
                        } else {
                            //                            echo "<pre>";
                            //                            print_r($script);
                            //                            echo "<br>";
                            //                            echo "-------------------";
                            //                            echo "<br>";
                            $attributes = array("type" => 'calculation', 'config' => array(
                                'label' => $calculation['label'],
                                'delta' => (int)$calculation['src_delta'],
                                'settings' => array('script' => $script)
                            ));
                            try {


                                $resp = PodioAppField::create($calculation['dest_app_id'], $attributes);
                                $destField = intval($resp);
                                $destFiledDetails = $this->customPodioAPI->podioGet("/app/" . $calculation['dest_app_id'] . "/field/" . $destField);
                                $STH2->execute(array(
                                    "dest_field_id" => $destField,
                                    "dest_field_external_id" => $destFiledDetails['external_id'],
                                    "dest_field_config" => json_encode($destFiledDetails['config']),
                                    "dest_delta" => $destFiledDetails['config']['delta'],
                                    "id" => $calculation['id']
                                ));
                            } catch (Exception $e) {
                                //                                print_r($script);
                                print_r("Error2");
                                //                                exit;
                            }
                        }
                    }
                }
            }
        } catch (Exception $e) {
            //            print_r($e);
            //            exit;
            print_r("Error Main");
        }
    }

    private
    function getSpaces()
    {
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $orgID = 310355;
            $spaces = $this->customPodioAPI->podioGet("/space/org/$orgID/");
            foreach ($spaces as $space) {
                if ($space['name'] != "Employee Network") {
                    print_r($space['space_id'] . ',');
                    echo "<br>";
                }
            }
        } else {
            echo "No auth";
        }
    }

    private
    function updateAppToAddComment()
    {
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(9)) { // if ($repo->authenticateSF(6)) {
            Log::log("updateAppToAddComment - started ", null, "info");
            $sql = "SELECT dest_app_id,id FROM  `apps` WHERE allow_comments=0";
            $STH = DB::prepare($sql);
            $STH->execute();
            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                //                $sql = "UPDATE apps set allow_comments =0 where id =:id";
                //                $STH = DB::prepare($sql);

                foreach ($result as $app) {
                    $appId = $app['dest_app_id'];
                    $appDetails = Podio::get("/app/$appId")->json_body();
                    $newAppDetails['config'] = $appDetails['config'];
                    $newAppDetails['config']['allow_comments'] = false;
                    $resp = PodioApp::update($appId, $newAppDetails);
                    //                        $STH->execute(array("id" => $app['id']));
                }
            }
            Log::log("updateAppToAddComment - finished ", null, "info");
        }
    }

    private
    function getUserReport()
    {
        echo "<pre>";
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            $spaces = $this->customPodioAPI->podioGet(" /space/org/568/");
            foreach ($spaces as $space) {
                //                echo $space['name'];
                //                echo "<br>";
                if ($space['name'] != "Employee Network") {
                    $spaceId = $space['space_id'];
                    $limit = 100;
                    $offset = 0;
                    $attributes = array("limit" => $limit);
                    do {
                        $attributes['offset'] = $offset;
                        $count = 0;
                        $admins = $this->customPodioAPI->podioGet("/space/" . $spaceId . "/member/", $attributes);
                        $count = count($admins);
                        foreach ($admins as $admin) {
                            $array = array(
                                'daniel.horn@groupm.com',
                                'podio@phases.dk'
                            );
                            if (!in_array($admin['user']['mail'], $array)) {
                                print_r($admin['profile']['name'] . "," . $admin['user']['mail']);
                                echo "<br>";
                            }
                        }
                        $offset += $limit;
                    } while ($count > 0);
                }
                echo "<br>";
            }
        } else {
            echo "asdasd";
        }
    }


    public function testCaseByChinnu()
    {

        $sql = "select dest_item_id from `items` where dest_item_id is not null limit 5 ";
        $STH = DB::prepare($sql);
        $STH->execute();

        $result = $STH->fetchAll(PDO::FETCH_ASSOC);
        // print_r($result);
        if ($result && count($result) > 0) {
            foreach ($result as $ItemId) {
                PodioItem::delete($ItemId);
            }
        }
    }

    public function inviteSpaceUsers()
    {
        try {
            $repo = new PodioAuthRepo();

            //Mention ws
            $wsArray = [
                6347509
            ];

            foreach ($wsArray as $space) {
                Podio::authenticate_with_password('', '');
                $count = 0;
                $complete = true;

                // Retrieve destination space IDs for each source space
                $sql1 = "SELECT dest_space_id FROM work_spaces WHERE src_space_id = :src_space_id";
                $STH1 = DB::prepare($sql1);
                $STH1->execute(['src_space_id' => $space]);
                $result1 = $STH1->fetchAll(PDO::FETCH_ASSOC);

                if (!$result1 || count($result1) === 0) {
                    Log::log("No destination space found for source space $space", 'invite-users');
                    continue;
                }

                foreach ($result1 as $ws) {
                    // Retrieve and remove existing members other than 'podio@bruger.dk'
                    // Step 1: Retrieve all current members from the destination workspace
                    // try {
                    //     $currentMembers = PodioSpaceMember::get_all($ws['dest_space_id']);

                    //     // Step 2: Retrieve contacts for the destination workspace
                    //     $contacts = PodioContact::get_for_space($ws['dest_space_id'], ['type' => 'user']);

                    //     // Step 3: Map contacts by email to find user IDs
                    //     $contactEmailToUserIdMap = [];
                    //     foreach ($contacts as $contact) {
                    //         if (isset($contact->mail[0])) {  // Assuming `mail` is an array, and the first email is relevant
                    //             $contactEmailToUserIdMap[strtolower($contact->mail[0])] = $contact->user_id;
                    //         }
                    //     }



                    //     // Step 4: Iterate over the current members and remove the ones not matching 'podio@bruger.dk'
                    //     foreach ($currentMembers as $member) {
                    //         if (isset($member->user->mail) && strtolower($member->user->mail) !== 'podio@bruger.dk') {
                    //             // Find the user ID based on the member's email from the contacts map

                    //             if (isset($contactEmailToUserIdMap[$member->user->mail])) {
                    //                 $userIdToRemove = $contactEmailToUserIdMap[strtolower($member->user->mail)];
                    //                 // Remove the user from the destination space
                    //                 $removeResponse = PodioSpaceMember::delete($ws['dest_space_id'], $userIdToRemove);
                    //                 if (!$removeResponse) {
                    //                     Log::log("Failed to remove user {$member->user->mail} from destination space {$ws['dest_space_id']}", 'remove-users');
                    //                     echo 'Failed to remove user ' . $member->user->mail . 'from destination space ' . $ws['dest_space_id'] . '<br>';
                    //                 } else {
                    //                     Log::log("Removed user {$member->user->mail} from destination space {$ws['dest_space_id']}", 'remove-users');
                    //                     echo 'users removed from source - ' . $space . ' ,destination - ' . $ws['dest_space_id'] . '<br>';
                    //                 }
                    //             }
                    //         }
                    //     }
                    //     echo '****** PROCESS COMPLETED******';
                    // } catch (Exception $e) {
                    //     Log::logError($e, $space, "removeMembers");
                    //     Log::log("Failed to retrieve or remove existing members for space {$ws['dest_space_id']}", 'remove-users');
                    //     echo 'Failed';
                    //     continue;
                    // }
                    $limit = 200;
                    $offset = 0;

                    // // Loop through members in batches
                    do {
                        $sql = "SELECT * FROM workspace_members WHERE identifier = :identifier AND src_space_id = :src_space_id LIMIT $limit OFFSET $offset";
                        $STH = DB::prepare($sql);
                        $STH->execute([
                            'identifier' => 1,
                            'src_space_id' => $space
                        ]);
                        $result = $STH->fetchAll(PDO::FETCH_ASSOC);

                        echo 'sourceSpace - ' . $space . ' - ' . count($result) . ' destinationSpace - ' . $ws['dest_space_id'] . "<br>";

                        if (!$result || count($result) === 0) {
                            echo 'break';
                            $complete = false;
                            break;
                        }

                        $count += count($result);
                        $roleArray = [];

                        // Populate bot user if there are multiple records
                        // if ($count > 1) {
                        $attrib = [
                            'mails' => [''], // bot user email if applicable
                            'role' => 'admin'
                        ];
                        $response = PodioSpaceMember::add($ws['dest_space_id'], $attrib);
                        if (!$response) {
                            Log::log("Failed to add bot user for destination space {$ws['dest_space_id']}", 'invite-users');
                            break;
                        }
                        Podio::authenticate_with_password('', ''); // authenticate with above added bot user

                        // }


                        // Process each contact and assign roles
                        foreach ($result as $contact) {
                            // if ($contact['email'] !== 'podio@bruger.dk') {
                            $newEmail = $this->findNewUserEmailMapping(strtolower($contact['email']));

                            if (!isset($roleArray[$contact['role']])) {
                                $roleArray[$contact['role']] = [
                                    'mails' => [],
                                    'role' => $contact['role']
                                ];
                            }
                            if (isset($newEmail))
                                $roleArray[$contact['role']]['mails'][] = $newEmail;
                            // }
                        }


                        // Send invites for each role
                        foreach ($roleArray as $title => $attributes) {
                            try {
                                $response = PodioSpaceMember::add($ws['dest_space_id'], $attributes);
                                if (!$response) {
                                    Log::log("Invite failed for role $title in space {$ws['dest_space_id']}", 'invite-users');
                                    echo 'Invite failed for role ' . $title . ' in space ' . $ws['dest_space_id'] . "<br>";
                                }
                            } catch (Exception $e) {
                                Log::logError($e, $space, "moveMembers");
                                Log::log("Invite failed for space $space - count: $count", 'invite-users');
                                echo 'Invite failed for space ' . $space . '- count:' . $count . "<br>";
                                $complete = false;
                            }
                        }

                        $offset += $limit;
                    } while (count($result) === $limit);
                }

                if ($complete) {
                    Log::log("Invite completed for space $space - count: $count", 'invite-users');
                    echo 'Invite completed for space' . $space . '- count:' . $count . "<br>";
                }
            }
        } catch (\Exception $e) {
            echo 'error';
            print_r($e);
        }
    }

    public function findNewUserEmailMapping($oldEmail)
    {
        try {

            $newEmail = null;
            switch ($oldEmail) {
                case strtolower('warrick@ccrecruitment.co.nz '):
                    return 'warrick@ccrgroup.co.nz';
                default:
                    // echo 'Email not found for ' . $oldEmail . '<br>';
                    // Log::log("Email not found for ' . $oldEmail", 'emailMapping');
                    return $oldEmail;
            }
            return $newEmail;
        } catch (\Exception $e) {
            echo 'error in UserMapping';
            print_r($e);
        }
    }



    public function updateTaskResponsible()
    {
        try {
            Log::log("updateTaskResponsible  started ", null, "info");
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(1)) {
                do {

                    $contactEmailToUserIdMap = [];
                    // $orgContacts = PodioContact::get_for_org(1439346, ['limit' => 180]);
                    // foreach ($orgContacts as $contact) {
                    //     if (isset($contact->mail[0])) {
                    //         $contactEmailToUserIdMap[strtolower($contact->mail[0])] = $contact->user_id;
                    //     }
                    // }

                    $haveMoreItems = false;
                    $limit = 100;
                    $sql = "select dest_task_id,responsible from tasks where `identifier`=:identifier and src_ref_type='space' and status ='active'";
                    // $sql = "SELECT dest_task_id, t.status, t.responsible, i.src_item_id, i.src_app_id, a.src_space_id, w.dest_space_id FROM tasks t 
                    // JOIN items i ON t.src_ref_id = i.src_item_id 
                    // JOIN apps a ON i.src_app_id = a.src_app_id 
                    // JOIN work_spaces w ON a.src_space_id = w.src_space_id ";

                    $STH = DB::prepare($sql);
                    $STH->execute(array('identifier' => 1));

                    $result = $STH->fetchAll(PDO::FETCH_ASSOC);
                    if ($result && count($result) > 0) {
                        $STH = NULL;
                        if (count($result) == $limit)
                            $haveMoreItems = true;

                        foreach ($result as $task) {
                            $responsible = json_decode($task['responsible']);
                            $oldUserId = $responsible->user_id;

                            //    echo $task['dest_task_id'];
                            // $taskDetails = PodioTask::get($task['dest_task_id']);
                            $continue = true;
                            // foreach ($taskDetails as $details) {

                            //     $responsiblePresent = $details['responsible'];
                            //     if (!empty($responsiblePresent)) {
                            //         //    $continue = false;
                            //     }
                            // }

                            if ($continue) {
                                $spaceContacts =  PodioContact::get_for_org(1439346, ['limit' => 180]);
                                // $spaceContacts = PodioContact::get_for_space($task['dest_space_id'], $attributes = array());
                                if (!empty($spaceContacts)) {
                                    foreach ($spaceContacts as $contact) {
                                        if (isset($contact->mail[0])) {
                                            $contactEmailToUserIdMap[strtolower($contact->mail[0])] = $contact->user_id;
                                        }
                                    }


                                    $email = null;
                                    $newUserId = null;
                                    $sql = "SELECT email FROM `workspace_members` WHERE 
                        user_id=:user_id";
                                    $STH = DB::prepare($sql);
                                    $STH->execute(array(
                                        'user_id' => $oldUserId
                                    ));
                                    $result = $STH->fetchAll(PDO::FETCH_ASSOC);
                                    if ($result && count($result) > 0) {
                                        $email = $result[0]['email'];
                                    }
                                    // echo '1';
                                    // echo $email;
                                    if ($email) {
                                        $newEmail = $this->findNewUserEmailMapping(strtolower($email));
                                        // echo '2';
                                        // echo $newEmail;
                                        if (isset($contactEmailToUserIdMap[$newEmail])) {
                                            $newUserId = $contactEmailToUserIdMap[strtolower($newEmail)];
                                        }
                                        // echo '3';
                                        // echo $newUserId;

                                        if (isset($newUserId)) {
                                            //updateTask Responsible
                                            $response = PodioTask::update($task['dest_task_id'], ['responsible' => $newUserId], ['silent' => true, 'hook' => false]);
                                            echo 'Updated responsible for destTask - ' . $task['dest_task_id'] . '<br>';
                                            if (!$response) {
                                                echo 'Failed to update responsible for destTask - ' . $task['dest_task_id'] . '<br>';
                                            }
                                        } else {
                                            $response = PodioTask::update($task['dest_task_id'], ['responsible' => Config::$DEFLT_TASK_RESP], ['silent' => true, 'hook' => false]);
                                            echo 'Updated to deafault dtask responsible - ' . $task['dest_task_id'] . '<br>';
                                        }
                                    } else {
                                        echo 'no member for  ' . $task['dest_task_id'] . '<br>';
                                    }
                                } else {
                                    // echo 'no space contacts added for ' . $task['dest_space_id'];
                                    // Log::log("no space contacts added ", $task['dest_space_id'], "info");
                                    exit;
                                }
                            } else {
                                echo 'Already added responsible for ' . $task['dest_task_id'] . '<br>';
                            }
                        }
                        $result = NULL;
                    }
                } while ($haveMoreItems);
                Log::log("updateTaskResponsible  ended ", null, "info");
            }
        } catch (\Exception $e) {
            echo 'error in UserMapping';
            print_r($e);
        }
    }

    public function updateAppRelation()
    {
        Log::log("updateRelation  started ", null, "info");
        try {
            $repo = new PodioAuthRepo();

            $sql = "select src_item_id,dest_item_id from items where dest_app_id=29881354 limit 1328,20";

            $STH = DB::prepare($sql);
            $STH->execute(array());

            $result = $STH->fetchAll(PDO::FETCH_ASSOC);
            if ($result && count($result) > 0) {
                foreach ($result as $item) {

                    $relationItemId = null;
                    $newRelationItemId = null;
                    if ($repo->authenticateSF(1)) {
                        $fieldDetails = PodioItem::get_field_value($item['src_item_id'], 190926310); //relation field id in source app
                    }
                    foreach ($fieldDetails as $field) {
                        $relationItemId = $field['value']['item_id'];
                    }

                    if (isset($relationItemId)) {
                        //find the corresponding item new copied ws
                        $sql2 = "select dest_item_id from items where src_item_id=:src_item_id limit 1";
                        $STH2 = DB::prepare($sql2);
                        $STH2->execute(array('src_item_id' => $relationItemId));

                        $result2 = $STH2->fetchAll(PDO::FETCH_ASSOC);
                        if ($result2 && count($result2) > 0) {
                            foreach ($result2 as $relatedItem) {
                                $newRelationItemId = $relatedItem['dest_item_id'];
                            }
                        }

                        if (isset($newRelationItemId)) {

                            $attributes = [
                                'fields' => [
                                    'relation' => intval($newRelationItemId)
                                ]
                            ];
                            // echo $newRelationItemId . '<br>';
                            try {
                                Podio::setup('podio-data-migration-6lq9pd', 'TG9trKsJ942e3RIjvk4FC3IY5fZ00WiESmruWLjuQSzYtqG5XZziQsxMSYjb1UX3');
                                Podio::authenticate_with_password('podio@rfibruger.dk', 'Zeus2200Zeus!!');
                                $resp = $this->customPodioAPI->updatePodioItem($item['dest_item_id'], $attributes);
                            } catch (\Exception $e) {
                                echo 'error in itemupdate';
                                print_r($e);
                            }

                            if (!$resp) {
                                // echo 'failed to update';
                                // print_r($resp);
                            }
                        }
                    } else {
                        // echo 'no relation added <br>';
                    }
                }
            }
            echo 'completed';
            Log::log("updateRelation  ended ", null, "info");
        } catch (\Exception $e) {
            echo 'error in update relation';
            print_r($e);
        }
    }

    public function updateContact()
    {
        try {
            Log::log("updateContact  started ", null, "info");
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(1)) {

                $sql = "SELECT af.src_app_id, af.src_field_id, af.status, af.field_type,af.dest_field_id, ifv.src_item_id, ifv.value, i.dest_item_id FROM app_fields af
             JOIN item_field_values ifv ON af.src_field_id = ifv.src_field_id
             JOIN items i ON ifv.src_item_id = i.src_item_id
             WHERE af.field_type = 'contact' AND af.status = 'active' and af.src_app_id  IN (26826404,27073034,22913513,28351864) LIMIT 12111,2000";

                $STH = DB::prepare($sql);
                $STH->execute(array());
                $contactFieldResults = $STH->fetchAll(PDO::FETCH_ASSOC);

                $spaceContacts = null;
                $spaceContacts = PodioContact::get_for_org(3765222, ['limit' => 180]);

                $contactEmailToProfileIdMap = [];
                if (!empty($spaceContacts)) {
                    foreach ($spaceContacts as $contact) {
                        if (isset($contact->mail[0])) {
                            $contactEmailToProfileIdMap[strtolower(trim($contact->mail[0]))] = $contact->profile_id;
                        }
                    }
                }

                if ($contactFieldResults && count($contactFieldResults) > 0) {
                    foreach ($contactFieldResults as $contactFields) {
                        $newProfileId = [];
                        $contactValue = json_decode($contactFields['value']);
                        if (!$contactValue || !is_array($contactValue)) {
                            continue;
                        }

                        foreach ($contactValue as $contact) {
                            $oldProfileId = $contact->profile_id;
                            $sql = "SELECT email FROM workspace_members WHERE profile_id = :profile_id";

                            $STH = DB::prepare($sql);
                            $STH->execute(array(
                                'profile_id' => $oldProfileId
                            ));
                            $memberResult = $STH->fetchAll(PDO::FETCH_ASSOC);
                            if (!$memberResult || count($memberResult) == 0) {
                                continue;
                            }

                            $oldEmail = strtolower(
                                trim($memberResult[0]['email'])
                            );

                            /**
                             * STEP 1
                             * Old contact must exist in destination org
                             */
                            if (!isset($contactEmailToProfileIdMap[$oldEmail])) {
                                continue;
                            }

                            /**
                             * STEP 2
                             * Check mapping
                             */
                            $mappedEmail = strtolower(trim($this->findNewUserEmailMapping($oldEmail)));

                            /**
                             * STEP 3
                             * If mapped email exists in org,
                             * use mapped profile
                             */
                            if ($mappedEmail && isset($contactEmailToProfileIdMap[$mappedEmail])) {
                                $newProfileId[] = intval($contactEmailToProfileIdMap[$mappedEmail]);
                            } else {

                                /**
                                 * STEP 4
                                 * Else use original profile
                                 */
                                $newProfileId[] = intval($contactEmailToProfileIdMap[$oldEmail]);
                            }
                        }

                        $newProfileId = array_unique($newProfileId);

                        if (empty($newProfileId)) {
                            continue;
                        }

                        $attributes = [
                            'fields' => [
                                $contactFields['dest_field_id'] => $newProfileId,
                            ]
                        ];

                        echo $contactFields['dest_item_id'] . '<br>';

                        $resp = $this->customPodioAPI->updatePodioItem(
                            $contactFields['dest_item_id'],
                            $attributes
                        );

                        $dest = $contactFields['dest_item_id'];

                        if (!$resp) {
                            echo 'failed to update <br>';
                        } else {

                            Log::log(
                                "updateContact - $dest ",
                                null,
                                "info"
                            );
                            $sql = "UPDATE item_field_values SET update_contact =1 WHERE src_item_id=:src_item_id AND src_field_id=:src_field_id";
                            $STH = DB::prepare($sql);
                            $STH->execute(array(
                                'src_item_id' => $contactFields['src_item_id'],
                                'src_field_id' => $contactFields['src_field_id']
                            ));
                        }
                        echo 'finished';
                    }
                }
            }
            Log::log("updateContact  finished ", null, "info");
        } catch (\Exception $e) {
            echo 'error in update contact';
            print_r($e);
            exit;
        }
    }

    public function deleteItems()
    {
        try {
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(1)) {
                Log::log("Deleted Item - started", null, "info");
                do {
                    // Fetch next batch
                    $itemCollection = PodioItem::filter(30590168, [
                        'limit' => 100,
                        'offset' => 0
                    ]);


                    foreach ($itemCollection as $item) {

                        PodioItem::delete($item->item_id, ['silent' => true]);
                        Log::log("Deleted Item - " . $item->item_id, null, "info");
                    }
                    sleep(10);
                    // Continue until no items remain
                } while (count($itemCollection) > 0);
            }
            Log::log("Deleted Item - finished", null, "info");
            echo 'finished';
        } catch (\Exception $e) {
            echo 'error in delete items';
            Log::log("Deleted Item - error", $e, "info");
            print_r($e);
            exit;
        }
    }

    public function createItemTasks()
    {
        try {
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(1)) {
                Log::log("Create Item Tasks - started", null, "info");

                // $response = PodioTask::update(313793309, ['responsible' => Config::$DEFLT_TASK_RESP], ['silent' => true, 'hook' => false]);
                // exit;

                //2380496718,
                $itemIds = [2357408483, 1462289563, 1172909730];

                echo  'createItemTasks';
                foreach ($itemIds as $itemId) {

                    $sql1 = "SELECT dest_item_id FROM items WHERE src_item_id=:src_item_id limit 1";
                    $STH1 = DB::prepare($sql1);
                    $STH1->execute(array('src_item_id' => $itemId));
                    $result1 = $STH1->fetchAll(PDO::FETCH_ASSOC);
                    if ($result1 && count($result1) > 0) {

                        $sql = "SELECT * FROM  `tasks` WHERE identifier=:identifier AND src_ref_type=:src_ref_type
        AND src_ref_id=:src_ref_id AND dest_task_id =0 "; //AND dest_task_id IS NULL
                        $STH = DB::prepare($sql);
                        $STH->execute(array(
                            'identifier' => 1,
                            'src_ref_type' => "item",
                            'src_ref_id' => $itemId
                        ));

                        $result = $STH->fetchAll(PDO::FETCH_ASSOC);

                        if ($result && count($result) > 0) {
                            foreach ($result as $task) {
                                $responsible = Config::$DEFLT_TASK_RESP;

                                $attributes = array(
                                    "responsible" => (int)$responsible,
                                    "text" => $task['text'],
                                    "description" => $task['description'],
                                    "private" => ($task['private'] == 0) ? false : true,
                                    "due_on" => $task['due_on'] ? $task['due_on'] : null, // date('Y-m-d H:i:s', $commentItem->created_on->getTimestamp())
                                    "due_date" => $task['due_date'] ? $task['due_date'] : null, // $task->due_date
                                    "due_time" => $task['due_time'] ? $task['due_time'] : null, //$task->due_time
                                );

                                $resp = $this->customPodioAPI->createTask('item', $result1[0]['dest_item_id'], $attributes);
                                $newTaskID = 0;
                                $taskCreate = new TaskCreateRepo();
                                if ($resp) {
                                    $newTaskID = $resp->task_id;
                                    if ($task['status'] == 'completed') {
                                        PodioTask::complete($resp->task_id);
                                    }

                                    $haveNoResponsible = false;
                                    if ($haveNoResponsible) {

                                        $commentValue = $taskCreate->getResponsibleUserComment($task);
                                        $this->customPodioAPI->createComment("task", $resp->task_id, array('value' => $commentValue));
                                    }

                                    $task['dest_task_id'] = $resp->task_id;
                                    $taskCreate->taskCreatedByComment($task);
                                    if (isset($task['completed_on']) && !is_null($task['completed_on']))
                                        $taskCreate->taskCompletedByComment($task);
                                }

                                echo $newTaskID;
                                $sql = "UPDATE  tasks SET dest_task_id=:dest_task_id WHERE id=:id";
                                $STH = DB::prepare($sql);
                                $STH->execute(array('id' => $task['id'], 'dest_task_id' => $newTaskID));
                            }
                        }
                    }
                    Log::log("Create Item Tasks - finished", null, "info");
                    echo 'finished';
                }
            }
        } catch (\Exception $e) {
            echo 'error in delete items';
            Log::log("Deleted Item - error", $e, "info");
            print_r($e);
            exit;
        }
    }

    public function saveItemFiles()
    {
        try {
            Log::log("saveItemFiles - started", null, "info");
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(1)) {
                $sql = "select t1.id,t1.src_app_id,t1.src_item_id,t1.file_count,t1.comment_count,t1.copy_next_step,t1.copy_completed_steps,
            t1.identifier,t2.src_app_type,t2.voting from `items` as t1 inner join apps as t2 on t1.src_app_id=t2.src_app_id and t1.identifier=t2.identifier
             where  t1.`identifier`=:identifier and t1.`dest_app_id` is NULL and t2.src_app_id IN (6634282,6634449,8940019,11894158,8676307,14738089,16376313,27953471,23450831,23450108)";
                $STH = DB::prepare($sql);
                $STH->execute(array('identifier' => 1));
                $result = $STH->fetchAll(PDO::FETCH_ASSOC);
                if ($result && count($result) > 0) {
                    foreach ($result as $item) {
                        $podioItem = $this->customPodioAPI->podioGet("/item/" . $item['src_item_id']);
                        $files = $podioItem['files'];
                        if ($files && is_array($files) && count($files) > 0) {
                            $fileRepo = new FileCopyRepo();
                            $fileRepo->saveFilesToDB(array(
                                "identifier" => $item['identifier'],
                                'src_ref_type' => "item",
                                'src_ref_id' => $item['src_item_id']
                            ), $files);
                            $sql = "UPDATE items SET save_file =1 WHERE src_item_id=:src_item_id ";
                            $STH = DB::prepare($sql);
                            $STH->execute(array(
                                'src_item_id' => $item['src_item_id']
                            ));
                        }
                    }
                }
            }
            Log::log("saveItemFiles - finished", null, "info");
            echo 'finished';
        } catch (\Exception $e) {
            echo 'error in saveItemFiles';
            Log::log("saveItemFiles - error", $e, "info");
            print_r($e);
            exit;
        }
    }

    public function saveCommentFiles()
    {
        try {
            Log::log("saveCommentFiles - started", null, "info");
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(1)) {
                // $sql = "select src_item_id from items where copy_next_step='completed' and src_app_id IN (6634282,6634449,8940019,11894158,8676307,14738089,16376313,27953471,23450831,23450108)";
                // $STH = DB::prepare($sql);
                // $STH->execute(array('identifier' => 1));
                // $result = $STH->fetchAll(PDO::FETCH_ASSOC);
                // if ($result && count($result) > 0) {
                //     foreach ($result as $item) {
                $sql1 = "select comment_id from files where src_ref_type='comment' and new_file_id is null limit 3";
                $STH1 = DB::prepare($sql1);
                $STH1->execute();
                $commentResult = $STH1->fetchAll(PDO::FETCH_ASSOC);
                if ($commentResult && count($commentResult) > 0) {
                    foreach ($commentResult as $comment) {
                        $podioComment = $this->customPodioAPI->podioGet("/comment/" . $comment['comment_id']);
                        $files = $podioComment['files'];
                        if ($files && is_array($files) && count($files) > 0) {
                            $fileRepo = new FileCopyRepo();
                            $fileRepo->saveFilesToDB(array(
                                "identifier" => 1,
                                'src_ref_type' => "comment",
                                'src_ref_id' => $comment['comment_id']
                            ), $files);
                            $sql = "UPDATE comments SET delta_need_update =1 WHERE comment_id=:comment_id ";
                            $STH = DB::prepare($sql);
                            $STH->execute(array(
                                'comment_id' => $comment['comment_id']
                            ));
                        }
                    }
                }
                // }
                // }
            }
            Log::log("saveCommentFiles - finished", null, "info");
            echo 'finished';
        } catch (\Exception $e) {
            echo 'error in saveCommentFiles';
            Log::log("saveCommentFiles - error", $e, "info");
            print_r($e);
            exit;
        }
    }

    public function saveTaskFiles()
    {
        try {
            Log::log("saveTaskFiles - started", null, "info");
            $repo = new PodioAuthRepo();
            if ($repo->authenticate(1)) {
                $sql = "select src_item_id from items where copy_next_step='completed' and src_app_id IN (6634282,6634449,8940019,11894158,8676307,14738089,16376313,27953471,23450831,23450108)";
                $STH = DB::prepare($sql);
                $STH->execute(array('identifier' => 1));
                $result = $STH->fetchAll(PDO::FETCH_ASSOC);
                if ($result && count($result) > 0) {
                    foreach ($result as $item) {
                        $sql = "select dest_task_id from tasks where identifier=1 and src_ref_type='item' and status ='active' and src_ref_id=:src_ref_id ";
                        $STH = DB::prepare($sql);
                        $STH->execute(array(
                            'identifier' => 1,
                            'src_ref_id' => $item['src_item_id']
                        ));
                        $result = $STH->fetchAll(PDO::FETCH_ASSOC);
                        if ($result && count($result) > 0) {
                            foreach ($result as $task) {
                                $podioTask = $this->customPodioAPI->podioGet("/task/" . $task['dest_task_id']);
                                $files = $podioTask['files'];
                                if ($files && is_array($files) && count($files) > 0) {
                                    $fileRepo = new FileCopyRepo();
                                    $fileRepo->saveFilesToDB(array(
                                        "identifier" => 1,
                                        'src_ref_type' => "task",
                                        'src_ref_id' => $task['dest_task_id']
                                    ), $files);
                                    $sql = "UPDATE tasks SET save_task_file =1 WHERE dest_task_id=:dest_task_id ";
                                    $STH = DB::prepare($sql);
                                    $STH->execute(array(
                                        'dest_task_id' => $task['dest_task_id']
                                    ));
                                }
                            }
                        }
                    }
                }
            }
            Log::log("saveTaskFiles - finished", null, "info");
            echo 'finished';
        } catch (\Exception $e) {
            echo 'error in saveTaskFiles';
            Log::log("saveTaskFiles - error", $e, "info");
            print_r($e);
            exit;
        }
    }
}

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists