<?php

namespace Admin\Controller;

use Exception;
use Lazer\Classes\Database;
use Lazer\Classes\Helpers\Validate;
use Lazer\Classes\LazerException;
use Application\Request;
use Application\Config;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Database\Connectors\ConnectionFactory;
use DateTime;
use PDO;

class SystemLogsController
{

    private $table, $database;
    private static $dbConnection = null;

    public function __construct()
    {
        $this->table = 'system_logs_' . $this->cleanString(Request::getOfferPath());
    }

    private function getDatabaseConnection()
    {
        if (self::$dbConnection === null) {
            try {
                $factory            = new ConnectionFactory();
                self::$dbConnection = $factory->make(array(
                    'driver'    => 'mysql',
                    'host'      => Config::settings('db_host'),
                    'username'  => Config::settings('db_username'),
                    'password'  => Config::settings('db_password'),
                    'database'  => Config::settings('db_name'),
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci',
                    'options' => [PDO::ATTR_EMULATE_PREPARES => true],
                ));
            } catch (Exception $ex) {
                
            }
        }
        return self::$dbConnection;
    }

    public function all($campaignType = '')
    {
        try {
            $row   = array();
            $query =  $this->getDatabaseConnection()->table($this->table)
                ->orderBy('id', 'desc');

            $totalRows = $this->getDatabaseConnection()->table($this->table)
                ->count();
            if (Request::form()->has('offset', 'limit') && Request::form()->get('limit') != 'all') {
                $data = $query
                    ->offset(Request::form()->get('offset'))
                    ->limit(Request::form()->get('limit'))
                    ->get();
                $data = $this->modifyData($data);
                return array(
                    'success'   => true,
                    'data'      => $data,
                    'totalData' => $totalRows,
                );
            }

            $data = $query
                ->get();
            
            $data = $this->modifyData($data);
            //gmdate("Y-m-d\TH:i:s\Z")
            return array(
                'success'   => true,
                'data'      => $data,
                'totalData' => $totalRows,
            );
        } catch (Exception $ex) {
            return array(
                'success'       => false,
                'error_message' => $ex->getMessage(),
            );
        }
    }
    
    public function getLog($id)
    {
        try {
            $row   = array();
            $query =  $this->getDatabaseConnection()->table($this->table)
                ->where('id', $id);
            $data = $query
                ->get();
            $data = $this->modifyData($data);
            return array(
                'success'   => true,
                'data'      => $data
            );
        } catch (Exception $ex) {
            return array(
                'success'       => false,
                'error_message' => $ex->getMessage(),
            );
        }
    }
    
    public function modifyData($data)
    {
        foreach ($data as $listKey => $listValue) {
            if(!empty($data[$listKey]['created_on'])){
                $source = $data[$listKey]['created_on'];
                $date = new DateTime($source);
                $data[$listKey]['created_on'] = $date->format('Y-m-d\TH:i:s\Z');
            }
            if(!empty($data[$listKey]['http_request'])) {
            	$httpRequestArray = json_decode($data[$listKey]['http_request'], true);
            	$data[$listKey]['http_request'] = $httpRequestArray['10015'];
            }
            $data[$listKey]['url'] = $httpRequestArray['10002'];
        }
        return $data;
    }

    public function checkExtensions()
    {
        $result = array(
            'success' => true,
            'extensionSystemLogsActive' => false,
        );
        $extensions = Config::extensions();

        $extensions = Config::extensions();
        foreach ($extensions as $extension)
        {
            if ($extension['extension_slug'] !== 'SystemLogs')
            {
                continue;
            }
            if ($extension['active'] === true)
            {
                $result['extensionSystemLogsActive'] = true;
            }
            break;
        }

        return $result;
    }
    
    private function cleanString($string)
    {
        return preg_replace('/[^A-Za-z0-9\-]/', '', str_replace('-', '_', $string)); 
    }

}
