<?php

namespace api\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 dashboards_v2 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;

        $id = grab_request_var('id', '');
        $all = grab_request_var('all', false);
        $response = [];
        $global_dashboard_access = get_user_meta(0, 'global_dashboard_access', 1);
        $user_id = $_SESSION['user_id'];
        if ($global_dashboard_access == 0 && !is_admin()) {
            if($id == '') {
                $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . " WHERE user_id= '" . $user_id . "' AND is_global= 0 ORDER BY id ASC";
                $dashboards = exec_sql_query(DB_NAGIOSXI, $sql);
                $rows = $dashboards->GetRows();
            } else {
                $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . " WHERE dashboard_id='" . $id . "' AND user_id= '" . $user_id . "' AND is_global= 0 ORDER BY id ASC";
                $dashboards = exec_sql_query(DB_NAGIOSXI, $sql);
                $rows = $dashboards->GetRows();
            }
        } else {
            if($id == '' && is_admin() && $all) {
                $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . " ORDER BY id ASC";
                $dashboards = exec_sql_query(DB_NAGIOSXI, $sql);
                $rows = $dashboards->GetRows();
            } else if($id == '') {
                $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . " WHERE user_id= '" . $user_id . "' OR is_global= 1 ORDER BY id ASC";
                $dashboards = exec_sql_query(DB_NAGIOSXI, $sql);
                $rows = $dashboards->GetRows();
            } else {
                $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["dashboards"] . " WHERE dashboard_id='" . $id . "' AND (user_id= '" . $user_id . "' OR is_global= 1) ORDER BY id ASC";
                $dashboards = exec_sql_query(DB_NAGIOSXI, $sql);
                $rows = $dashboards->GetRows();
            }
        }
        foreach ($rows as &$row) {
            if (isset($row['is_global'])) {
                $row['is_global'] = (bool)$row['is_global'];
            }
        }
        $response = $rows;
        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 dashboard with provided parameters.
     * @return array Confirmation message of dashboard creation.
     */
    public function post() {
        check_nagios_session_protector();
        return create_smart_dashboard(grab_request_var("name", ""), grab_request_var("is_global", 0));
    }

    /**
     * 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_put() {
        return true;
    }

    /**
     * Edits a dashboard with the given parameters.
     * @return array Confirmation of successful dashboard edit.
     */
    public function put() {
        global $db_tables;
        check_nagios_session_protector();
        $dashboard_id = grab_request_var("dashboard_id", "");
        $dashlets = grab_request_var("dashlets", []);
        $name = grab_request_var("name", '');
        $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"];
        if (grab_request_var("toggle_global", '') != '' && ($global_dashboard_access >= 3 || is_admin())) {
            $toggle_global = true;

        } else {
            $toggle_global = false;
        }
        $updated = 'SET ';
        if (!empty($name)) {
            $updated .= "name = '" . escape_sql_param($name, DB_NAGIOSXI) . "'";
        }
        if (!empty($name) && $toggle_global) {
            $updated .= ", ";
        }
        if ($toggle_global) {
            $updated .= "is_global = " . ($board_is_global == 1 ? 0 : 1);
        }
        error_log($updated);
        // Handle name update
        if ((!empty($name) || $toggle_global == true) && !empty($dashboard_id) && (is_admin() || $board_user_id == $user_id || ($global_dashboard_access == 3 && $board_is_global))) {
            $sql = "UPDATE " . $db_tables[DB_NAGIOSXI]["dashboards"] . " " . $updated . " WHERE dashboard_id = '" . escape_sql_param($dashboard_id, DB_NAGIOSXI) . "'";
            $res = exec_sql_query(DB_NAGIOSXI, $sql);
            if (!$res) {
                throw new \Exception(_("Failed to edit dashboard."), 500);
            }
        }

        // Handle dashlet layout update (existing logic)
        if (!empty($dashlets) && (is_admin() || $board_user_id == $user_id || ($global_dashboard_access == 3 && $board_is_global))) {
            foreach ($dashlets as $dashlet) {
                $dashlet_id = $dashlet['dashlet_id'];
                $height = $dashlet['height'];
                $width = $dashlet['width'];
                $x = $dashlet['x'];
                $y = $dashlet['y'];
                $sql = "UPDATE " . $db_tables[DB_NAGIOSXI]["dashlets"] . " SET
                        height = " . escape_sql_param($height, DB_NAGIOSXI) . ",
                        width = " . escape_sql_param($width, DB_NAGIOSXI) . ",
                        x = " . escape_sql_param($x, DB_NAGIOSXI) . ",
                        y = " . escape_sql_param($y, DB_NAGIOSXI) . "
                        WHERE dashlet_id = '" . escape_sql_param($dashlet_id, DB_NAGIOSXI) . "'";
                exec_sql_query(DB_NAGIOSXI, $sql);
            }
        }

        return ["message" => _("Successfully edited dashboard")];
    }

    /**
     * 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;

        $user_id = $_SESSION['user_id'];
        $dashboard_id = grab_request_var("id", -1);
        $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]["dashboards"] . " WHERE dashboard_id='" . $dashboard_id . "'";

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

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