<?php
require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/api_curl.class.php';

use Luracast\Restler\RestException;

require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT . '/custom/bbus/class/basicservices.class.php';

class TicketChecker
{
    use CurlApi;

    private $db;
    private $mac;
    private $code;
    private $lat;
    private $lon;
    private $printingTime;
    private $status = 0;
    private $device_id;
    private $service_location_id;
    private $product_id;
    private $fils = array();
    private $ticketIdForCheck;
    private $basic_service_id;
    private $ticket_id;
    private $bbTicketRowId;
    private $usage;
    private $facture_id;
    private $bundle_id;
    private $merged_tickets;
    private $imei;
    private $validated_at;
    private $expire_at;
    private $duration;
    private $productObj;
    private $factureObj;
    private $bbticketNaploObj;
    private $bbDevicesObj;
    private $BbDevicesServiceLocationObj;
    private $BbDevicesServiceLocationProductObj;
    private $bbticketObj;
    private $bbticketInvoicePrintingObj;



    public function __construct()
    {
        global $db, $conf, $user;

        $this->db = $db;
        $this->user = $user;
        $this->productObj = new Product($this->db);
        $this->factureObj = new Facture($this->db);
        $this->bbticketNaploObj = new BbTicketNaplo($this->db);
        $this->bbDevicesObj = new BbDevices($this->db);
        $this->BbDevicesServiceLocationObj = new BbDevicesServiceLocation($this->db);
        $this->BbDevicesServiceLocationProductObj = new BbDevicesServiceLocationProduct($this->db);
        $this->bbticketObj = new BbTicket($this->db);
        $this->bbticketInvoicePrintingObj = new BbTicketInvoicePrinting($this->db);
    }

    public function setMac($mac)
    {
        $this->mac = $mac;
    }

    public function setCode($code)
    {
        $code_and_timstamp = explode('_', $code);
        $this->code = $code_and_timstamp[0];
    }

    public function setLat($lat)
    {
        $this->lat = $lat;
    }

    public function setLon($lon)
    {
        $this->lon = $lon;
    }

    public function setTimestamp($code, $log, $logId)
    {
        global $user;
        $code_and_timstamp = explode('_', $code);
        $this->printingTime = $code_and_timstamp[1];
        if (empty($this->printingTime)) {
            ApiBbusLog::$log("{$logId} Timestamp is empty!");
            throw new RestException(404, 'Timestamp is empty!');
        }
    }

    public function setImei($imei, $logId)
    {
        global $user;
        $this->imei = $imei;
        if (empty($this->imei)) {
            ApiBbusLog::ticketvalidationByPhone("{$logId} IMEI is empty!");
            throw new RestException(404, 'IMEI is empty!');
        }
    }

    public function SetTicketidFromPhone($ticketid, $logId)
    {
        $this->ticket_id = $ticketid;
        ApiBbusLog::ticketvalidationByPhone("{$logId} Ticketid: {$this->ticket_id}");
        if (empty($this->ticket_id)) {
            ApiBbusLog::ticketvalidationByPhone("{$logId} Ticketid is empty!");
            throw new RestException(404, 'Ticketid is empty!');
        }
    }

    public function set_device_id()
    {
        $result = $this->bbDevicesObj->fetchAll('ASC', 'date_creation', 1, 0, ["customsql" => "device_id = '" . $this->mac . "'"]);
        $this->setId($result, 'BbDevices', 'device_id', 'id');
    }

    public function set_service_location_id()
    {
        $result = $this->BbDevicesServiceLocationObj->fetchAll('ASC', 'date_creation', 1, 0, ['customsql' => "device_id = " . $this->device_id]);
        $this->setId($result, 'device_servicelocation', 'service_location_id', 'id');
    }

    public function set_basic_service_id()
    {
        $result = $this->BbDevicesServiceLocationProductObj->fetchAll('ASC', 'date_creation', 1, 0, ['customsql' => "devicesservicelocation_id = " . $this->service_location_id]);
        $this->setId($result, 'device_service_location_product', 'basic_service_id', 'basic_service');
    }

