Duffer Derek

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

<?php

namespace App\Repository\Copy;


use App\Repository\Create\ItemCreateRepo;
use App\Repository\General\Async;
use App\Repository\General\Constants;
use App\Repository\General\DB;
use App\Repository\General\Log;
use App\Repository\Utils\CustomPodioAPI;
use App\Repository\Utils\LinkReplaceRepo;
use App\Repository\Utils\PodioAuthRepo;
use PDO;
use PodioComment;

/**
 * Created by PhpStorm.
 * User: jis
 * Date: 30/3/17
 * Time: 9:33 AM
 */
class ItemCopyRepo
{
    private $customPodioAPI;
    private $linkReplaceRepo;

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

    // copy-async/process-items-in-the-app?identifier=

    /**
     * @param $identifier
     * @param $appID
     */
    public function saveItemsCommentsFilesTasks($identifier, $appID = null)
    {
        try {
            Log::log("saveItemsCommentsFilesTasks started " . $appID, null, "info");
            $limit = 100;
            do {
                $haveMoreItems = false;
                $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.`copy_next_step` ='save_item_comments_tags_voting_files' and t1.`identifier`=:identifier and t1.`dest_app_id` is NULL limit $limit";
                //    where t1.`copy_next_step` ='save_item_comments_tags_voting_files' and t1.`identifier`=:identifier and t1.`src_app_id`=:src_app_id limit $limit";
                $STH = DB::prepare($sql);
                $STH->execute(array(
                    'identifier' => $identifier,
                    // 'src_app_id' => $appID
                ));
                $result = $STH->fetchAll(PDO::FETCH_ASSOC);
                if ($result && count($result) > 0) {
                    if (count($result) == $limit)
                        $haveMoreItems = true;

                    $STH = NULL;
                    $repo = new PodioAuthRepo();
                    if ($repo->authenticate($identifier)) {
                        // if ($repo->authenticateSF($identifier)) {
                        Constants::setREFTYPE("item " . $identifier);
                        foreach ($result as $item) {
                            Constants::setREFID($item['src_item_id']);
                            $this->doNextStep($item);
                        }
                        $result = NULL;
                    } else {
                        Log::log("saveItemsCommentsFilesTasks authentication issue, identifier: " . $identifier, null, "warning");
                    }
                }
            } while ($haveMoreItems);
            Log::log("saveItemsCommentsFilesTasks finished " . $appID, null, "info");

            $this->processNextApp($identifier, $appID);
        } catch (\Exception $e) {
            Log::logError($e . "", null, "saveItemsCommentsFilesTasks");
        }
    }


    public function saveItemsCommentsFilesTasksDelta($identifier)
    {
        try {
            Log::log("saveItemsCommentsFilesTasksDelta started ", null, "info");
            $limit = 200;
            do {
                $haveMoreItems = false;
                $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.`copy_next_step` !='completed' and t1.`identifier`=:identifier  limit $limit";
                $STH = DB::prepare($sql);
                $STH->execute(array(
                    'identifier' => $identifier,
                ));
                $result = $STH->fetchAll(PDO::FETCH_ASSOC);
                if ($result && count($result) > 0) {

                    if (count($result) == $limit)
                        $haveMoreItems = true;

                    $STH = NULL;
                    $repo = new PodioAuthRepo();
                    if ($repo->authenticate($identifier)) {
                        Constants::setREFTYPE("item " . $identifier);
                        foreach ($result as $item) {
                            Constants::setREFID($item['src_item_id']);
                            $this->doNextStep($item);
                        }
                        $result = NULL;
                    } else {
                        Log::log("saveItemsCommentsFilesTasks authentication issue, identifier: " . $identifier, null, "warning");
                    }
                }
            } while ($haveMoreItems);
            Log::log("saveItemsCommentsFilesTasks finished ", null, "info");
        } catch (\Exception $e) {
            Log::logError($e . "", null, "saveItemsCommentsFilesTasks");
        }
        Log::log("saveItemsCommentsFilesTasksDelta finished ", null, "info");
    }

    public function processNextApp($identifier, $appID)
    {
        $sql = "UPDATE apps SET  copy_next_step =:copy_next_step,copy_completed_steps=CONCAT(COALESCE(copy_completed_steps,''),:copy_completed_steps)
        where `identifier`=:identifier and src_app_id=:src_app_id";
        $STH = DB::prepare($sql);
        $STH->execute(array(
            'identifier' => $identifier,
            'src_app_id' => $appID,
            'copy_next_step' => 'completed',
            'copy_completed_steps' => ", save_items_comments_files_tasks"
        ));

        $sql = "select src_space_id from `apps` where `identifier`=:identifier and src_app_id=:src_app_id limit 1";
        $STH = DB::prepare($sql);
        $STH->execute(array(
            'identifier' => $identifier,
            'src_app_id' => $appID
        ));
        $result = $STH->fetchAll(PDO::FETCH_ASSOC);
        if ($result && count($result) > 0) {
            Log::log("Process Next App", null, "nvj");
            $app = $result[0];
            // start processing first app
            //            print("http://podiomigration.bitkit.dk/copy-async/process-first-app-in-the-space?identifier=1&space=" . $app['src_space_id']);
            //            exit;
            Async::callAsync("copy-async/process-first-app-in-the-space?identifier="
                . $identifier . "&space=" . $app['src_space_id']);
            //            Async::callAsync("copy-async/process-first-app?identifier=" . $identifier);
        } else {
            Log::log("No Process Next App", null, "nvj");
        }
    }

