<?php
/*****************************************************************************
IP Reg, a PHP/MySQL IPAM tool
Copyright (C) 2007-2009 Wietse Warendorff (up to v0.5)
Copyright (C) 2011-2023 Thomas Hooge

SPDX-License-Identifier: GPL-3.0-or-later
*****************************************************************************/

include("includes.php");

if (isset($_REQUEST['id'])) {
    $id = (int) $_REQUEST['id'] or $id = 0;
}

// ========== ACTIONS START ===================================================
switch ($submit = form_get_action()) {

    case NULL: break;

    case 'add':   $action = ACT_ADD; break;
    case 'view':  $action = ACT_VIEW; break;
    case 'edit':  $action = ACT_EDIT; break;
    case 'del':   $action = ACT_DELETE; break;

    case 'insert':
        $name = sanitize($_POST['asset_name']);
        $hostname = sanitize($_POST['asset_hostname']);
        $assetclass_id = sanitize($_POST['assetclass_id']);
        $info = sanitize($_POST['asset_info']);
        $intf = sanitize($_POST['asset_intf']);
        $asset_type = sanitize($_POST['asset_type']);

        $sql = "INSERT INTO asset
                    (asset_name, asset_hostname, assetclass_id, asset_info,
                     asset_intf, asset_type)
                VALUE 
                    (?, ?, ?, ?, ?, ?)";
        $sth = $dbh->prepare($sql);
        $sth->execute([$name, $hostname, $assetclass_id, $info, $intf, $asset_type]);
        $id = $dbh->lastInsertId();
        $action = ACT_VIEW;
        break;

    case 'update':
        $asset_name = sanitize($_POST['asset_name']);
        $asset_info = sanitize($_POST['asset_info']);
        $asset_intf = sanitize($_POST['asset_intf']);
        $asset_hostname = sanitize($_POST['asset_hostname']);
        $assetclass_id = sanitize($_POST['assetclass_id']);
        $asset_type = sanitize($_POST['asset_type']);

        $sql = "UPDATE asset SET
                    asset_name=?, asset_info=?, asset_hostname=?,
                    assetclass_id=?, asset_intf=?, asset_type=?
                WHERE asset_id=?";
        $sth = $dbh->prepare($sql);
        try {
            $sth->execute([$asset_name, $asset_info, $asset_hostname, 
                           $assetclass_id, $asset_intf, $asset_type,
                           $id]);
        } catch (PDOException $e) {
            $g_error->Add($e->getMessage());
        }
        // Ext. links
        if ($config_ext['zabbix']['enabled'] and isset($_POST['x_zbx_host'])) {
            $zbx_host = sanitize($_POST['x_zbx_host']);
            $sql = "SELECT extlink_id FROM extlink WHERE asset_id=? AND extlink_type='zabbix'";
            $sth = $dbh->prepare($sql);
            $sth->execute([$id]);
            if ($linkid = $sth->fetchColumn()) {
                $sql = "UPDATE extlink SET extlink_refid=? WHERE extlink_id=?";
                $sth = $dbh->prepare($sql);
                $sth->execute([$zbx_host, $linkid]);
            } else {
                $sql = "INSERT INTO extlink (asset_id, extlink_type, extlink_refid) VALUES (?, 'zabbix', ?)";
                $sth = $dbh->prepare($sql);
                $sth->execute([$id, $zbx_host]);
            }
        }

        $action = ACT_VIEW;
        break;

    case 'delete':
        $sth = $dbh->prepare("DELETE FROM asset WHERE asset_id=?");
        $sth->execute([$id]);
        $sth = $dbh->prepare("DELETE FROM node WHERE asset_id=?");
        try {
            $sth->execute([$id]);
        } catch (PDOException $e) {
            $g_error->Add($e->getMessage());
        }        $action = ACT_DEFAULT;
        break;

    default:
        $g_error->Add(submit_error($submit));
        $valid = FALSE;
}

// ========== ACTIONS END =====================================================

include("header.php");

if ($action == ACT_DEFAULT):
// ========== VARIANT: default behavior =======================================

// create letter links
$sql = "SELECT DISTINCT SUBSTRING(UPPER(asset_name),1,1) AS bst
	FROM asset
	ORDER BY bst";
$sth = $dbh->query($sql);

$alphabet = $sth->fetchAll();
$alphabet[] = ['bst' => '*'];
$smarty->assign("alphabet", $alphabet);

// total asset count
$sth = $dbh->query("SELECT COUNT(*) FROM asset");
$assetcount = $sth->fetchColumn();
$smarty->assign("assetcount", $assetcount);

// assets for current letter
if (isset($_GET['bst'])) {
    $bst = sanitize($_GET['bst']);
} else {
   $bst = $alphabet[0]['bst'];
}

$sql = "SELECT a.asset_id, IF(LENGTH(a.asset_name)>0, a.asset_name, '...') AS asset_name,
            a.asset_info, c.assetclass_id, c.assetclass_name
	FROM asset AS a LEFT OUTER JOIN assetclass AS c USING (assetclass_id)";
