<?php

class HelperRollerStorage
{
    public $db;

    public $table_element = 'inventory';

    public function __construct(DoliDB $db)
    {
        $this->db = $db;
    }

    function getEntities()
    {
        $entitiesArray = [];
        $sql = "SELECT rowid, label FROM " . MAIN_DB_PREFIX . "entity";
        $data = $this->db->query($sql);
        $dataArray = pg_fetch_all($data);
        if (empty($dataArray)) {
            dol_syslog("No data found.", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
            return $entitiesArray;
        }
        foreach ($dataArray as $row) {
            $entitiesArray[$row['rowid']] = $row['label'];
        }
        return $entitiesArray;
    }

    function getWarehouses()
    {
        $warehousesObj = [];
        $warehouses = new Entrepot($this->db);
        $sql = "SELECT rowid, ref FROM " . $this->db->prefix() . $warehouses->table_element . " ORDER BY rowid ASC";
        $myWarehousesObj = $this->db->query($sql);
        while ($warehouse = pg_fetch_assoc($myWarehousesObj)) {
            $warehousesObj[] = $warehouse;
        }
        return $warehousesObj;
    }
    function getWarehouseData($inventory_id)
    {
        $warehouses = new Entrepot($this->db);
        $sql = "SELECT rowid, ref, lieu, address, zip, town FROM " . $this->db->prefix() . $warehouses->table_element . " WHERE rowid = " . $inventory_id;
        $myWarehousesObj = $this->db->query($sql);
        while ($warehouse = pg_fetch_assoc($myWarehousesObj)) {
            return $warehouse;
        }
    }

    function getWarehouseStatusAndInventoryData($inventory_id)
    {
        $data = [];
        $sql = "select s.status_id, s.ref, e.ref AS warehouse, count(i.rowid) as numberofstatuses 
	FROM " . MAIN_DB_PREFIX . "inventory AS i
	INNER JOIN " . MAIN_DB_PREFIX . "entrepot AS e ON e.rowid = i.fk_warehouse
	INNER JOIN " . MAIN_DB_PREFIX . "rollerstorage_statuses as s ON i.status = s.status_id
	WHERE i.fk_warehouse = {$inventory_id}
	group by e.rowid, i.status, s.ref, s.status_id
	ORDER BY e.ref";
        $res = $this->db->query($sql);
        while ($result = pg_fetch_assoc($res)) {
            $data[] = $result;
        }
        return $data;
    }

    function getLibStatus($object)
    {
        global $stasusesObj;
        global $db;
        global $langs;
        $allapotok = $stasusesObj->getStatusIds($db);
        return '<span class="badge  badge-status' . $object->status . ' badge-status" title="' . $langs->trans($allapotok[$object->status]) . '">' . $langs->trans($allapotok[$object->status]) . '</span>';
    }

    function getAssignabelDevices($inventory_id)
    {
        $devices = [];
        $sql = "SELECT i.rowid, i.ref FROM " . MAIN_DB_PREFIX . "inventory AS i 
        INNER JOIN " . MAIN_DB_PREFIX . "inventory_extrafields as ie ON ie.fk_object = i.rowid
        WHERE fk_warehouse = {$inventory_id} AND ie.device_type in ('1', '2') ORDER BY i.ref";
        $res = $this->db->query($sql);
        $result = pg_fetch_all($res);
        if (empty($result)) {
            dol_syslog("No data found.", LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERR);
            return $devices;
        }
        foreach ($result as $device) {
            $devices[$device['rowid']] = $device['ref'];
        }
        return $devices;
    }

    /**
     * Output the buttons to submit a creation/edit form
     *
     * @param   string  $save_label     	Alternative label for save button
     * @param   string  $cancel_label   	Alternative label for cancel button
     * @param   array   $morebuttons    	Add additional buttons between save and cancel
     * @param   bool    $withoutdiv     	Option to remove enclosing centered div
     * @param	string	$morecss			More CSS
     * @param	string	$dol_openinpopup	If the button are shown in a context of a page shown inside a popup, we put here the string name of popup.
     * @return 	string						Html code with the buttons
     */
    public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $cancelURL = '', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
    {
        global $langs;

        $buttons = array();

        $save = array(
            'name' => 'save',
            'label_key' => $save_label,
        );

        if ($save_label == 'Create' || $save_label == 'Add') {
            $save['name'] = 'add';
        } elseif ($save_label == 'Modify') {
            $save['name'] = 'edit';
        }

        $cancel = array(
            'name' => 'cancel',
            'label_key' => 'Cancel',
        );

        !empty($save_label) ? $buttons[] = $save : '';

        if (!empty($morebuttons)) {
            $buttons[] = $morebuttons;
        }

        //!empty($cancel_label) ? $buttons[] = $cancel : '';

        $retstring = $withoutdiv ? '' : '<div class="center">';

        foreach ($buttons as $button) {
            $addclass = empty($button['addclass']) ? '' : $button['addclass'];
            $retstring .= '<input type="submit" class="button button-' . $button['name'] . ($morecss ? ' ' . $morecss : '') . ' ' . $addclass . '" name="' . $button['name'] . '" value="' . dol_escape_htmltag($langs->trans($button['label_key'])) . '">';
        }

        if ($cancel_label == "Cancel") {
            $retstring .= '<a class="button button-' . $cancel['name'] . '" href="' . dol_buildpath($cancelURL, 1) . /*'?restore_lastsearch_values=1' .*/ (!empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans($cancel['label_key']) . '</a>';
        }

        $retstring .= $withoutdiv ? '' : '</div>';

        if ($dol_openinpopup) {
            $retstring .= '<!-- buttons are shown into a $dol_openinpopup=' . $dol_openinpopup . ' context, so we enable the close of dialog on cancel -->' . "\n";
            $retstring .= '<script>';
            $retstring .= 'jQuery(".button-cancel").click(function(e) {
				e.preventDefault(); console.log(\'We click on cancel in iframe popup ' . $dol_openinpopup . '\');
				window.parent.jQuery(\'#idfordialog' . $dol_openinpopup . '\').dialog(\'close\');
				 });';
            $retstring .= '</script>';
        }

        return $retstring;
    }
}