<?php

namespace App\Model\Table;

use App\Utility\Common;
use Cake\ORM\Table;

class AppTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('Timestamp');
    }
    //geting the current time with system time
    public function getSystemCurrentTimeStamp($formate = '', $time_zone = '')
    {
        if (!empty($time_zone)) {
            date_default_timezone_set($time_zone);
        } else {
            $current_time_zone = $this->getMemberTimeZone();
            if (!empty($current_time_zone)) {
                date_default_timezone_set($current_time_zone);
            } else {
                date_default_timezone_set("UTC");
            }
        }

        if ($formate == '') {
            return date("Y-m-d H:i:s");
        } else {
            return date($formate);
        }
    }

    public function getCompanyId()
    {
        //$session = $_SESSION;
        if (isset($_SESSION['company_info']) && !empty($_SESSION['company_info'])) {
            return $_SESSION['company_info']['id'];
        } else {
            return 0;
        }
    }


    public function getMemberTimeZone()
    {
        return $_SESSION['Auth']['User']['time_zone'];
    }

    public function daysBetween($from_date, $to_date)
    {
        return Common::daysBetweenDate($from_date, $to_date);
    }


    public function reminderDaysCalculation($difference, $id)
    {

        $day_string = "";
        if ($difference < 0) {
            $info[$id]['color'] = 'R';
            $over_day = abs($difference);
            if ($over_day == 1) {
                $day_string = $over_day . " day over";
            } else {
                $day_string = $over_day . " days over";
            }
        } else {
            $info[$id]['color'] = 'Y';
            $day_string = $difference . " days till due";

            if ($difference == 0) {
                $day_string = "Today";
            } else if ($difference == 1) {
                $day_string = $difference . " day till due";
            }
        }

        $result['color_info'] = $info;
        $result['day_string'] = $day_string;
        return $result;
    }

    public function reminderOrganizeList($remainders, $is_with_today = true, $total_unread_count = 0)
    {
        $result = [];

        $current_date = $this->getSystemCurrentTimeStamp('Y-m-d');

        $assoc_info['today'] = [];
        $assoc_info['due'] = [];
        $assoc_info['over'] = [];
        $total_unread = 0;
        if (count($remainders) > 0) {

            foreach ($remainders as $remainder) {

                $info['client_id'] = $remainder->client_id;
                $info['title'] = $remainder->title;
                //$info['description'] = $remainder->description;
                $info['name'] = $remainder->name;
                $info['is_read'] = $remainder->is_read;
                $info['reminder_date'] = $remainder->remainder_date;
                $info['user_type'] = $remainder->user_type;
                $info['created_by'] = $remainder->created_by;

                if (!empty($info['reminder_date'])) {
                    $info['reminder_date'] = date('Y-m-d', strtotime($info['reminder_date']));
                }

                $difference = $this->daysBetween($current_date, $info['reminder_date']);
                $info['diff'] = $difference;

                $reminder_calculation = $this->reminderDaysCalculation($difference, $remainder->id);

                $day_string = $reminder_calculation['day_string'];

                if (!empty($day_string)) {
                    $info['days'] = $day_string;
                }
                if ($remainder->is_read == 0) {
                    $total_unread++;
                }

                if (isset($reminder_calculation['color_info'][$remainder->id]['color']) && !empty($reminder_calculation['color_info'][$remainder->id]['color'])) {
                    $info['color'] = $reminder_calculation['color_info'][$remainder->id]['color'];
                }

                if ($difference == 0) {
                    $assoc_info['today'][$remainder->id] = $info;
                } else if ($difference > 0) {
                    $assoc_info['due'][$remainder->id] = $info;
                } else {
                    $assoc_info['over'][$remainder->id] = $info;
                }
            }

            if (!empty($assoc_info['today'])) {
                uasort($assoc_info['today'], function ($item1, $item2) {
                    return $item1['diff'] - $item2['diff'];
                });
            }
            //pr($assoc_info);exit;
            if (!empty($assoc_info['due'])) {
                uasort($assoc_info['due'], function ($item1, $item2) {
                    return $item1['diff'] - $item2['diff'];
                });
            }

            if (!empty($assoc_info['over'])) {
                uasort($assoc_info['over'], function ($item1, $item2) {
                    return $item2['diff'] - $item1['diff'];
                });
            }

            $final_info = [];

            if ($is_with_today) {
                $final_info = $assoc_info['today'];
            }

            if (!empty($assoc_info['due'])) {
                $final_info += $assoc_info['due'];
            }

            if (!empty($assoc_info['over'])) {
                $final_info += $assoc_info['over'];
            }

            if ($total_unread_count > 0) {
                $total_unread = $total_unread_count;
            }

            $result = [
                "remainders" => $final_info,
                "due" => $assoc_info['due'],
                "over" => $assoc_info['over'],
                "today" => $assoc_info['today'],
                "total_unread" => $total_unread,
                "total_remainder" => $total_unread
            ];
        }

        return $result;
    }


    public function uploadHtmlContent($id, $member_id, $content, $table, $db_column, $file_dir)
    {
        $result = false;
        $dir = "";
        if ($id > 0 && $member_id > 0 && !empty($content)) {
            $dir = WWW_ROOT . $file_dir . "/" . $member_id;
            if (!is_dir($dir)) {
                @mkdir($dir, 0777, true);
            }
            $file_name = $id . ".html";
            if (!empty($file_name)) {
                $dir .= "/" . $file_name;
                file_put_contents($dir, $content);
                $table->updateAll([$db_column => $file_name], ['id' => $id]);
            }

            $result = true;
        }

        return $dir;
    }

    public function uploadContent($id, $member_id, $content, $table, $db_column, $file_dir)
    {
        $result = false;
        $dir = "";
        if ($id > 0 && $member_id > 0 && !empty($content)) {
            $relative_path = $file_dir . "/" . $member_id;
            $dir = WWW_ROOT . $relative_path;
            if (!is_dir($dir)) {
                @mkdir($dir, 0777, true);
            }
            $file_name = $id . "_" . $content['name'];
            if (!empty($file_name)) {
                $dir .= "/" . $file_name;
                @move_uploaded_file($content['tmp_name'], $dir);
                // file_put_contents($dir,$content['tmp_name']);
                $table->updateAll([$db_column => $relative_path . "/" . $file_name], ['id' => $id]);
            }

            $result = true;
        }

        return $dir;
    }

    public function getContentById($file_path)
    {
        $content = "";
        if (file_exists($file_path)) {
            $content = file_get_contents($file_path);
        }
        return $content;
    }


    public function getCurrentUserType()
    {
        $common = new \App\Utility\Common;
        return $common->getCurrentUserInfo();
    }

    public function get_time_ago_in_number($current_time, $created_time)
    {
        $date = date_create($created_time);
        $created_time  = date_format($date, "Y-m-d H:i:s");
        $time_difference = strtotime($current_time) - strtotime($date);


        if ($time_difference < 1) {
            return $time_difference;
        }
        $condition = array(
            12 * 30 * 24 * 60 * 60 =>  'year',
            30 * 24 * 60 * 60       =>  'month',
            24 * 60 * 60            =>  'day',
            60 * 60                 =>  'hour',
            60                      =>  'minute',
            1                       =>  'second'
        );

        foreach ($condition as $secs => $str) {
            if ($secs == 1) {
                return $secs;
            }
            $d = $time_difference / $secs;

            if ($d >= 1) {
                return $d;
            }
        }
    }
}
