<?php

namespace api\v2\dashboards_v2;
use api\v2\Base;
use Exception;

use function api\v2\import_common;
import_common();
require_once(dirname(__FILE__) . '/../../../../../html/includes/utils-smart-dashboards.inc.php');

/**
 * Manages dashboards including retrieval, creation, deletion, and updates.
 */
class dashlets extends Base {

    /**
     * Auth function for get request method on api/v2/account/dashboards 
     * All necessary auth is done in check_authentication so this just returns true.
     */
    public function authorized_for_get() {
        return true;
    }

    /**
     * Retrieves a dashboard by ID, or all dashboards if no ID is specified.
     * @return array The dashboard data or an error message if not found.
     */
    public function get() {
        global $db_tables;

        $dashboard_id = escape_sql_param(grab_request_var("dashboard_id", ""), DB_NAGIOSXI);
        $user_id      = escape_sql_param($_SESSION['user_id'], DB_NAGIOSXI);
        $global_dashboard_access = get_user_meta(0, 'global_dashboard_access', 1);
        
        if (is_admin()) {
            $dashsql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . " WHERE dashboard_id='" . $dashboard_id . "'";
        }
         else if ($global_dashboard_access == 0) {
            $dashsql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . " WHERE dashboard_id='" . $dashboard_id . "' AND user_id= '" . $user_id . "' AND is_global= 0";
        } else {
            $dashsql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . " WHERE dashboard_id='" . $dashboard_id . "' AND (user_id= '" . $user_id . "' OR is_global= 1)";
        }
        $dashboard = exec_sql_query(DB_NAGIOSXI, $dashsql);
        if ($dashboard->RecordCount() == 0) {
            return [];
        }

        $board_user_id = $dashboard -> fields["user_id"];
        $board_is_global = $dashboard -> fields["is_global"];
        $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashlets"] . " WHERE dashboard_id='" . $dashboard_id . "' ORDER BY id ASC";
        if (is_admin() || $board_user_id == $user_id || ($global_dashboard_access >= 1 && $board_is_global)) {
            $dashlets = exec_sql_query(DB_NAGIOSXI, $sql);
        }
        $response = $dashlets->GetRows();
        
        return $response;
    }

    /**
     * Auth function for post request method on api/v2/account/dashboards 
     * All necessary auth is done in check_authentication so this just returns true.
     */
    public function authorized_for_post() {
        return true;
    }

    /**
     * Adds a new dashlet with provided parameters.
     * @return array Confirmation message of dashboard creation.
     */
    public function post() {
        global $db_tables;
        check_nagios_session_protector();

        $title = grab_request_var("title", "");
        if (empty($title)) {
            throw new Exception(_("No title specified!"), 500);
        }
        $dashlet = array();
        $dashlet["name"] = grab_request_var("name", "");
        $dashlet["dashboard_id"] = grab_request_var("dashboard_id", "");
        $dashlet["options"] = grab_request_var("options", "{}");
        if (gettype($dashlet["options"]) != "string") {
             $dashlet["options"] = json_encode($dashlet["options"]);
        }
        $dashlet["height"] = intval(grab_request_var("height", 10));
        $dashlet["width"] = intval(grab_request_var("width", 10));
        $dashlet["x"] = intval(grab_request_var("x", 0));
        $dashlet["y"] = intval(grab_request_var("y", 0));
        $dashlet["dashlet_id"] = random_string(6);
        $dashlet["title"] = $title;
        return add_smart_dashlet_to_smart_dashboard($dashlet);
    }

    /**
     * Auth function for put request method on api/v2/account/dashboards
     * All necessary auth is done in check_authentication so this just returns true.
     */
    public function authorized_for_put() {
        return true;
    }

    /**
     * Updates an existing dashlet with provided parameters.
     * @return array Confirmation message of dashlet update.
     */
    public function put() {
        global $db_tables;
        check_nagios_session_protector();

        $dashlet_id = grab_request_var("dashlet_id", "");
        if (empty($dashlet_id)) {
            throw new Exception(_("No dashlet ID specified!"), 500);
        }

        $title = escape_sql_param(grab_request_var("title", ""), DB_NAGIOSXI);
        $options = escape_sql_param(grab_request_var("options", "{}"), DB_NAGIOSXI);
        $dashlet_id = escape_sql_param($dashlet_id, DB_NAGIOSXI);

         $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashlets"] . "
            WHERE dashlet_id = '" . $dashlet_id . "';";
        $dashboard_id = exec_sql_query(DB_NAGIOSXI, $sql) -> fields["dashboard_id"];
        $user_id = $_SESSION['user_id'];
        $global_dashboard_access = get_user_meta(0, 'global_dashboard_access', 1);
        $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . "
            WHERE dashboard_id = '" . $dashboard_id . "';";
        $dashboard = exec_sql_query(DB_NAGIOSXI, $sql);
        $board_user_id = $dashboard -> fields["user_id"];
        $board_is_global = $dashboard -> fields["is_global"];

        $sql = "UPDATE " . $db_tables[DB_NAGIOSXI]["dashlets"] . " SET
            title = '" . $title . "',
            options = '" . $options . "'
            WHERE dashlet_id = '" . $dashlet_id . "'";

        if (is_admin() || $board_user_id == $user_id || ($global_dashboard_access >= 2 && $board_is_global)) {
            $response = exec_sql_query(DB_NAGIOSXI, $sql);
        }
        if (!$response) {
            throw new Exception(_("Could not edit dashlet."), 500);
        }

        return ["message" => _("Successfully updated dashlet")];
    }

    /**
     * Auth function for delete request method on api/v2/account/dashboards 
     * All necessary auth is done in check_authentication so this just returns true.
     */
    public function authorized_for_delete() {
        return true;
    }

    /**
     * Deletes a specified dashboard by its ID.
     * @return array Confirmation or error message based on the operation result.
     */

    public function delete() {
        check_nagios_session_protector();
        global $db_tables;

        $dashlet_id = escape_sql_param(grab_request_var("id", -1), DB_NAGIOSXI);
       
        $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashlets"] . "
            WHERE dashlet_id = '" . $dashlet_id . "';";
        $dashboard_id = exec_sql_query(DB_NAGIOSXI, $sql) -> fields["dashboard_id"];
        $user_id = $_SESSION['user_id'];
        $global_dashboard_access = get_user_meta(0, 'global_dashboard_access', 1);
        $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . "
            WHERE dashboard_id = '" . $dashboard_id . "';";
        $dashboard = exec_sql_query(DB_NAGIOSXI, $sql);
        $board_user_id = $dashboard -> fields["user_id"];
        $board_is_global = $dashboard -> fields["is_global"];

        $sql = "DELETE FROM " . $db_tables[DB_NAGIOSXI]["dashlets"] . " WHERE dashlet_id='" . $dashlet_id . "'";
        
        if (is_admin() || $board_user_id == $user_id || ($global_dashboard_access >= 2 && $board_is_global)) {
            $response = exec_sql_query(DB_NAGIOSXI, $sql);
        }
        if (!$response) {
            throw new Exception(_("Could not delete dashlet."), 500);
        }

        return ["message" => _("Successfully deleted dashlet")];
    }
}