if ($bst != '*') {
    $sql .= " WHERE SUBSTRING(a.asset_name,1,1)=?";
    $p = array($bst);
} else {
    $p = array();
}
$sql .=	" ORDER BY a.asset_name";
$sth = $dbh->prepare($sql);
$sth->execute($p);
$smarty->assign("assets", $sth->fetchAll());

$smarty->display("asset.tpl");

elseif ($action == ACT_ADD):
// ========== VARIANT: add record =============================================

if((isset($_GET['assetclass_id'])) ? $assetclass_id = sanitize($_GET['assetclass_id']) : $assetclass_id = "");
$smarty->assign("assetclass_id", $assetclass_id);

$sql = "SELECT assetclass_id, assetclass_name
        FROM assetclass
	ORDER BY assetclass_name";
$sth = $dbh->query($sql);

$types = db_load_enum('asset','asset_type');

$smarty->assign("type_ids", $types);
$smarty->assign("type_names", $types);
$smarty->assign("type_selected", $types[0]);

$assetclass_options = array();
foreach ($sth->fetchAll(PDO::FETCH_NUM) as $rec) {
    $assetclass_options[$rec[0]] = $rec[1];
}
$smarty->assign("assetclass_options", $assetclass_options);

$smarty->display("assetadd.tpl");

elseif ($action == ACT_VIEW):
// ========== VARIANT: view single record =====================================

$sql = "SELECT a.asset_id, a.asset_name, a.asset_hostname, a.asset_info,
            a.asset_intf, a.asset_type, c.assetclass_id, c.assetclass_name
        FROM asset AS a LEFT OUTER JOIN assetclass AS c USING (assetclass_id)
        WHERE a.asset_id=?";
$sth = $dbh->prepare($sql);
$sth->execute([$id]);
$asset = $sth->fetch(PDO::FETCH_OBJ);
$smarty->assign("asset", $asset);

$sql = "SELECT node_id, node_ip, node.node_flags & 0x1 = 1 AS deleted,
            CONCAT(LEFT(node_info, 40), IF(CHAR_LENGTH(node_info)>40,'...','')) AS node_info
        FROM node
        WHERE asset_id=?
        ORDER BY INET_ATON(node_ip)";
$sth = $dbh->prepare($sql);
$sth->execute([$id]);
$smarty->assign("nodes", $sth->fetchAll(PDO::FETCH_ASSOC));

// external systems
// extlink_id
// asset_id
// Type:  enum('cdb','zabbix','topdesk', osticket
// ID: extlink_refid  int
//     extlink_uid string

if ($config_ext['zabbix']['enabled']) {
    $smarty->assign("zabbix", true);
    $sql = "SELECT extlink_refid FROM extlink WHERE extlink_type='zabbix' AND asset_id=?";
    $sth = $dbh->prepare($sql);
    $sth->execute([$id]);
    $refid = $sth->fetchColumn();
    // TODO fetch ext data here
    //$zbx = new PDO('mysql:host='.$config_ext['zabbix']['host'].';dbname='.$config_ext['zabbix']['db'].';', $config_ext['zabbix']['user'], $config_ext['zabbix']['pass']);
    //$zbx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //$zbx->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    $smarty->assign('refid', $refid);
}


$smarty->display("assetview.tpl");

elseif ($action == ACT_EDIT):
// ========== VARIANT: edit single record =====================================

$sql = "SELECT asset_id, asset_name, asset_hostname, asset_info, asset_intf,
            assetclass_id, asset_type
	FROM asset
	WHERE asset_id=?";
$sth = $dbh->prepare($sql);
$sth->execute([$id]);
$smarty->assign("asset", $sth->fetch(PDO::FETCH_OBJ));

// Type selection
$smarty->assign("type_ids", ['active', 'passive']);
$smarty->assign("type_names", ['Active', 'Passive']);

$smarty->assign("assetclass_options", db_get_options_assetclass());



$smarty->display("assetedit.tpl");

elseif ($action == ACT_DELETE):
// ========== VARIANT: delete record ==========================================

// asset to delete	
$sth = $dbh->prepare("SELECT asset_name FROM asset WHERE asset_id=?");
$sth->execute([$id]);
$smarty->assign("asset_id", $id);
$smarty->assign("asset_name", $sth->fetchColumn());

// nodes to delete
$sql = "SELECT node_id, node_ip FROM node WHERE asset_id=? ORDER BY INET_ATON(node_ip)";
$sth = $dbh->prepare($sql);
$sth->execute([$asset_id]);
$smarty->assign("nodes", $sth->fetchAll(PDO::FETCH_ASSOC));

$smarty->display("assetdel.tpl");

else:
// ========== ERROR UNKNOWN VARIANT ===========================================

echo "<p>Unknown function call: Please report to system development!</p>\n";

endif; // $action == ...
// ========== END OF VARIANTS =================================================

$smarty->display('footer.tpl');