    private function doNextStep($item)
    {
        try {
            Log::log("ItemRepo doNextStep " . $item['copy_next_step'] . " " . $item['src_item_id'], $item);
            if ($this->makeSureNextStepIsNotDoneBefore($item)) {
                switch ($item['copy_next_step']) {

                    case "save_item_comments_tags_voting_files":
                        $this->saveItemTagsCommentsVoting($item);
                        break;

                    case "save_item_tasks":
                        $this->saveItemTasks($item);
                        break;
                }
            } else {
                // all steps in the app is completed
                $this->markItemAsCompleted($item);
            }
        } catch (\Exception $e) {
            Log::logError($e . "", $item, "doNextStep");
        }
    }

    private function saveItemTasks($item)
    {
        $tasksRepo = new TasksCopyRepo();
        $tasksRepo->saveTasks(array(
            'ref_type' => "item",
            "ref_id" => $item['src_item_id'],
            "identifier" => $item['identifier']
        ));

        $this->updateNextStep($item, "completed", ", save_item_tasks");
    }


    private function saveItemTagsCommentsVoting($item)
    {
        try {
            Log::log("saveItemTagsCommentsVoting", $item);
            //            // GET /item/{item_id}
            $podioItem = $this->customPodioAPI->podioGet("/item/" . $item['src_item_id']);

            // meeting participants
            if (isset($item['src_app_type']) && $item['src_app_type'] == "meeting") {
                $this->saveMeetingParticipants($item, $podioItem);
            }

            // tags
            $this->saveTags($item, $podioItem);

            // save comments // Item will return  max of 100 comments.
            $this->saveComments($item, $podioItem);

            // save item voting
            if (isset($item['voting'])) {
                $this->saveItemVoting($item);
            }

            // save files
            $this->saveItemFiles($item, $podioItem['files']);

            $this->updateNextStep($item, "save_item_tasks", ", save_item_comments_tags_voting_files");
        } catch (\Exception $e) {
            Log::logError($e . "", $item, "saveItemCommentsAndVoting");
        }
    }

    private function updateNextStep($item, $nextStep, $currentStep)
    {
        $sql = "UPDATE items SET  copy_next_step=:copy_next_step,copy_completed_steps=CONCAT(COALESCE(copy_completed_steps,''),:copy_completed_steps)  WHERE id=:id";
        $data = array("copy_next_step" => $nextStep, "id" => $item['id'], "copy_completed_steps" => $currentStep);
        $STH = DB::prepare($sql);
        $STH->execute($data);
        $item['copy_next_step'] = $nextStep;
        $item['copy_completed_steps'] = $item['copy_completed_steps'] . $currentStep;
        $this->doNextStep($item);
    }

