<?php

//////////////////////////////////////////////////////////////
//===========================================================
// list_baremetal_theme.php
//===========================================================
// SOFTACULOUS VIRTUALIZOR
// Version : 1.0
// Inspired by the DESIRE to be the BEST OF ALL
// ----------------------------------------------------------
// Started by: Alons
// Date:       8th Mar 2010
// Time:       23:00 hrs
// Site:       https://www.virtualizor.com/ (SOFTACULOUS VIRTUALIZOR)
// ----------------------------------------------------------
// Please Read the Terms of use at https://www.virtualizor.com
// ----------------------------------------------------------
//===========================================================
// (c)Softaculous Ltd.
//===========================================================
//////////////////////////////////////////////////////////////

if(!defined('VIRTUALIZOR')){

	die('Hacking Attempt');

}

function getSortHeader($header_name, $column ,$size = 80){

    global $theme, $globals;
    
	$str = '<div class="d-inline-flex align-items-center" style="width:'.$size.'px;">
		<div class="mr-2">
			<span class="" >'.$header_name.'</span>
		</div>
		<span class="sorter">
			<a class="text-always-white" href="'.$globals['index'].'act=list_datacenters&sortcolumn='.$column.'&sortby=asc"><i class="fas fa-sort-up"></i></a><br>
			<a class="text-always-white" href="'.$globals['index'].'act=list_datacenters&sortcolumn='.$column.'&sortby=desc"><i class="fas fa-sort-down"></i></a>
		</span>
	</div>';
	return $str;
}