    public function get_Basic_service_array()
    {
        $productRowIdsArray = [];
        $sql = "SELECT fk_object FROM " . $this->db->prefix() . $this->productObj->table_element . "_extrafields WHERE basic_service = '{$this->basic_service_id}'";
        $productsRowIDs = $this->db->query($sql);
        while ($row = pg_fetch_assoc($productsRowIDs)) {
            $productRowIdsArray[] = $row['fk_object'];
        }
        return $productRowIdsArray;
    }

    public function setTicketId($logId)
    {
        $this->set_device_id();
        $this->set_service_location_id();
        $this->set_basic_service_id();
        $this->set_ticketIDForCheck();

        if (!isset($this->ticketIdForCheck)) {
            ApiBbusLog::getByBarcode("{$logId} Invalid ticket");
            throw new RestException(404, 'Invalid ticket');
        }
        $sqlBbticketInvoicePrinting = "SELECT * FROM " . $this->db->prefix() . $this->bbticketInvoicePrintingObj->table_element . " WHERE printing_date_timestamp ILIKE '%{$this->printingTime}%' AND product_id = {$this->ticketIdForCheck}";
        //print $sqlBbticketInvoicePrinting;exit;
        $resultBBT = $this->db->query($sqlBbticketInvoicePrinting);
        while ($row = pg_fetch_assoc($resultBBT)) {
            $result2[$row['rowid']] = (object) $row;
        }
        //print_r($result2);exit;
        $this->setId($result2, 'bbticketinvoiceprinting', 'ticket_id', 'ticket_id');

    }

    public function set_ticketIDForCheck()
    {
        $basic_service_array = $this->get_Basic_service_array();
        foreach ($this->fils as $elem) {
            if (in_array($elem, $basic_service_array)) {
                $this->ticketIdForCheck = $elem;
            }
        }
    }

    public function check5Minutes($logId)
    {
        ApiBbusLog::getByBarcode("check5Minutes!!!!");
        $result = $this->bbticketNaploObj->fetchAll('DESC', 'rowid', 1, 0, ["customsql" => "ticket_row_id = {$this->bbTicketRowId}"]);
        if ($result > 0) {
            foreach ($result as $ticket) {
                if (strtotime("+5 minutes", $ticket->date_creation) > dol_now()) {
                    ApiBbusLog::getByBarcode("{$logId} Too fast!");
                    throw new RestException(401, 'Too fast');
                }
            }
        }
    }

    public function setFilsArray()
    {
        if (is_null($this->facture_id)) {
			$this->curlSetFilsArray($this->code);
		}else{
        $sql = "SELECT fdet.fk_product FROM " . $this->db->prefix() . $this->factureObj->table_element . " AS f
		INNER JOIN " . $this->db->prefix() . $this->factureObj->table_element_line . " as fdet ON fdet.fk_facture = f.rowid
		INNER JOIN " . $this->db->prefix() . $this->productObj->table_element . " AS p ON p.rowid = fdet.fk_product
		WHERE f.rowid = {$this->facture_id}";
        $result = $this->db->query($sql);
        while ($sqlDataResult = pg_fetch_assoc($result)) {
            $this->fils[] = $sqlDataResult['fk_product'];
        }
        }
    }

    public function curlSetFilsArray($ref)
    {
        $postFields = '{"ref":"' . $ref . '"}';
        $this->fils = $this->curlRunner('bbus/curlGetFilsArray', $postFields, 'POST', true);
    }

