<?php

namespace DataAccess\ServiceMessages;


use BusinessLogic\ServiceMessages\GetServiceMessagesFilter;
use BusinessLogic\ServiceMessages\ServiceMessage;
use BusinessLogic\ServiceMessages\ServiceMessageLocation;
use BusinessLogic\ServiceMessages\ServiceMessageStyle;
use DataAccess\CommonDao;

class ServiceMessagesGateway extends CommonDao {
    /**
     * @param $serviceMessage ServiceMessage
     * @return ServiceMessage
     */
    function createServiceMessage($serviceMessage, $heskSettings) {
        $this->init();

        // Get the latest service message order
        $res = hesk_dbQuery("SELECT `order` FROM `" . hesk_dbEscape($heskSettings['db_pfix']) . "service_messages` ORDER BY `order` DESC LIMIT 1");
        $row = hesk_dbFetchRow($res);
        $myOrder = intval($row[0]) + 10;

        $style = ServiceMessageStyle::getIdForStyle($serviceMessage->style);
        $type = $serviceMessage->published ? 0 : 1;

        // Insert service message into database
        hesk_dbQuery("INSERT INTO `" . hesk_dbEscape($heskSettings['db_pfix']) . "service_messages` (`author`,`title`,`message`,`style`,`type`,`order`, `icon`, `mfh_language`) VALUES (
            '" . intval($serviceMessage->createdBy) . "',
            '" . hesk_dbEscape($serviceMessage->title) . "',
            '" . hesk_dbEscape($serviceMessage->message) . "',
            '" . hesk_dbEscape($style) . "',
            '{$type}',
            '{$myOrder}',
            '" . hesk_dbEscape($serviceMessage->icon) . "',
            '" . hesk_dbEscape($serviceMessage->language) . "'
            )");

        $serviceMessage->id = hesk_dbInsertID();

        foreach ($serviceMessage->locations as $location) {
            hesk_dbQuery("INSERT INTO `" . hesk_dbEscape($heskSettings['db_pfix']) . "mfh_service_message_to_location` 
                (`service_message_id`, `location`) VALUES (" . intval($serviceMessage->id) . ", '" . hesk_dbEscape($location) . "')");
        }

        // Get the autogenerated fields
        $rs = hesk_dbQuery("SELECT `dt`, `order` FROM `" . hesk_dbEscape($heskSettings['db_pfix']) . "service_messages` 
            WHERE `id` = " . intval($serviceMessage->id));
        $row = hesk_dbFetchAssoc($rs);
        $serviceMessage->dateCreated = $row['dt'];
        $serviceMessage->order = intval($row['order']);

        $this->close();

        return $serviceMessage;
    }

    /**
     * @param $heskSettings
     * @param $searchFilter GetServiceMessagesFilter
     * @return ServiceMessage[]
     */
    function getServiceMessages($heskSettings, $searchFilter) {
        $this->init();

        $serviceMessages = array();

        $sql = "SELECT DISTINCT `service_messages`.* FROM `". hesk_dbEscape($heskSettings['db_pfix']) . "service_messages` AS `service_messages` ";

        if (!$searchFilter->includeStaffServiceMessages) {
            $sql .= "INNER JOIN `" . hesk_dbEscape($heskSettings['db_pfix']) . "mfh_service_message_to_location` AS `location`
                ON `location`.`service_message_id` = `service_messages`.`id` AND `location`.`location` LIKE 'CUSTOMER%' ";
        }

        if (!$searchFilter->includeDrafts) {
            $sql .= "WHERE `type` = '0' ";
        }

        $sql .= "ORDER BY `order`";


        $rs = hesk_dbQuery($sql);
        while ($row = hesk_dbFetchAssoc($rs)) {
            $serviceMessage = new ServiceMessage();
            $serviceMessage->id = $row['id'];
            $serviceMessage->published = intval($row['type']) !== 1;
            $serviceMessage->createdBy = intval($row['author']);
            $serviceMessage->order = intval($row['order']);
            $serviceMessage->dateCreated = $row['dt'];
            $serviceMessage->title = $row['title'];
            $serviceMessage->message = $row['message'];
            $serviceMessage->style = ServiceMessageStyle::getStyleById($row['style']);
            $serviceMessage->icon = $row['icon'];
            $serviceMessage->language = $row['mfh_language'];
            $serviceMessage->locations = array();

            $locationSql = "SELECT `location` FROM `" . hesk_dbEscape($heskSettings['db_pfix']) . "mfh_service_message_to_location`
                WHERE `service_message_id` = " . intval($serviceMessage->id);

            if (!$searchFilter->includeStaffServiceMessages) {
                $locationSql .= " AND `location` LIKE 'CUSTOMER%'";
            }

            $locationsRs = hesk_dbQuery($locationSql);
            while ($innerRow = hesk_dbFetchAssoc($locationsRs)) {
                $serviceMessage->locations[] = $innerRow['location'];
            }

            $serviceMessages[] = $serviceMessage;
        }

        $this->close();

        return $serviceMessages;
    }

    function updateServiceMessage($serviceMessage, $heskSettings) {
        $this->init();

        $style = ServiceMessageStyle::getIdForStyle($serviceMessage->style);
        $type = $serviceMessage->published ? 0 : 1;

        hesk_dbQuery("UPDATE `" . hesk_dbEscape($heskSettings['db_pfix']) . "service_messages`
            SET `title` = '" . hesk_dbEscape($serviceMessage->title) . "', 
                `message` = '" . hesk_dbEscape($serviceMessage->message) . "', 
                `style` = '" . intval($style) . "', 
                `type` = '{$type}',
                `icon` = '" . hesk_dbEscape($serviceMessage->icon) . "',
                `order` = " . intval($serviceMessage->order) . ",
                `mfh_language` = '" . hesk_dbEscape($serviceMessage->language) . "'
            WHERE `id` = " . intval($serviceMessage->id));

        hesk_dbQuery("DELETE FROM `" . hesk_dbEscape($heskSettings['db_pfix']) . "mfh_service_message_to_location`
            WHERE `service_message_id` = " . intval($serviceMessage->id));
        foreach ($serviceMessage->locations as $location) {
            hesk_dbQuery("INSERT INTO `" . hesk_dbEscape($heskSettings['db_pfix']) . "mfh_service_message_to_location` 
                (`service_message_id`, `location`) VALUES (" . intval($serviceMessage->id) . ", '" . hesk_dbEscape($location) . "')");
        }

        $otherFieldsRs = hesk_dbQuery("SELECT `dt`, `author`, `order` FROM `" . hesk_dbEscape($heskSettings['db_pfix']) . "service_messages`
            WHERE `id` = " . intval($serviceMessage->id));
        $otherFields = hesk_dbFetchAssoc($otherFieldsRs);

        $serviceMessage->createdBy = intval($otherFields['author']);
        $serviceMessage->dateCreated = $otherFields['dt'];

        $this->close();

        return $serviceMessage;
    }

    function deleteServiceMessage($id, $heskSettings) {
        $this->init();

        hesk_dbQuery("DELETE FROM `" . hesk_dbEscape($heskSettings['db_pfix']) . "mfh_service_message_to_location`
            WHERE `service_message_id` = " . intval($id));

        hesk_dbQuery("DELETE FROM `" . hesk_dbEscape($heskSettings['db_pfix']) . "service_messages`
            WHERE `id` = " . intval($id));

        $this->close();
    }

    function resortAllServiceMessages($heskSettings) {
        $this->init();

        $rs = hesk_dbQuery("SELECT `id` FROM `" . hesk_dbEscape($heskSettings['db_pfix']) . "service_messages`
            ORDER BY `order` ASC");

        $sortValue = 10;
        while ($row = hesk_dbFetchAssoc($rs)) {
            hesk_dbQuery("UPDATE `" . hesk_dbEscape($heskSettings['db_pfix']) . "service_messages`
                SET `order` = " . intval($sortValue) . "
                WHERE `id` = " . intval($row['id']));

            $sortValue += 10;
        }

        $this->close();
    }
}