<?php

use Luracast\Restler\RestException;

trait RollerHandligHelper
{
    public function getAllScooterDataByCode($code)
    {
        $deviceTypes = ['6' => 'Seev Citycoco', '7' => 'WIZTEM', '8' => 'MONSTERROLLER', '9' => 'NEOS'];
        $rentableStatuses = [110, 115];
        $sql = "SELECT 
            i.rowid, i.entity, i.ref, i.fk_warehouse, i.status, i.title
            , ent.ref, ent.lieu
            , ie.device_type
            FROM llx_inventory as i 
            INNER JOIN llx_entrepot AS ent ON ent.rowid = i.fk_warehouse
            INNER JOIN llx_inventory_extrafields as ie ON ie.fk_object = i.rowid
            WHERE i.title ILIKE '%{$code}%'";
        $result = $this->db->query($sql);
        if ($this->db->num_rows($result) > 0) {
            while ($row = $this->db->fetch_object($result)) {
                $row->device_type = $deviceTypes[$row->device_type];
                $row->isRentable = in_array($row->status, $rentableStatuses);
                return $row;
            }
        }
        return [];
    }

    public function getScooterRowidByCode($code)
    {
        $sql = "SELECT * FROM llx_inventory as i WHERE i.title ILIKE '%{$code}%'";
        $result = $this->db->query($sql);
        if ($this->db->num_rows($result) > 0) {
            while ($row = $this->db->fetch_object($result)) {
                return $row->rowid;
            }
        }
        return [];
    }

    public function CreateScooterRentHistoryRecord($inventory_id, $invoice_number, $timestamp = null, $ticket_id, $status = 1)
    {
        if (!is_null($timestamp)) {
            $ticket_id = $this->getTicketId($invoice_number, $timestamp);
        }
        ApiBbusLog::ScooterRentLog('RentHistoryRecord: ___START___');
        global $user;
        $rollerRentHistoryObj = new RollerRentHistory($this->db);
        $rollerRentHistoryObj->inventory_id = $inventory_id;
        $rollerRentHistoryObj->ticket_id = $ticket_id;
        $rollerRentHistoryObj->invoice_number = $invoice_number;
        $rollerRentHistoryObj->status = $status;
        return $rollerRentHistoryObj->create($user);
    }

    private function checkError($error)
    {
        if ($error > 0) {
            $this->db->rollback();
            ApiBbusLog::ScooterRentLog('ConnectFactureAndScooter Rollback...');
            throw new RestException(509);
        }
    }

    private function updateScooterBbticket($selectedTicket)
    {
        $ticketChecker = new TicketChecker();
        $validated_at = date('Y-m-d H:i:s');
        $duration = $this->getDurationByProductId($selectedTicket->ticket_id);
        $expire_at = $this->getExpireAt($selectedTicket, $duration, $validated_at);
        $usage = $this->setUsage($selectedTicket);
        $sql = "UPDATE " . $this->db->prefix() . "bbus_bbticket SET validated_at = '" . $validated_at . "', expire_at = '" . $expire_at . "'";
        $sql .= ", usage = '" . $usage . "'";
        $sql .= " WHERE rowid = " . $selectedTicket->rowid;
        return $this->db->query($sql);
    }

    private function getDurationByProductId($ticket_id)
    {
        $sql = "SELECT p.duration as duration  FROM " . $this->db->prefix() . "product AS p WHERE rowid = " . $ticket_id;
        $result = $this->db->query($sql);
        while ($row = $this->db->fetch_object($result)) {
            return $row->duration;
        }
    }

    private function getExpireAt($obj, $duration, $validated_at)
    {
        return date('Y-m-d H:i:s', strtotime($validated_at . ' +' . substr($duration, 0, -1) . ' ' . $this->getIntervalTimeByDuration()));
    }