    public function setFactureId($log, $logId)
    {
        $sqlFacture = "SELECT rowid FROM " . $this->db->prefix() . $this->factureObj->table_element . " WHERE ref ILIKE '%{$this->code}%'";
        $result = $this->db->query($sqlFacture);
        if (pg_num_rows($result) > 0) {
            while ($adatok = pg_fetch_assoc($result)) {
                $factureRowid = $adatok['rowid'];
            }
        } else {
            ApiBbusLog::$log("{$logId} Invoice not found. Maybe cross-shopping: {$this->code}");
            $this->facture_id = null;
            //throw new RestException(404, 'Invoice not found.');
        }
        if(!is_null($factureRowid)){
        $sql = "SELECT rowid FROM " . $this->db->prefix() . $this->factureObj->table_element . " WHERE fk_facture_source = {$factureRowid} AND type = 2";
        $res = $this->db->query($sql);
        if (pg_num_rows($res) > 0) {
            ApiBbusLog::$log("{$logId} Invoice has a Credit account.");
            throw new RestException(404, 'Invoice has a Credit account.');
        }

        $this->facture_id = $factureRowid;
    }
    }

    public function setBbTicketRowId($id)
    {
        $this->bbTicketRowId = $id;
    }

    public function saveData($selectedTicket)
    {
        global $user;
        if ($this->newTicket($selectedTicket)) {
            $this->validated_at = date('Y-m-d H:i:s');
            $this->setDurationByProductId($selectedTicket->ticket_id);
            $this->setExpireAt($selectedTicket);
            $this->setUsage($selectedTicket);
            if ($this->merged_tickets) {
                $tickets = $this->getAllTicketsByfactureIdAndTimestamp();
                foreach ($tickets as $key => $value) {
                    $sql = "UPDATE " . $this->db->prefix() . $this->bbticketObj->table_element . " SET validated_at = '" . $this->validated_at . "', expire_at = '" . $this->expire_at . "'";
                    if ($key == $this->bbTicketRowId && $this->usage != 0) {
                        $sql .= ", usage = '" . $this->usage . "'";
                    }
                    $sql .= " WHERE rowid = " . $key;
                    $this->bbTicketRowId = $key;
                    $this->saveAndCreateNaplo($sql);
                }
            } else {
                $sql = "UPDATE " . $this->db->prefix() . $this->bbticketObj->table_element . " SET usage = '" . $this->usage . "', validated_at = '" . $this->validated_at . "', expire_at = '" . $this->expire_at . "' WHERE rowid = " . $this->bbTicketRowId;
                $this->saveAndCreateNaplo($sql);
            }
        } else {
            $this->setUsage($selectedTicket);
            $sql = "UPDATE " . $this->db->prefix() . $this->bbticketObj->table_element . " SET usage = '" . $this->usage . "' WHERE rowid = " . $this->bbTicketRowId;
            $this->saveAndCreateNaplo($sql);
        }
    }

