<?php

namespace modules\billmanagervps;

use email\Email;
use model\Bill;
use model\Client;
use model\ServiceCategories;
use modules\billmanagervps\classes\BillManagerAPI;
use modules\billmanagervps\classes\model\Order;
use modules\billmanagervps\classes\model\Plan;
use sms\SMS;
use System\Config;
use System\Cookie;
use System\Db\Db;
use System\Db\Schema\Schema;
use System\Db\Schema\Table;
use System\Notifier;
use System\Tools;
use System\View\View;

class billmanagervps extends \System\Module
{

    public $name = 'Ресселинг VPS (BillManager API)';
    public $author = '<a target="_blank" href="http://hopebilling.com">hopebilling.com</a>';
    public $paid = false;

    public function actionSetting()
    {
        $config = new Config('billmanagervps.module');

        if (Tools::rPOST()) {
            $config->url = Tools::rPOST('url');
            $config->username = Tools::rPOST('username');
            $config->password = Tools::rPOST('password');
            $config->save();
        }

        $view = $this->getModuleView('setting.php', 'admin');
        $view->bconfig = $config;

        return $view;
    }

    public function install()
    {
        $this->registerHook('getFrontLayoutMenu');
        $this->registerHook('getAdminLayoutMenu');
        $this->registerHook('payBill');
        $this->registerHook('dailyCronUpdate');
        $this->registerHook('getListServicesForBills');
        $this->registerHook('getListBills');
        $this->registerHook('afterGetListBills');

        Schema::create('billmanagervps_plans', function (Table $t) {
            $t
                ->increment('id')
                ->string('name')
                ->string('link')
                ->float('price')
                ->int('pricelist')
                ->text('description')
                ->int('price_id')
                ->int('period_id')
                ->text('additions')
                ->text('templates')
                ->create();
        });

        Schema::create('billmanagervps_orders', function (Table $t) {
            $t
                ->increment('id')
                ->int('plan_id')
                ->int('client_id')
                ->int('billorder_id')
                ->int('order_id')
                ->bool('active')
                ->text('ostempl')
                ->string('username')
                ->string('userpassword')
                ->string('password')
                ->string('domain')
                ->string('ip')
                ->bool('notified')
                ->date('paid_to')
                ->create();
        });


         return parent::install(); // TODO: Change the autogenerated stub
    }

    public function uninstall()
    {
        Schema::drop('billmanagervps_plans');
        Schema::drop('billmanagervps_orders');

        $config = new Config('billmanagervps.module');
        $config->remove();

        $billObject = new Bill();
        $billObject->where('type', 101)->removeRows();


        return parent::uninstall(); // TODO: Change the autogenerated stub
    }

    public function getAdminLayoutMenu(&$menu)
    {
        $menu['services'][] = (object)[
            'link' => Tools::link('modules/billmanagervps/orders'),
            'name' => 'Billmanager VDS',
            'icon' => 'fa-server',
            'items' => [
                (object)['link' => Tools::link('admin/modules/billmanagervps/orders'), 'name' => 'Заказы', 'icon' => 'glyphicon-shopping-cart'],
                (object)['link' => Tools::link('admin/modules/billmanagervps/plans'), 'name' => 'Тарифы', 'icon' => 'glyphicon-stats'],
            ]
        ];

    }

    public function getFrontLayoutMenu(&$menu)
    {

        $menu['orders'][] = (object)['link' => Tools::link('modules/billmanagervps/orders'), 'name' => 'VPS', 'icon' => 'glyphicon glyphicon-hdd'];
        $menu['create_orders'][] = (object)['link' => Tools::link('modules/billmanagervps/order/new'), 'name' => 'VPS', 'icon' => 'glyphicon glyphicon-hdd'];
    }

    /**
     * @param $billObject
     */
    public function payBill(&$billObject)
    {


        if ($billObject->is_paid && $billObject->type == 101) {


            $config = new Config('billmanagervps.module');
            $billManager = new BillManagerAPI($config->url, $config->username, $config->password);
            $orderObject = new Order($billObject->hosting_account_id);

            if (!$orderObject->billorder_id) {
                $planObject = new Plan($orderObject->plan_id);

                $addons = $planObject->additions;
                $addons = explode(PHP_EOL, $addons);

                $addons_formed = [];
                foreach ($addons as $addon) {
                    $res = explode('=', $addon);
                    $addons_formed[$res[0]] = $res[1];
                }
                $order = $billManager->createVds($planObject->pricelist, $billObject->pay_period, $orderObject->ostempl, $addons_formed, $orderObject->domain);

                if ($order) {
                    $orderObject->billorder_id = $order['billorder_id'];
                    $orderObject->order_id = $order['order_id'];
                    $orderObject->paid_to = date('Y-m-d', strtotime($orderObject->paid_to) + Cookie::ONE_MONAT * $billObject->pay_period);
                    $orderObject->active = 1;
                    $orderObject->save();

                    $billManager->payVds($orderObject->billorder_id);

                    $clientObject = new Client($orderObject->client_id);
                    $view = $this->getModuleView('admin/order/new.php', 'sms');;
                    $view2 = $this->getModuleView('order/new.php', 'sms');;
                    SMS::getGateway()->sendSMS($clientObject->phone, $view2->fetch());
                    SMS::getGateway()->sendSMS($config->site_sms, $view->fetch());
                }

            } else if ($orderObject->isLoadedObject()) {


                if (!$orderObject->active) {
                    $billManager->resumeVds($orderObject->order_id);
                    $orderObject->active = 1;
                }

                $orderObject->paid_to = date('Y-m-d', strtotime($orderObject->paid_to) + Cookie::ONE_MONAT * $billObject->pay_period);
                $orderObject->save();

            }


        }


    }

