<?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);
        $sth->execute([$asset_name, $asset_info, $asset_hostname, 
                       $assetclass_id, $asset_intf, $asset_type,
                       $id]);
        $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=?");
        $sth->execute([$id]);
        $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 asset_letter
	FROM asset
	ORDER BY asset_letter";
$sth = $dbh->query($sql);

$alphabet = $sth->fetchAll();
$smarty->assign("alphabet", $alphabet);

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

// assets for current letter
if (isset($_GET['asset_letter'])) {
    $asset_letter = sanitize($_GET['asset_letter']);
} else {
   $asset_letter = $alphabet[0]['asset_letter'];
}
		
$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)
	WHERE SUBSTRING(a.asset_name,1,1)=?
	ORDER BY a.asset_name";
$sth = $dbh->prepare($sql);
$sth->execute([$asset_letter]);
$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, 
            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

// $sql = "SELECT extlink_id, extlink_type, extlink_refid, extlink_uid FROM extline WHERE extlink_asset_id=?";

$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');
?>