    private function saveItemFiles($item, $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);
        }
    }

    private function saveItemVoting($item)
    {
        try {
            $voting = json_decode($item['voting']);
            if (is_array($voting) && count($voting) > 0) {
                // /voting/item/558602561/voting/3732480/result?max_voters=23

                //UNCOMMENT FOR DELTA COPY
                // $sql = "INSERT  INTO `item_field_values` ( `identifier`, `src_app_id`, `src_item_id`, `src_field_id`,
                //           `type`, `value`) VALUES (:identifier, :src_app_id, :src_item_id, :src_field_id,
                //            :type, :value) ON DUPLICATE KEY UPDATE `value`=:value,delta_need_update=1 ";

                //NORMAL COPY
                $sql = "INSERT  INTO `item_field_values` ( `identifier`, `src_app_id`, `src_item_id`, `src_field_id`,
                   `type`, `value`) VALUES (:identifier, :src_app_id, :src_item_id, :src_field_id, 
                    :type, :value) ON DUPLICATE KEY UPDATE `value`=:value";

                $STH = DB::prepare($sql);
                $data = array('identifier' => $item['identifier'], 'src_app_id' => $item['src_app_id'], 'src_item_id' => $item['src_item_id']);

                foreach ($voting as $vote) {
                    $vote = (array)$vote;
                    $itemVotes = $this->customPodioAPI->podioGet("/voting/item/" . $item['src_item_id'] . "/voting/" . $vote['voting_id'] . "/result?max_voters=1000");
                    $itemField = array();
                    if ($itemVotes && is_array($itemVotes)) {
                        foreach ($itemVotes['values'] as $key => $itemVoteValue) {
                            if (!isset($itemField[$key]))
                                $itemField[$key] = array();
                            foreach ($itemVoteValue['users'] as $user) {
                                $itemField[$key][] = array(
                                    'user_id' => $user['user_id'],
                                    'name' => $user['name'],
                                    'profile_id' => $user['profile_id'],
                                    'link' => $user['link']
                                );
                            }
                        }
                    }
                    $itemField = json_encode($itemField);
                    $data['value'] = $itemField;
                    $data['type'] = $vote['kind'];
                    $data['src_field_id'] = $vote['voting_id'];
                    $STH->execute($data);
                }
                $STH = NULL;
            }
        } catch (\Exception $e) {
            Log::logError($e . "", $item, "saveItemVoting");
        }
    }

    private function saveComments($item, $podioItem)
    {
        try {
            if (count($podioItem['comments']) > 0) {
                $commentRepo = new CommentRepo();
                if (count($podioItem['comments']) < 100) {
                    $commentRepo->saveComments(1, $podioItem['comments']);
                } else {
                    //GET /comment/{type}/{id}/
                    $limit = 100;
                    $offset = 0;
                    do {
                        $attributes = array('limit' => $limit, 'offset' => $offset);
                        $iterationCount = 0;
                        //CHANGEEEEEEEE
                        $comments = $this->customPodioAPI->podioGet("/comment/item/" . $item['src_item_id'] . "/", $attributes);
                        //                        $comments = $this->customPodioAPI->podioGet("/comment/item/" . $item['src_ref_id'] . "/", $attributes);
                        if ($comments && is_array($comments) && count($comments) > 0) {
                            $iterationCount = count($comments);
                            $commentRepo->saveComments(1, $comments);
                        }
                        $offset += $limit;
                    } while ($iterationCount > 0);
                }
            }
        } catch (\Exception $e) {
            Log::logError($e . "", $podioItem, "saveComments");
            exit;
        }
    }

    private function saveTags($item, $podioItem)
    {
        try {
            $tags = NULL;
            if (isset($podioItem['tags']) && is_array($podioItem['tags']) && count($podioItem['tags']) > 0) {
                $tags = $podioItem['tags'];
                $sql = "UPDATE items SET  tags =:tags WHERE id=:id";
                $data = array("tags" => json_encode($tags), "id" => $item['id']);
                $STH = DB::prepare($sql);
                $STH->execute($data);
                $STH = NULL;
            }
        } catch (\Exception $e) {
            Log::logError($e . "", $podioItem, "saveTags");
        }
    }

    private function saveMeetingParticipants($item, $podioItem)
    {
        try {
            $participants = NULL;
            if (isset($podioItem['participants']) && is_array($podioItem['participants']) && count($podioItem['participants']) > 0) {
                $participants = $podioItem['participants'];
                $sql = "UPDATE items SET  participants =:participants WHERE id=:id";
                $data = array("participants" => json_encode($participants), "id" => $item['id']);
                $STH = DB::prepare($sql);
                $STH->execute($data);
                $STH = NULL;
            }

            foreach ($podioItem['fields'] as $field) {
                if ($field['external_id'] == "meeting-participants") {
                    $value = $this->getContactValues($field);
                    $sql = "UPDATE item_field_values SET  `value` =:value WHERE identifier=:identifier 
                    AND src_item_id=:src_item_id AND src_field_id=:src_field_id";
                    $data = array(
                        "value" => json_encode($value),
                        "identifier" => $item['identifier'],
                        "src_item_id" => $item['src_item_id'],
                        "src_field_id" => $field['field_id']
                    );
                    $STH = DB::prepare($sql);
                    $STH->execute($data);
                    $STH = NULL;
                    break;
                }
            }
        } catch (\Exception $e) {
            Log::logError($e . "", $item, "saveMeetingParticipants");
        }
    }

    private function markItemAsCompleted($app)
    {
        $sql = "UPDATE items SET  copy_next_step =:copy_next_step  WHERE id=:id";
        $data = array("copy_next_step" => "completed", "id" => $app['id']);
        $STH = DB::prepare($sql);
        $STH->execute($data);
    }

    private function makeSureNextStepIsNotDoneBefore(&$item)
    {
        $appSteps = array("save_item_comments_tags_voting_files", "save_item_tasks");
        if (in_array($item['copy_next_step'], $appSteps)) {
            $pos = strpos($item['copy_completed_steps'], $item['copy_next_step']);
            if ($pos === false) {
                return true;
            }
            // already completed 'copy_next_step'
            // find the first not completed step
            foreach ($appSteps as $step) {
                $pos = strpos($item['copy_completed_steps'], $step);
                if ($pos === false) {
                    $item['copy_next_step'] = $step; // make this step as 'copy_next_step'
                    return true;
                }
            }
            // all steps in the item is completed
        }
        return false;
    }


    public function saveItemsToDB($identifier, $app, $items)
    {
        if ($items && is_array($items) && count($items) > 0) {
            Log::log("saveItemToDB", $items);
            foreach ($items as $item) {
                $this->saveItem($identifier, $app, $item);
                $this->saveItemFieldValues(array(
                    'identifier' => $identifier,
                    'src_app_id' => $app,
                    'src_item_id' => $item['item_id']
                ), $item['fields']);
            }
        }
    }


    public function saveDeltaItemsToDB($identifier, $app, $items)
    {
        if ($items && is_array($items) && count($items) > 0) {
            Log::log("saveItemToDB", $items);
            $deltaTime = 1735794038; // Sunday, 21 April 2019 05:17:53
            foreach ($items as $item) {
                $timestamp = strtotime($item['last_event_on']);
                if ($deltaTime < $timestamp) {
                    $this->saveItem($identifier, $app, $item);
                    $this->saveItemFieldValues(array(
                        'identifier' => $identifier,
                        'src_app_id' => $app,
                        'src_item_id' => $item['item_id']
                    ), $item['fields']);
                } else
                    return false;
            }
            return true;
        }
        return false;
    }

    private function saveItem($identifier, $app, $item)
    {
        $data = array(
            "identifier" => $identifier,
            "src_item_id" => $item['item_id'],
            "revision" => $item['revision'],
            "comment_count" => $item['comment_count'],
            "file_count" => $item['file_count'],
            "title" => $item['title'],
            "created_by_user_id" => $item['created_by']['user_id'],
            "created_by_name" => $item['created_by']['name'],
            "created_by_url" => $item['created_by']['url'],
            "src_app_id" => $app,
            "last_event_on" => null,
            "created_on" => $item['created_on'],
            "copy_next_step" => "save_item_comments_tags_voting_files",
            "create_next_step" => "create_item",
            'src_app_item_id' => $item['app_item_id']
        );
        if (isset($item['last_event_on'])) {
            $data['last_event_on'] = $item['last_event_on'];
        }

        //UNCOMMENT FOR DELTA-COPY
        // $sql = "INSERT INTO `items` (`identifier`, `src_app_id`, `src_item_id`, `src_app_item_id`, `title`, `file_count`, `comment_count`,
        // `revision`, `created_on`, `last_event_on`, `created_by_user_id`, `created_by_name`, `created_by_url`, `copy_next_step`, `create_next_step`, `delta_need_update`) 
        // VALUES
        // (:identifier, :src_app_id, :src_item_id, :src_app_item_id, :title, :file_count, :comment_count, :revision, :created_on, :last_event_on,
        //  :created_by_user_id, :created_by_name, :created_by_url, :copy_next_step, :create_next_step, 1)
        // ON DUPLICATE KEY UPDATE 
        // `title`=:title, `file_count`=:file_count, `comment_count`=:comment_count,`revision`=:revision,`last_event_on`=:last_event_on, `delta_need_update` = 1";

        //NORMAL COPY
        $sql = "INSERT INTO `items` (`identifier`, `src_app_id`, `src_item_id`,`src_app_item_id`,  `title`, `file_count`, `comment_count`,
        `revision`, `created_on`,`last_event_on`, `created_by_user_id`, `created_by_name`, `created_by_url`, `copy_next_step`,`create_next_step`) VALUES
         (:identifier, :src_app_id,:src_item_id, :src_app_item_id, :title, :file_count, :comment_count,:revision,:created_on,:last_event_on,
          :created_by_user_id, :created_by_name, :created_by_url, :copy_next_step,:create_next_step) ON DUPLICATE KEY UPDATE 
          `title`=:title, `file_count`=:file_count, `comment_count`=:comment_count,`revision`=:revision,`last_event_on`=:last_event_on";


        $STH = DB::prepare($sql);
        $STH->execute($data);
        $STH = NULL;
    }

    private function saveItemFieldValues($data, $fields)
    {
        try {

            //UNCOMMENT FOR DELTA-COPY
            // $sql = "INSERT  INTO `item_field_values` ( `identifier`, `src_app_id`, `src_item_id`, `src_field_id`,
            //        `src_field_external_id`, `type`, `value`,delta_need_update) VALUES (:identifier, :src_app_id, :src_item_id, :src_field_id,
            //        :src_field_external_id,:type, :value,1) ON DUPLICATE KEY UPDATE `value`=:value,`delta_need_update`=1";

            //NORMAL COPY
            $sql = "INSERT  INTO `item_field_values` ( `identifier`, `src_app_id`, `src_item_id`, `src_field_id`,
            `src_field_external_id`, `type`, `value`) VALUES (:identifier, :src_app_id, :src_item_id, :src_field_id, 
            :src_field_external_id,:type, :value) ON DUPLICATE KEY UPDATE `value`=:value";



            $STH = DB::prepare($sql);
            foreach ($fields as $field) {
                $data['src_field_id'] = $field['field_id'];
                $data['src_field_external_id'] = $field['external_id'];
                $data['type'] = $field['type'];
                $value = NULL;
                switch ($field['type']) {
                    case "text":
                    case "calculation":
                    case "number":
                    case "progress":
                    case "duration":
                        if (isset($field['values'][0]['value']))
                            $value = $field['values'][0]['value'];
                        break;

                    case "date":
                        $value = $this->getDateValue($field);
                        break;

                    case "phone":
                    case "email":
                        $value = $this->getPhoneEmailValues($field);
                        break;

                    case "embed":
                        $value = $this->getEmbedValues($field);
                        break;

                    case "location":
                        $value = $field['values'][0]['value'];
                        break;

                    case "category":
                        $value = $this->getCategoryValues($field);
                        break;

                    case "contact":
                        $value = $this->getContactValues($field);
                        break;

                    case "app":
                        $value = $this->getAppValues($field);
                        break;

                    case "tag":
                        $value = $this->getTagFieldValues($field);
                        break;

                    case "money":
                        $value = json_encode($field['values'][0]);
                        break;

                    case "image":
                        $value = $this->getImageFields($data['identifier'], $field['values'], $field['field_id']);
                        break;
                }
                $data['value'] = $value;
                $STH->execute($data);
            }
            $STH = NULL;
        } catch (\Exception $e) {
            Log::logError($e . "", array($data, $fields), "saveItemFieldValues");
        }
    }

    private function getImageFields($identifier, $values, $fieldID)
    {

        $value = array();
        try {
            $fileSaveValues = array();
            foreach ($values as $imageValue) {
                $value[] = $imageValue['value']['file_id'];
                $fileSaveValues[] = $imageValue['value'];
            }

            $fileRepo = new FileCopyRepo();
            $fileRepo->saveFilesToDB(array(
                "identifier" => $identifier,
                'src_ref_type' => "item_image_field",
                'src_ref_id' => $fieldID
            ), $fileSaveValues);
        } catch (\Exception $e) {
            Log::logError($e . "", $values, "getImageFields");
        }
        return json_encode($value);
    }

    private function getTagFieldValues($field)
    {
        $value = array();
        foreach ($field['values'] as $fieldValue) {
            $value[] = $fieldValue['value'];
        }
        return json_encode($value);
    }

    private function getAppValues($field)
    {
        $value = array();
        foreach ($field['values'] as $fieldValue) {

            $spaceId = $fieldValue['value']['space']['space_id'] ?? null;
            $appId = $fieldValue['value']['app']['app_id'] ?? null;
            $itemId = $fieldValue['value']['item_id'] ?? null;

            $value[] = array(
                'space_id' => $spaceId,
                'app' => $appId,
                'item_id' => $itemId
            );

            // $value[] = array(
            //     'space_id' => $fieldValue['value']['space']['space_id'],
            //     'app' => $fieldValue['value']['app']['app_id'],
            //     'item_id' => $fieldValue['value']['item_id']
            // );
        }
        // return json_encode($value);
        return json_encode(array_filter($value));
    }

    private function getContactValues($field)
    {
        $value = array();
        try {
            foreach ($field['values'] as $fieldValue) {
                $value[] = array(
                    'user_id' => $fieldValue['value']['user_id'],
                    'space_id' => $fieldValue['value']['space_id'],
                    'profile_id' => $fieldValue['value']['profile_id']
                );
            }
        } catch (\Exception $e) {
            Log::logError($e . "", $field, "getContactValues");
        }
        return json_encode($value);
    }

    private function getCategoryValues($field)
    {
        $value = array();
        foreach ($field['values'] as $fieldValue) {
            $value[] = $fieldValue['value']['id'];
        }
        return json_encode($value);
    }

    private function getEmbedValues($field)
    {
        $value = array();
        foreach ($field['values'] as $fieldValue) {
            $value[] = $fieldValue['embed']['original_url'];
        }
        return json_encode($value);
    }

    private function getDateValue($field)
    {
        $value = array();
        $fieldValue = $field['values'][0];
        if (isset($fieldValue['start_utc']))
            $value['start_utc'] = $fieldValue['start_utc'];

        if (isset($fieldValue['end_utc']))
            $value['end_utc'] = $fieldValue['end_utc'];

        if (isset($fieldValue['end_time_utc']))
            $value['end_time_utc'] = $fieldValue['end_time_utc'];

        if (isset($fieldValue['start_time_utc']))
            $value['start_time_utc'] = $fieldValue['start_time_utc'];

        return json_encode($value);
    }

    private function getPhoneEmailValues($field)
    {
        $value = $field['values'];
        return json_encode($value);
    }

    public function saveItemComments()
    {
        $sql = "SELECT `src_ref_id` FROM `old_comments` WHERE `new_comment_id`<1 GROUP BY `src_ref_id`";
        $STH = DB::prepare($sql);
        $STH->execute();
        $items = $STH->fetchAll(PDO::FETCH_ASSOC);
        $repo = new PodioAuthRepo();
        if ($repo->authenticate(1)) {
            if ($items && count($items) > 0) {
                foreach ($items as $item) {
                    try {
                        $podioItem = $this->customPodioAPI->podioGet("/item/" . $item['src_ref_id']);
                        $this->saveComments($item, $podioItem);
                    } catch (\Exception $e) {
                        Log::logError($e . "", $podioItem, "saveComments");
                        exit;
                    }
                }
            }
        }
    }

    public function ReplaceItemCommentsToOne()
    {
        try {
            echo "<pre>";
            $sql = "SELECT `src_ref_id` FROM `comments` GROUP BY `src_ref_id`";
            $STH = DB::prepare($sql);
            $STH->execute();
            $comment_items = $STH->fetchAll(PDO::FETCH_ASSOC);
            $sql1 = "SELECT * FROM `items` WHERE `src_item_id`=:src_item_id";
            $STH1 = DB::prepare($sql1);
            $repo = new PodioAuthRepo();
            $sql2 = "select * from `comments` 
             where  `src_ref_id` =:src_ref_id"; // and new_comment_id is null
            if ($repo->authenticateSF(2)) {
                if ($comment_items && count($comment_items) > 0) {
                    foreach ($comment_items as $comment_item) {
                        echo $comment_item['src_ref_id'];
                        echo "<br>";
                        $comment_count = 0;
                        $commentAttributes = array();
                        $commentAttributes2 = array();
                        $commentAttributes3 = array();
                        $commentAttributes4 = array();
                        $commentAttributes5 = array();
                        $commentAttributes6 = array();
                        $commentAttributes7 = array();
                        $newcommentAttributes = array();
                        $commentValue = "";
                        $commentValue2 = "";
                        $commentValue3 = "";
                        $commentValue4 = "";
                        $commentValue5 = "";
                        $commentValue6 = "";
                        $commentValue7 = "";
                        echo "Item id -- " . $comment_item['src_ref_id'] . "<br>";
                        $STH1->execute(array("src_item_id" => $comment_item['src_ref_id']));
                        $item = $STH1->fetchAll(PDO::FETCH_ASSOC);
                        $STH2 = DB::prepare($sql2);
                        $STH2->execute(array(
                            'src_ref_id' => $comment_item['src_ref_id']
                        ));
                        $new_comments = $STH2->fetchAll(PDO::FETCH_ASSOC);
                        if ($new_comments && count($new_comments) > 0) {
                            foreach ($new_comments as $new_comment) {
                                $comment_count += 1;
                                if ($comment_count == 1) {
                                    $createdComment = $this->itemCreatedByComment($item[0]);
                                    $commentValue .= $createdComment;
                                }
                                if ($comment_count <= 20) {
                                    $commentValue .= "\n" . $this->getCommentValue($new_comment['rich_value'], 1);
                                    if ($new_comment['file_count'] > 0) {
                                        $newFiles = $this->getNewFiles($new_comment);
                                        if ($newFiles)
                                            $commentValue .= "\n" . "\n" . $newFiles;
                                    }
                                    $commentValue .= $this->commentBy($new_comment);
                                } else if ($comment_count > 20 && $comment_count <= 40) {
                                    $commentValue2 .= "\n" . $this->getCommentValue($new_comment['rich_value'], 1);
                                    if ($new_comment['file_count'] > 0) {
                                        $newFiles = $this->getNewFiles($new_comment);
                                        if ($newFiles)
                                            $commentValue2 .= "\n" . "\n" . $newFiles;
                                    }
                                    $commentValue2 .= $this->commentBy($new_comment);
                                } else if ($comment_count > 40 && $comment_count <= 60) {
                                    $commentValue3 .= "\n" . $this->getCommentValue($new_comment['rich_value'], 1);
                                    if ($new_comment['file_count'] > 0) {
                                        $newFiles = $this->getNewFiles($new_comment);
                                        if ($newFiles)
                                            $commentValue3 .= "\n" . "\n" . $newFiles;
                                    }
                                    $commentValue3 .= $this->commentBy($new_comment);
                                } else if ($comment_count > 60 && $comment_count <= 80) {
                                    $commentValue4 .= "\n" . $this->getCommentValue($new_comment['rich_value'], 1);
                                    if ($new_comment['file_count'] > 0) {
                                        $newFiles = $this->getNewFiles($new_comment);
                                        if ($newFiles)
                                            $commentValue4 .= "\n" . "\n" . $newFiles;
                                    }
                                    $commentValue4 .= $this->commentBy($new_comment);
                                } else if ($comment_count > 80 && $comment_count <= 100) {
                                    $commentValue5 .= "\n" . $this->getCommentValue($new_comment['rich_value'], 1);
                                    if ($new_comment['file_count'] > 0) {
                                        $newFiles = $this->getNewFiles($new_comment);
                                        if ($newFiles)
                                            $commentValue5 .= "\n" . "\n" . $newFiles;
                                    }
                                    $commentValue5 .= $this->commentBy($new_comment);
                                } else if ($comment_count > 100 && $comment_count <= 120) {
                                    $commentValue6 .= "\n" . $this->getCommentValue($new_comment['rich_value'], 1);
                                    if ($new_comment['file_count'] > 0) {
                                        $newFiles = $this->getNewFiles($new_comment);
                                        if ($newFiles)
                                            $commentValue6 .= "\n" . "\n" . $newFiles;
                                    }
                                    $commentValue6 .= $this->commentBy($new_comment);
                                } else {
                                    $commentValue7 .= "\n" . $this->getCommentValue($new_comment['rich_value'], 1);
                                    if ($new_comment['file_count'] > 0) {
                                        $newFiles = $this->getNewFiles($new_comment);
                                        if ($newFiles)
                                            $commentValue7 .= "\n" . "\n" . $newFiles;
                                    }
                                    $commentValue7 .= $this->commentBy($new_comment);
                                }
                            }
                        }
                        $commentAttributes['value'] = $commentValue;
                        if ($commentValue2 != "") {
                            $commentAttributes2['value'] = $commentValue2;
                        }
                        if ($commentValue3 != "") {
                            $commentAttributes3['value'] = $commentValue3;
                        }
                        if ($commentValue4 != "") {
                            $commentAttributes4['value'] = $commentValue4;
                        }
                        if ($commentValue5 != "") {
                            $commentAttributes5['value'] = $commentValue5;
                        }
                        if ($commentValue6 != "") {
                            $commentAttributes6['value'] = $commentValue6;
                        }
                        if ($commentValue7 != "") {
                            $commentAttributes7['value'] = $commentValue7;
                        }
                        $created = false;
                        $comment_count = 0;
                        try {
                            $limit = 100;
                            $offset = 0;
                            do {
                                $attributes = array('limit' => $limit, 'offset' => $offset);
                                $iterationCount = 0;
                                $comments = $this->customPodioAPI->podioGet("/comment/item/" . $item[0]['dest_item_id'] . "/", $attributes);
                                if ($comments && is_array($comments) && count($comments) > 0) {
                                    $iterationCount = count($comments);
                                    foreach ($comments as $comment) {
                                        if ($comment['created_by']['user_id'] == 4856280) {
                                            $comment_count += 1;
                                            //                                            if ($comment_count > 1) {
                                            //                                                PodioComment::delete($comment['comment_id']);
                                            //                                            }
                                            if ($comment_count == 1) {
                                                try {
                                                    PodioComment::update($comment['comment_id'], $commentAttributes);
                                                } catch (\Exception $e) {
                                                    Log::logError($e . "", "saveComments");
                                                }
                                            }
                                            //                                            if (empty($commentAttributes2) && $comment_count == 2) {
                                            //                                                print_r("Inside Comment2");
                                            //                                                try {
                                            //                                                    PodioComment::update($comment['comment_id'], $commentAttributes);
                                            //                                                } catch (\Exception $e) {
                                            //                                                    Log::logError($e . "", "saveComments");
                                            //                                                }
                                            //                                            }
                                            //                                            if (!empty($commentAttributes2) && $comment_count == 2) {
                                            //                                                print_r("Inside Comment3");
                                            //                                                try {
                                            //                                                    PodioComment::update($comment['comment_id'], $commentAttributes2);
                                            //                                                } catch (\Exception $e) {
                                            //                                                    Log::logError($e . "", "saveComments");
                                            //                                                }
                                            //                                            }
                                        }
                                    }
                                    if (!empty($commentAttributes2)) {
                                        try {
                                            PodioComment::create("item", $item[0]['dest_item_id'], $commentAttributes2);
                                        } catch (\Exception $e) {
                                            Log::logError($e . "", "saveComments");
                                        }
                                    }
                                    if (!empty($commentAttributes3)) {
                                        try {
                                            PodioComment::create("item", $item[0]['dest_item_id'], $commentAttributes3);
                                        } catch (\Exception $e) {
                                            Log::logError($e . "", "saveComments");
                                        }
                                    }
                                    if (!empty($commentAttributes4)) {
                                        try {
                                            PodioComment::create("item", $item[0]['dest_item_id'], $commentAttributes4);
                                        } catch (\Exception $e) {
                                            Log::logError($e . "", "saveComments");
                                        }
                                    }
                                    if (!empty($commentAttributes5)) {
                                        try {
                                            PodioComment::create("item", $item[0]['dest_item_id'], $commentAttributes5);
                                        } catch (\Exception $e) {
                                            Log::logError($e . "", "saveComments");
                                        }
                                    }
                                    if (!empty($commentAttributes6)) {
                                        try {
                                            PodioComment::create("item", $item[0]['dest_item_id'], $commentAttributes6);
                                        } catch (\Exception $e) {
                                            Log::logError($e . "", "saveComments");
                                        }
                                    }
                                    if (!empty($commentAttributes7)) {
                                        try {
                                            PodioComment::create("item", $item[0]['dest_item_id'], $commentAttributes7);
                                        } catch (\Exception $e) {
                                            Log::logError($e . "", "saveComments");
                                        }
                                    }
                                }
                                $offset += $limit;
                            } while ($iterationCount > 0);
                        } catch (\Exception $e) {
                            Log::logError($e . "", "saveComments");
                        }
                    }
                    echo "Success";
                }
            }
        } catch (\Exception $e) {
            Log::logError($e . "", "saveComments");
            exit;
        }
    }


    public
    function getCommentValue($text, $identifier)
    {
        try {
            $text = $this->linkReplaceRepo->replaceLinks($text, $identifier);
            $value = $this->transformMentions($text);
            return $value;
        } catch (\Exception $e) {
            Log::logError($e . "", "saveComments");
            exit;
        }
    }

    public
    function transformMentions($string)
    {
        try {
            return preg_replace('/@\[(.*?)]\([\w]+:([\w]+)\)/i', '[$1](https://podio.com/users/$2)', $string);
        } catch (\Exception $e) {
            Log::logError($e . "", "saveComments");
            exit;
        }
    }

    public
    function getNewFiles($comment)
    {
        try {
            $sql = "select new_file_id  from files where `identifier`=:identifier 
        and  src_ref_id =:src_ref_id and src_ref_type=:src_ref_type and new_file_id is not null";
            $STH = DB::prepare($sql);

            $STH->execute(array(
                'identifier' => $comment['identifier'],
                'src_ref_id' => $comment['comment_id'],
                'src_ref_type' => "comment"
            ));

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

            if ($result && count($result) > 0) {
                $newFiles = "";
                foreach ($result as $newFileID) {
                    $newFileID = intval($newFileID['new_file_id']);
                    if ($newFileID > 0)
                        $newFiles .= "https://files.podio.com/" . $newFileID . "\n";
                }
                if ($newFiles != "")
                    return $newFiles;
            }
            return NULL;
        } catch (\Exception $e) {
            Log::logError($e . "", "saveComments");
            exit;
        }
    }

    public
    function commentBy($commentItem)
    {
        try {
            $id = substr($commentItem['created_by_url'], strrpos($commentItem['created_by_url'], '/') + 1);
            $linkRepo = new LinkReplaceRepo();
            $userId = $linkRepo->getNewUser($id);
            $itemRepo = new ItemCreateRepo();
            $commentItem['created_on'] = $itemRepo->formatDateTime($commentItem['created_on']);
            $commentItem['created_by_url'] = str_replace($id, $userId, $commentItem['created_by_url']);
            $comment = "\n" . "  " . "\n";
            $comment .= ' *by [' . $commentItem['created_by_name'] . '](' . $commentItem['created_by_url'] . ')*';
            $comment .= ' *on ' . $commentItem['created_on'] . '* ';
            $comment .= "\n" . "  " . "\n";
            $comment .= "   " . "--------------------------------------------------------------";
            return $comment;
        } catch (\Exception $e) {
            Log::logError($e . "", "saveComments");
            exit;
        }
    }

    public function itemCreatedByComment($item, $destId = null)
    {
        $id = substr($item['created_by_url'], strrpos($item['created_by_url'], '/') + 1);
        $linkRepo = new LinkReplaceRepo();
        $userId = $linkRepo->getNewUser($id);
        $item['created_by_url'] = str_replace($id, $userId, $item['created_by_url']);
        $itemRepo = new ItemCreateRepo();
        $item['created_on'] = $itemRepo->formatDateTime($item['created_on']);
        $commentValue = "*Item created by [" . $item['created_by_name'] . '](' . $item['created_by_url'] . ') on '
            . $item['created_on'] . '*  ';
        $commentValue .= PHP_EOL . "  " . PHP_EOL;
        $commentValue .= "   " . "--------------------------------------------------------------";
        return $commentValue;
    }
}

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