    public function getListServicesForBills(&$services)
    {
        $services['module_101'] = 'VPS';
    }

    public function getListBills($moduleDate)
    {
        $filter = Tools::rPOST('filter');
        $billObject = $moduleDate['billObject'];


        if ($filter['type']['value'] == 'module_101') {
            $billObject->where('type', 101);
        }

        $view = $moduleDate['view'];
        if (Tools::rGET('id_order_billmanager')) {
            $view->order = new Order(Tools::rGET('id_order_billmanager'));
            $billObject->where('hosting_account_id', '=', Tools::rGET('id_order_billmanager'));
        }
    }

    public function afterGetListBills(&$bills)
    {
        $plans = [];
        foreach ($bills as &$bill) {
            if ($bill->type == 101) {

                if (!isset($plans[$bill->hosting_account_id])) {
                    $orderObject = new Order($bill->hosting_account_id);
                    $planObject = new Plan($orderObject->plan_id);
                    $plans[$bill->hosting_account_id] = $planObject;
                }

                $planObject = $plans[$bill->hosting_account_id];

                $bill->plan = $planObject->name;
            }
        }

    }

    public function dailyCronUpdate()
    {
        $VpsOrder = new Order();
        $vps_orders = $VpsOrder->getRows();

        foreach ($vps_orders as $vps_order) {
            $VpsOrder = new Order($vps_order);


            $time_now = time();
            $now = date('Y-m-d');
            $account_paid = $VpsOrder->paid_to;
            $account_paid = strtotime($account_paid);


            $client = new Client($VpsOrder->client_id);

            if ($VpsOrder->active && ($account_paid - $time_now < 86400 * 3) && ($account_paid - $time_now) >= 0) {

                $time = $account_paid - $time_now;
                $days = ceil($time / (60 * 60 * 24));


                $bill = new \model\Bill();
                $res = $bill
                    ->where('type', Bill::TYPE_ORDER)
                    ->where('hosting_account_id', $VpsOrder->id)
                    ->where('client_id', $VpsOrder->client_id)
                    ->where('is_paid', 0)->getRow();

                if (!($res)) {


                    $bill = new \model\Bill();

                    $plan = new \model\VpsPlan($VpsOrder->plan_id);
                    $bill->hosting_account_id = $VpsOrder->id;
                    $bill->is_paid = 0;
                    $bill->client_id = $VpsOrder->client_id;
                    $bill->type = 101;
                    $bill->pay_period = 1;
                    $bill->hosting_plan_id = $plan->id;
                    $bill->price = $plan->price;
                    $bill->total = $plan->price;
                    $bill->date = date('Y-m-d');

                    if ($bill->save()) {

                    }

                }
            }
//echo time().' -- '.$account_paid. '<br>';
            $config = new Config('billmanagervps.module');
            $billManager = new BillManagerAPI($config->url, $config->username, $config->password);

            if (time() >= $account_paid && $VpsOrder->active == 1) {
                $VpsOrder->active = 0;
                $billManager->suspendVds($VpsOrder->order_id);
                $clientObject = new Client($VpsOrder->client_id);

                $email = new Email();
                $email->to = $clientObject->email;
                $eview = $this->getModuleView('order/suspend.php', 'email');
                $eview->order = $VpsOrder;
                $email->msg = $eview->fetch();
                $email->send();

                $view = $this->getModuleView('admin/order/suspend.php', 'sms');
                $view2 = $this->getModuleView('order/suspend.php', 'sms');;
                SMS::getGateway()->sendSMS($clientObject->phone, $view2->fetch());
                SMS::getGateway()->sendSMS($config->site_sms, $view->fetch());

                $VpsOrder->save();


            } else if ($VpsOrder->active == 0 && time() < $account_paid) {

                $VpsOrder->active = 1;
                $billManager->resumeVds($VpsOrder->order_id);
                $clientObject = new Client($VpsOrder->client_id);

                $email = new Email();
                $email->to = $clientObject->email;
                $eview = $this->getModuleView('order/unsuspend.php', 'email');
                $eview->order = $VpsOrder;
                $email->msg = $eview->fetch();
                $email->send();

                $view = $this->getModuleView('admin/order/unsuspend.php', 'sms');;
                $view2 = $this->getModuleView('order/unsuspend.php', 'sms');;
                SMS::getGateway()->sendSMS($clientObject->phone, $view2->fetch());
                SMS::getGateway()->sendSMS($config->site_sms, $view->fetch());

                $VpsOrder->save();

            }
        }
    }

}