    public function saveCoordinates($logId)
    {
        global $db, $user;
        $bbTicketValidationCoordsObj = new BbTicketValidationCoords($db);
        $bbTicketValidationCoordsObj->fk_ticket = $this->bbTicketRowId;
        $bbTicketValidationCoordsObj->device_id = $this->device_id;
        $bbTicketValidationCoordsObj->location_id = $this->service_location_id;
        $bbTicketValidationCoordsObj->lat = $this->lat;
        $bbTicketValidationCoordsObj->lon = $this->lon;
        if ($bbTicketValidationCoordsObj->create($user) < 0) {
            ApiBbusLog::getByBarcode("{$logId} ##ERROR## Nem sikerult menteni a jegy koordinatait.");
            dol_syslog("{$logId} ##ERROR## Nem sikerult menteni a jegy koordinatait.", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
        }
        ApiBbusLog::getByBarcode("{$logId} Koordinatak mentve");
    }

    private function newTicket($selectedTicket)
    {
        return is_null($selectedTicket->validated_at) && is_null($selectedTicket->expire_at) || empty($selectedTicket->validated_at) && empty($selectedTicket->expire_at);
    }

    private function setExpireAt($selectedTicket)
    {
        $discountArray = $this->getDiscountFromfacturedet($selectedTicket->ticket_id);
        if (!empty($discountArray)) {
            $this->expire_at = date('Y-m-d H:i:s', strtotime($this->validated_at . ' +' . substr($this->duration, 0, -1) . ' ' . $this->getIntervalTimeByDuration() . ' +' . $discountArray['value'] . ' hours'));
        } else {
            $this->expire_at = date('Y-m-d H:i:s', strtotime($this->validated_at . ' +' . substr($this->duration, 0, -1) . ' ' . $this->getIntervalTimeByDuration()));
        }
    }

    private function getDiscountFromFActuredet($ticket_id)
    {
        $sql = "SELECT fdete.discount_hours AS value FROM " . $this->db->prefix() . $this->factureObj->table_element . " AS f
            INNER JOIN " . $this->db->prefix() . $this->factureObj->table_element_line . " AS fdet ON f.rowid = fdet.fk_facture
            INNER JOIN " . $this->db->prefix() . "facturedet_extrafields AS fdete ON fdete.fk_object = fdet.rowid
            WHERE f.rowid = {$this->facture_id} AND fdet.fk_product = {$ticket_id}";
        $res = $this->db->query($sql);
        if (pg_num_rows($res) > 0) {
            while ($adatok = pg_fetch_assoc($res)) {
                return $adatok;
            }
        } else {
            return [];
        }
    }

    private function setDurationByProductId($ticket_id)
    {
        $sql = "SELECT p.duration as duration  FROM " . $this->db->prefix() . $this->productObj->table_element . " AS p WHERE rowid = " . $ticket_id;
        $result = $this->getDataFromDatabase($sql, "Product");
        $this->duration = $this->getIdFromResult($result, 'duration');
    }

    private function getIdFromResult($res, $fieldName)
    {
        while ($adatok = pg_fetch_assoc($res)) {
            return $adatok[$fieldName];
        }
    }

    private function getIntervalTimeByDiscountPeriod($period)
    {
        switch ($period) {
            case 'hour':
                return 'hours';
            case 'day':
                return 'days';
            default:
                return 'hours';
        }
    }

    private function getIntervalTimeByDuration()
    {
        $duration = $this->duration[-1];
        switch ($duration) {
            case 'h':
                return 'hours';
            case 'd':
                return 'days';
            case 'w':
                return 'weeks';
            case 'm':
                return 'months';
            case 'y':
                return 'years';
            default:
                return 'hours';
        }
    }

    private function setUsage($selectedTicket)
    {
        $this->usage = $selectedTicket->usage;
        if ($selectedTicket->usable_occasions !== 0) {
            $this->usage++;
        }
    }

    private function getAllTicketsByfactureIdAndTimestamp()
    {
        $tickets = [];
        $sql = "SELECT ip.ticket_id, t.usable_occasions FROM " . $this->db->prefix() . $this->bbticketInvoicePrintingObj->table_element . " as ip
		INNER JOIN " . $this->db->prefix() . $this->bbticketObj->table_element . " as t ON t.rowid = ip.ticket_id
		WHERE ip.printing_date_timestamp = '{$this->printingTime}' AND ip.fk_facture = {$this->facture_id}";
        $res = $this->db->query($sql);
        while ($result = pg_fetch_assoc($res)) {
            $tickets[$result['ticket_id']] = $result['usable_occasions'];
        }
        return $tickets;
    }

    public function checkExceptionHandlers($selectedTicket, $log, $logId)
	{
		$now = strtotime(date("Y-m-d H:i:s"));
		if ($selectedTicket->usage == $selectedTicket->usable_occasions && $selectedTicket->usable_occasions != 0) {
            ApiBbusLog::$log("{$logId} Out of usage!");
			$this->ExceptionHandler(2, 'Out of usage!');
		}

		if ($selectedTicket->available_at < $now || ((!is_null($selectedTicket->expire_at) && !empty($selectedTicket->expire_at)) && $selectedTicket->expire_at < $now)) {
            ApiBbusLog::$log("{$logId} Expired!");
			$this->ExceptionHandler(1, 'Expired');
		}

	}

    private function ExceptionHandler($status, $message)
	{
		$this->status = $status;
		$this->saveBbTicketNaplo();
		throw new RestException(401, $message);
	}


    private function saveAndCreateNaplo($sql)
    {
        $this->bbticketUpdate($sql);
        $this->saveBbTicketNaplo();
    }

    private function bbticketUpdate($sql)
    {
        $updated = $this->db->query($sql);
        if (!$updated) {
            dol_syslog("Nem sikerult a ticketek updateje. facture_id: " . $this->facture_id, LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
            throw new RestException(404, 'Update failed');
        }
    }

    private function saveBbTicketNaplo()
    {
        global $user;
        $bbTicketNaplo = new BbTicketNaplo($this->db);
        $bbTicketNaplo->ticket_row_id = $this->bbTicketRowId;
        $bbTicketNaplo->bbservicelocation_id = isset($this->service_location_id) ? $this->service_location_id : null;
        $bbTicketNaplo->device_id = isset($this->device_id) ? $this->device_id : null;
        $bbTicketNaplo->status = $this->status;


        if ($bbTicketNaplo->create($user) < 0) {
            print_r($bbTicketNaplo->error);exit;
            dol_syslog('Nem sikerult menteni a bbticketNaplo tablaba a rekordot.', LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
            throw new RestException(500, 'Nem sikerult menteni a bbticketNaplo tablaba a rekordot.');
        }
    }

    public function setMergedTickets($selectedTicket, $log, $logId)
    {
        $this->bundle_id = $selectedTicket->bundle_id;
        $sql = "SELECT merged_tickets FROM " . $this->db->prefix() . "product_extrafields WHERE fk_object = " . $this->bundle_id;
        $result = $this->getDataFromDatabase($sql, "Product_extrafields");

        while ($adatok = pg_fetch_assoc($result)) {
            $this->merged_tickets = $adatok['merged_tickets'] == 1 ? true : false;
            if($this->merged_tickets){
                ApiBbusLog::$log("{$logId} Merged ticket");
            }
        }
    }

    public function checkBbTicketInvoicePrinting()
    {
        $result = $this->bbticketInvoicePrintingObj->fetchAll('', '', 0, 0, ['customsql' => "printing_date_timestamp = '{$this->printingTime}' AND fk_facture = {$this->facture_id} AND ticket_id = {$this->ticket_id}"]);
        $this->checkResult($result, 'bbticketinvoiceprinting');
    }

    public function getDataOfTheSelectedTicket()
    {
        $result = $this->bbticketObj->fetchAll('ASC', 'rowid', 0, 0, ['customsql' => "rowid = {$this->ticket_id} AND fk_ticket IS NULL"]);
        $this->checkResult($result, 'bbticket');

        foreach ($result as $device) {
            $selectedTicket = $device;
        }
        return $selectedTicket;
    }

    #_______________________________________________________________


    private function getDataFromDatabase($sql, $name)
    {
        $res = $this->db->query($sql);
        $this->checkValidation($res, $name);
        return $res;
    }

    private function checkValidation($res, $name)
    {
        if (pg_num_rows($res) == 0) {
            throw new RestException(404, $name . ' not found');
        }
    }

    private function setId($result, $tableName, $variableName, $fieldName)
    {
        $this->checkResult($result, $tableName);
        foreach ($result as $device) {
            $this->$variableName = $device->$fieldName;
        }
    }

    private function checkResult($result, $tableName)
    {
        if (!is_array($result) || empty($result)) {
            dol_syslog("A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
            throw new RestException(404, "A megadott szuresi adatokhoz nem tartozik rekord ({$tableName}).");
        }
    }

    public function getTicketTypeByProductId($product_id){
        $productObj = new Product($this->db);
        $result = $productObj->fetch($product_id);
        if($result > 0){
            $basicServicesObj = new BasicServices($this->db);
            $resultBS = $basicServicesObj->fetch($productObj->array_options['options_basic_service']);
            if($resultBS > 0){
                return $basicServicesObj->server_host;
            }
        }else{
            return false;
        }
    }
}