    private function setUsage($selectedTicket)
    {
        $usage = (int)$selectedTicket->usage + 1;
        return $usage;
    }

    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';
        }
    }

    public function checkRentHistory($rowid, $invoice_number)
    {
        $sql = "SELECT * FROM llx_rollerstorage_rollerrenthistory WHERE inventory_id = {$rowid} AND invoice_number = '{$invoice_number}' AND status = 1";
        return $this->db->query($sql);
    }

    public function getInvoiceNumberByInvetoryId($inventory_id)
    {
        $invoice_number = '';
        $sql = "SELECT * FROM llx_rollerstorage_rollerrenthistory WHERE inventory_id = {$inventory_id} AND status = 1 ORDER BY date_creation DESC LIMIT 1";
        $result = $this->db->query($sql);
        if ($this->db->num_rows($result) > 0) {
            while ($row = $this->db->fetch_object($result)) {
                $invoice_number = $row->invoice_number;
            }
        }
        return $invoice_number;
    }

    public function getRollerrenthistoryDataByInvetoryId($inventory_id)
    {
        $rollerrenthistoryData = '';
        $sql = "SELECT * FROM llx_rollerstorage_rollerrenthistory WHERE inventory_id = {$inventory_id} AND status = 1 ORDER BY date_creation DESC LIMIT 1";
        $result = $this->db->query($sql);
        if ($this->db->num_rows($result) > 0) {
            while ($row = $this->db->fetch_object($result)) {
                $rollerrenthistoryData = $row;
            }
        }
        return $rollerrenthistoryData;
    }

    public function getTicketId($invoice_number, $timestamp)
    {
        $ticketData = $this->getBbticketDataByInvoiceNumber_and_Timestamp($invoice_number, $timestamp);
        return $ticketData->rowid;
    }

    public function getBbticketDataByInvoiceNumber_and_Timestamp($invoice_number, $timestamp)
    {
        global $conf;
        $bbTicketData = [];
        $sql = "SELECT bbt.* FROM llx_bbus_bbticketinvoiceprinting as bbtip 
            INNER JOIN llx_product_extrafields as pre ON pre.fk_object = bbtip.product_id
            INNER JOIN llx_bbus_bbticket as bbt ON bbt.rowid = bbtip.ticket_id
            INNER JOIN llx_bbus_basicservices as bbs ON bbs.rowid = CAST(pre.basic_service AS integer)
            WHERE bbtip.invoice_number = '{$invoice_number}'
            AND bbtip.printing_date_timestamp = '{$timestamp}'
			AND bbs.server_host = '{$conf->global->LOCAL_SERVER_HOST}'
            ORDER BY bbtip.rowid DESC limit 1";
        $result = $this->db->query($sql);
        if ($this->db->num_rows($result) > 0) {
            while ($row = $this->db->fetch_object($result)) {
                $bbTicketData = $row;
            }
        }
        return $bbTicketData;
    }

    public function getTicketIdByInvoiceNumberFromRollerRentHistory($invoice_number, $scooter_code)
    {
        $scooterData = $this->getScooterRowidByCode($scooter_code);
        $sql = "SELECT ticket_id FROM public.llx_rollerstorage_rollerrenthistory 
            WHERE invoice_number = '{$invoice_number}' AND inventory_id = {$scooterData}
            ORDER BY rowid DESC LIMIT 1";
        $result = $this->db->query($sql);
        if ($this->db->num_rows($result) > 0) {
            while ($row = $this->db->fetch_object($result)) {
                return $row->ticket_id;
            }
        }
        return null;
    }

    public function checkExpireDate($ticket_id)
    {
        $array = [];
        $now = date("Y-m-d H:i:s", dol_now());
        if ($ticket_id !== '') {
            $sql = "SELECT expire_at FROM llx_bbus_bbticket WHERE rowid = {$ticket_id}";
            $result = $this->db->query($sql);
            if ($this->db->num_rows($result) > 0) {
                while ($row = $this->db->fetch_object($result)) {
                    if (strtotime($row->expire_at) < strtotime($now)) {
                        $array['isExpired'] = true;
                        $array['date'] = $row->expire_at;
                        return $array;
                    } else {
                        $array['isExpired'] = false;
                        return $array;
                    }
                }
            }
        } else {
            throw new RestException(508);
        }
        $array['isExpired'] = false;
        return $array;
    }

    public function getTicketIdByInvoiceNumber($invoice_number, $timestamp)
    {
        $bbticketObj = $this->getBbticketDataByInvoiceNumber_and_Timestamp($invoice_number, $timestamp);
        return $bbticketObj->ticket_id;
    }

    public function isRented($QRCodeData, $inventory_id)
    {
        $rollerrenthistory = false;
        $sql = "SELECT status FROM public.llx_rollerstorage_rollerrenthistory 
            WHERE invoice_number = '{$QRCodeData[0]}' AND inventory_id = {$inventory_id} AND status = 1
            ORDER BY rowid DESC LIMIT 1";
        $result = $this->db->query($sql);
        if ($this->db->num_rows($result) > 0) {
            while ($row = $this->db->fetch_object($result)) {
                $rollerrenthistory = $row->status == 1;
            }
        }
        return $rollerrenthistory;
    }

    public function createHistoryRecord($obj, $fromStatus){
		global $user;
		//print_r($obj);exit;

		$statuses2 = new Statuses($this->db);
        $status_id_from_statuses = $statuses2->getRowIdFromStatusId($this->db, $fromStatus);
    	$status_id_to_statuses = $statuses2->getRowIdFromStatusId($this->db, $obj->status);
		
		$rollerhistory = new RollerHistory($this->db);
		$rollerhistory->fk_inventory = $obj->id;
		$rollerhistory->warehouse_from = $obj->fk_warehouse;
		$rollerhistory->warehouse_to = $obj->fk_warehouse;
		$rollerhistory->status_from = $status_id_from_statuses;
		$rollerhistory->status_to = $status_id_to_statuses;
		$rollerhistory->status = 0;
		if ($rollerhistory->create($user) == -1) {
			dol_syslog("Nem sikerult a rollerstorage_history mentese.");
		}
	}
}