function list_datacenters_theme(){

global $globals, $l, $error, $done, $list_datacenters;


    softheader($l['<title>']);

    $buttons = array(
        0 => array(
            'name' => __('Add Datacenter'),
            'act'  => 'add_datacenter'
        )
    );

    $GLOBALS['breadcrumbs'] = array( 'dashboard', 'lms_list_datacenters');

    echo page_header(__('List Datacenters'), 'fas fa-server', '', 1, 0, $buttons);

    error_handle($error);

    echo '<script language="javascript" type="text/javascript"><!-- // --><![CDATA[

    function action_chosen(action, dcid , ele){

        dcid = dcid || 0;
        action = action || "";
        
        if(action == ""){
            if($(ele).parent().prev().find("select").val() == 0){
                    showalert("'.__J('No action selected !').'","1");
                    return false;
            }else{
                action = $(ele).parent().prev().find("select").val();
            }
        }

        // List of ids
        var dc_list = new Array();

        if(dcid < 1){
            $(".ios:checked").each(function(){
                dc_list.push($(this).val());
            });
        }else{	
            dc_list.push(dcid);
        }
        
        if(dc_list.length < 1){
            showalert("'.__J('Nothing selected !').'","1");
            return false;
        }
        // To delete Datacenter
        if(action == "delete"){
            showalert("'.__J('Are you sure want to Delete the Datacenter ?').'" ,"3" ,function(confirm){
                if(confirm == false){
                    return false;
                }else{
                    var finalData = new Object();
                    finalData["delete"] = dc_list.join(",");
                    exec(finalData);
                }
            });
        }else{
            showalert("'.__J('No action selected !').'","1");
            return false;
        }
        
        return false;
    };

    function exec(finalData){
        $("#progress_bar").show();
        $.ajax({
            type: "POST",
            url: "'.$globals['index'].'act=list_datacenters&api=json",
            data : finalData,
            dataType : "json",
            success: function(data){

                console.log(data);

                let status = data.status;

                if( status == "success") {

                    let dc_list = data.data;
                    let message = data.message;
                    let i = 0;
                    
                    for(datacenter in dc_list){
                        i++;
                        message = message +"</br><b>"+i+") "+dc_list[datacenter]+"</b>";
                    }

                    console.log(message);

                    // let message =  `${data.message} </br> <b>${dc}</b>`;

                    setTimeout(function(){showalert(message, 0);
                    $("#alert-modal").on("hidden.bs.modal", function (e) {
                        location.reload(true);
                    });} ,200);

                }else{
                    let error_message = data.message;
                    var errstr = "'.__J('The following errors were found</br>').'";
                    for(x in error_message){
                        errstr = errstr+"\n"+error_message[x];
                    }
                    setTimeout(function(){showalert(data.message, 1);} ,200);
                }

                $("#progress_bar").hide();
                if("done" in data){
                    setTimeout(function(){showalert("'.__J('The action was completed sucessfully').'");
                    $("#alert-modal").on("hidden.bs.modal", function (e) {
                        location.reload(true);
                    });} ,200);
                }
                if("error" in data){
                    var errstr = "'.__J('The following errors were found').'";
                    for(x in data["error"]){
                        errstr = errstr+"\n"+data["error"][x];
                    }
                    setTimeout(function(){showalert(errstr,"1");} ,200);
                }
                if("fatal_error_text" in data){
                    setTimeout(function(){showalert(data["fatal_error_text"] ,"1");} ,200);
                }
            },
            error: function(data) {
                $("#progress_bar").hide();
                //alert(data.description);
                return false;
            }
        });
    };
    
    // show the confirm message before delete any datacenter
    function show_confirm(dcid, ){

        if(dcid > 0){
            dc_list[0] = dcid;
            multi_action = cur_action;
            selected_list += "\n'.__J('Data Center Name ').'"+dcid+" ["+$("#tr_hostname"+dcid).attr("value")+"]"+" '.__J('of')." ".__J('Server').' "+$("#server_"+dcid).text();
            
        // Multi select
        }else{
        
            multi_action = $(ele).parent().prev().find("select").val();
            if(multi_action == "0"){
                showalert("'.__J('No action selected !').'","1");
                return false;
            }
        }

        confirm_message = "'.__J('Are you sure you wish to ').'" + ((!empty(confirm_net))? confirm_net : ucfirst(multi_action))+"'.__J(' the following VPS(s) ? ').'<br>"+selected_list+((multi_action == "lock" ? "<br>'.__J('Reason').': <input type=\"text\" class=\"form-control\" id=\"lock_reason\" name=\"reason\">" : "") || (multi_action == "suspend" ? "<br>'.__J('Reason').': <input type=\"text\" class=\"form-control\" id=\"suspend_reason\" name=\"suspend_reason\">" : ""));
	
        if(multi_action == "delete"){
            vps_randstr = generateString(5);
            confirm_message += "<br><label class=\"my-2\">'.__J('Type').' <b id=\"vps_randstr\" class=\"text-monospace\" style=\"letter-spacing: 3px;\">DELETE</b> '.__J('to delete the vps!').'</label> <br> <input type=\"text\" class=\"form-control text-monospace\" style=\"letter-spacing: 3px;border-radius: 4px;\" id=\"delete_check\" autocomplete=\"off\">";
        }
    }

    <!--
    function dc_radial_bar_chart(radial_bar_id, data = ""){
        
        var options = {
            series: [data["data"][0], data["data"][1], data["data"][2], data["data"][3]],
            // series: [76, 67, 61, 90],
            
            chart: {
                height: 250,
                type: "radialBar",
            },

            stroke: {
                show: false,
            },

            legend: {
                show: false,
                position: "right",
            },

            plotOptions: {
                radialBar: {
                    offsetY: 0,
                    startAngle: 0,
                    endAngle: 270,
                    hollow: {
                        margin: 5,
                        size: "30%",
                        background: "transparent",
                        image: undefined,
                    },
                    dataLabels: {
                        name: {
                            show: false,
                        },
                        value: {
                            show: false,
                        }
                    },
                    barLabels: {
                        enabled: true,
                        useSeriesColors: true,
                        offsetX: -8,
                        fontSize: "16px",
                        formatter: function (seriesName, opts) {
                            return seriesName + ":  " + opts.w.globals.series[opts.seriesIndex]
                        },
                    },
                }
            },

            colors: ["#1ab7ea", "#0084ff", "#39539E", "#0077B5"],
            
            labels: [data["label"][0], data["label"][1], data["label"][2], data["label"][3]],
            responsive: [{
                breakpoint: 480,
                options: {
                    legend: {
                        show: false
                    }
                }
            }]
        };

        var chart = new ApexCharts(document.querySelector(radial_bar_id), options);
        chart.render();
    }

    function datacenters_details(dcid = "", element, rows="", columns="", racks="", units ="") {
        // radial_chart();
        let tr = $(element).closest("tr");
        let next_row = tr.next();

        // If already open — close just this one
        if (next_row.hasClass("dc-details-row")) {
            next_row.find(".dc-details").slideUp(250, function() {
                next_row.remove();
            });
            return;
        }

        let radial_bar_chart_id = "radial_bar_chart_"+dcid;

        // Insert new full-width row
        const detailsHtml = `
            <tr id="ds_details_${dcid}" class="dc-details-row">
                <td colspan="100%">
                    <div class="dc-details d-flex align-items-center">
                        <div id="${radial_bar_chart_id}"></div>
                        <div class="">
                            <div>Rows = ${rows}</div>
                            <div>Columns = ${columns}</div>
                            <div>Racks = ${racks}</div>
                            <div>Units = ${units}</div>
                        </div>
                    </div>
                </td>
            </tr>`;

        tr.after(detailsHtml);

        let dc_details = {
            data: [rows, columns, racks, units],
            label : ["'.__J('Rows').'", "'.__J('Columns').'", "'.__J('Racks').'", "'.__J('Units').'"]
        }

        dc_radial_bar_chart("#"+radial_bar_chart_id, dc_details);

        // Animate the slide down
        tr.next().find(".dc-details").slideDown(300);
    }
    -->

    // ]]></script>
    <div class="card p-2 mx-3">
        <div id="showsearch" class="mb-3" style="display:'.(optREQ('search') || (!empty($list_baremetal) && !empty($globals['showsearch'])) ? "" : "none").';">
            <form accept-charset="'.$globals['charset'].'" name="list_baremetal" method="GET" action="" class="form-horizontal">
                <input type="hidden" name="act" value="list_baremetal">
                <div class="form-group_head">
                    <div class="row mx-auto w-100">
                        <div class="col-sm-4">
                            <label for="input text">'.__('search_id').'</label>
                            <input type="text" class="form-control" name="uid" id="uid" size="15" value="'.REQval('uid','').'" />
                        </div>
                        <div class="col-sm-4">
                            <label for="input text" class="control-label">'.__('search_email').'</label>&nbsp;<i class="fas text-primary fa-info-circle" tooltip="'.__('wiki_help').'"></i>
                            <input type="text" class="form-control" name="email" id="email" size="30" value="'.REQval('email', '').'" />
                        </div>
                    </div>
                    <div class="row mx-auto w-100 my-2">
                        <div class="col-sm-12 text-center">
                            <button type="submit" name="search" class="go_btn sm_space mt-2" value="Search">'.__('submit').'</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>';

    if(empty($list_datacenters)){
        echo '<div class="notice"><b>'.__('note').' : </b> &nbsp;'.(optREQ('search') ? __('No search result found') : __('No Data Centers added')).'</div>';
    }
    else{
        
        echo'
        <div id="vpsmenu" class="vpsmenu card" onmouseover="clearTimeout(menuhider);">
            <div class="vpsmenubg d-flex align-items-center" id="vpsmenubg">
            <a href="javascript:void(0)" class="text-success"><i class="fas fa-play icon-fix d-flex align-items-center justify-content-center replace-class" title="'.__('Start VPS').'" onclick="vpsactions(\'start\')"/></i></a>
            <a href="javascript:void(0)" class="text-danger"><i class="fas fa-stop icon-fix d-flex align-items-center justify-content-center replace-class" title="'.__('Stop VPS').'" onclick="vpsactions(\'stop\')"/></i></a>
            <a href="javascript:void(0)" class="text-admin"><i class="fas fa-sync icon-fix d-flex align-items-center justify-content-center replace-class" title="'.__('Restart VPS').'"  onclick="vpsactions(\'restart\')"/></i></a>
            <a href="javascript:void(0)" class="text-danger"><i class="fas fa-power-off icon-fix d-flex align-items-center justify-content-center replace-class" title="'.__('PowerOFF VPS').'"  onclick="vpsactions(\'poweroff\')"/></i></a>'
            .(!empty($globals['novnc']) ? '<a href="javascript:void(0)" id="novncURL" class="vncButton text-primary" onclick="launchvnc(1)"/><i class="fas fa-laptop icon-fix d-flex align-items-center justify-content-center replace-class"></i></a>' : (empty($globals['disable_java_vnc']) ? '<a href="javascript:void(0)" id="java_vnc" class="vncButton " onclick="launchvnc(2)"/><i class="fas fa-laptop icon-fix d-flex align-items-center justify-content-center replace-class"></i></a>' : '')).'
            </div>
        </div>

        <div class="row mx-auto w-100 mb-3">
            <div class="col-sm-4 col-lg-4 col-md-6 text-right d-flex align-items-center">
                <div class="bottom-menu float-right w-100">
                    <div class="row my-auto">
                        <div class="p-0">
                            <label>'.__('With Selected').'</label>
                        </div>
                        <div class="col p-0">
                            <select class="custom-select" name="plans_task_select" id="plans_task_select">
                                <option value="0">---</option>
                                <option value="delete">'.__('Delete').'</option>
                            </select>
                        </div>
                        <div class="pl-2">
                            <input type="submit" id ="plans_submit" class="go_btn" name="plans_submit" value="'.__('Go').'" onclick="action_chosen(\'\' ,0 ,this); return false;">
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-sm-8 col-lg-8 col-md-6 d-flex align-items-center justify-content-end p-0 mt-2 mt-md-0 mt-lg-0">';
                page_links($globals['num_res'], $globals['cur_page'], $globals['reslen']);
                echo get_num_records($globals['num_res']).'
            </div>
        </div>
        <form accept-charset="'.$globals['charset'].'" name="multi_list_baremetal" id="multi_list_baremetal" method="post" action="" class="form-horizontal">
            <div class="w-100 mx-auto sticky">
                <table class="table table-hover tablesorter common-table">
                    <tr class="table_heading">
                        <th class="z-index-1 min_width" align="center">
                            '.get_checkbox('select_all', '', 'select_all', array('chk_it' => 0), '', 'select_all').'
                        </th>
                        <th  class="min_width" align="center">'.__('ID').'</th>
                        <th  class="w_135_tp">'.getSortHeader(__('Location'), 'location' ,51).'</th>
                        <th>'.getSortHeader(__('Name'), 'name' ,51).'</th>
                        <th >'.__('Contact').'</th>
                        <th>'.__('Floors').'</th>
                        <th>'.__('Racks').'</th>
                        <th>'.__('Baremetals').'</th>
                        <th class="text-right pr-3" colspan="3">'.__('Action').'</th>
                    </tr>
                    <tbody>';

                    $i = 1;

                    foreach ($list_datacenters as $k => $v) {
                        echo '
                        <tr id=dc_' . $k . '" class="hover_wrapper">
                            <td align="center" class="w-auto">
                                <div class="vs_loader"></div>
                                ' . get_checkbox('dc_list[]', '', '', [], $k, 'popup-checkbox') . '
                            </td>
                            <td align="left">
                                ' . $v['dcid'] . '
                            </td>
                            <td align="left d-flex gap-2" tooltip="'.$v['address'].'">
                                <img src="'.location_flag($v['country']).'" width="35" class="mr-2"/>
                                <span>'.$v['location'].'</span>
                            </td>
                            <td align="left">
                                '.$v['name'].'
                            </td>
                            <td align="text-right d-flex flex-column align-items-center justify-content-end gap-2">
                                <div>
                                    <i class="text-admin fas fa-envelope"></i>
                                    '.$v['email'].'
                                </div>
                                <div>
                                    <i class="text-admin fas fa-phone"></i>
                                    '.$v['phone'].'
                                </div>
                            </td>
                            <td align="left">
                                '.$v['total_floors'].'
                            </td>
                            <td align="left">
                                '.$v['total_racks'].'
                            </td>
                            <td align="left">
                                '.$v['total_baremetals'].'
                            </td>
                            <td id="action_' . $k . '" class="align-items-end pr-2">
                                <div class="badge_container justify-end dc-details">
                                    <!--
                                    <a href="javascript:void(0)" class="badge badge-settings" onclick="datacenters_details('.$k.', this, '.$v['rack_details']['rows'].', '.$v['rack_details']['columns'].', '.$v['rack_details']['racks'].', '.$v['rack_details']['units'].')">
                                        <i class="fas fa-info-circle"></i>
                                    </a>-->
                                    <a class="badge badge-manage" href="' . $globals['ind'] . 'act=edit_datacenter&dcid=' . $k . '" id="action_vpsmanage_' . $k . '" class="mx-2">
                                        <i class="fas fa-pencil-alt"></i>
                                    </a>
                                    <a class="badge badge-trash" href="javascript:void(0);" onclick="return action_chosen(\'delete\', '.$k.');" title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>';
                        $i++;
                    }

                    echo 
                    '</tbody>
                </table>
            </div>';
            echo
            '<div class="row mx-auto w-100 mt-5">
                <div class="col-sm-4 col-lg-4 col-md-6 text-right mb-3">
                    <div class="bottom-menu float-right w-100">
                        <div class="row my-auto">
                            <div class="p-0">
                                <label>'.__('With Selected').'</label>
                            </div>
                            <div class="col p-0">
                                <select name="user_task_select" class="custom-select" id="user_task_select">
                                    <option value="0">---</option>
                                    <option value="delete">'.__('Delete').'</option>
                                </select>
                            </div>
                            <div class="pl-2">
                                <button type="submit" class="go_btn" id="user_submit" name="user_submit" onclick="action_chosen(\'\', 0, this); return false;">'.__('Go').'</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-8 col-lg-8 col-md-6 mb-3 p-0">';
                    page_links($globals['num_res'], $globals['cur_page'], $globals['reslen']);
                    echo'
                </div>
            </div>
            
        </form>
        <div id="progress_bar" class="my-3" style="display:none;">
            <br />
            <center>
                <font id="progress_txt" size="4">'.__('action_msg').'</font>
            </center>
            <div class="my-2" align="center">
                <div class="progress w-50">
                    <div class="progress-bar bg-primary progress-bar-striped progress-bar-animated w-100">
                    </div>
                </div>
            </div>
            <center>
                '.__('notify_msg').'
            </center>
        </div>
        <div class="modal fade" role="dialog" id="conf_modal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header" id="conf_modal_head">				
                        <span class="fhead text-always-white">'.__('dont_destroy_vps_header').'</span>
                        <button type="button" class="close text-always-white" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body" id="conf_modal_body">
                        <div class="row">
                            <div class="col-xs-10 col-sm-6">
                                <label class="control-label">'.__('dont_destroy_vps').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('dont_destroy_vps_help').'"><i class="fas text-primary fa-info-circle"></i></a></label> 
                            </div>
                            <div class="col-xs-2 col-sm-6">
                                '.get_checkbox('dvps', '', 'dvps').'
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" id="saveset" class="go_btn">'.__('dont_destroy_vps_continue').'</button>
                    </div>
                </div>
            </div>
        </div>
    </div>';
    }

echo 
    '<div class="d-flex align-items-center justify-content-center my-4">
        <a href="'.$globals['ind'].'act=add_datacenter" class="go_btn">'.__('Add Datacenter').'</a>
    </div>
    </div><br>

';
softfooter();

}
