<?php

//////////////////////////////////////////////////////////////
//===========================================================
// add_dcracks_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 add_dcracks_theme(){

    global $theme, $globals, $kernel, $l, $error, $done, $SESS, $baremetals, $list_datacenters, $dc_locations, $countries, $floor_plans, $list_dcfloors;


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

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

    echo page_header(__('Add Datacenter Rack'), 'fas fa-server', '', 1, 0, '');

    error_handle($error);

    if($done){
        show_alert(__('saved'));
    }

    echo'
    <script>

    function get_ajax_reps(url){
        var data_response = "";
        $.ajax({
            type:"GET",
            url: url,
            async: false,
            success:function(data){
                data_response = data;
            }
        });

        return data_response;
    }

    // common function for every ajax call so no need to write again and again
    function post_ajax_res(url, formname, post_name, dcid_number=""){
        let response_data = "";
        let dcid_join = "";

        console.log(dcid_number);

        if(dcid_number){
            dcid_join = "&selected_dc="+dcid_number;
        }

        let data = $("#"+formname).serialize()+"&"+post_name+"=1"+dcid_join;

        $.ajax({
            type: "POST",
            url: url,
            data: data,
            async: false,
            success:function(data_res){
                response_data = data_res;
            },
        });

        return response_data;
    }

    function check_floor_plan(selected_dc_id){

        // first we need to reset the options so last selecte DC floors will not show
        let temp_options = `<option value="0">'.__('Select Floor').'</option>
                            <option disabled value="">'.__('No Floors Added. Please Choose Valid Datacenter').'</option>`;

        $("#select_rack_floor").html(temp_options);
        $rack_plan_form = document.getElementById("rack_plan_details");
        $("#rack_plan_details").hide();

        let dcid = $(selected_dc_id).val();
        let selected_dc =  $(selected_dc_id).find(":selected");
        let dc_name = selected_dc.data("name")

        if(dcid){
            
            act_url = "'.$globals['index'].'&act=add_dcracks&api=json&jsnohf=1";

            $.ajax({
                type: "GET",
                url: act_url,
                data: {"dcid":dcid},
                async: false,
                success:function(response){

                    response = JSON.parse(response);

                    console.log(response);

                    if(response.status == "success") {
                            
                        let data = response.data;
                        let message = response.message;

                        if(data == -1){
                            let mesaage = `${message} </br> Please Add floors in <a href="'.$globals['index'].'act=add_dcfloors'.'">${dc_name}</a> Datacenter`;
                            showalert(mesaage, 2);
                            return false;
                        
                        }else{
                            
                            var floor_plans = data;
                            var	temp_options = `<option value="0">'.__j('Select Floor').'</option>`;
                            
                            $.each(floor_plans, function(key, value){
                                temp_options += `<option data-dcid="${value["dcid"]}" data-number="${value["floor_number"]}" value="${value["flid"]}" >${value["floor_name"]} (Floor Number: ${value["floor_number"]})</option>`;
                            });

                            $("#select_rack_floor").html(temp_options);
                        }

                    }
                },
            });

        } else {
            showalert("No datacenter Selected", 1);
        }
    }

    function floor_plan_change(floor_option){

        let option = floor_option.options[floor_option.selectedIndex];
        let flid = option.value;
        let dcid = option.dataset.dcid;
        
        if(flid > -1){

            // Get the user plan and fill the details
            var url = "'.$globals['index'].'&act=add_dcracks&flid="+flid+"&selected_dc="+dcid+"&api=json";
            resource_vals = get_ajax_reps(url);
            resource_vals = JSON.parse(resource_vals);
            temp_racks_options = resource_vals.data.total_racks;
            temp_floors_options = resource_vals.data.total_floors;

            var	temp_options = `<option value="-1" selected="selected">'.__j('Add Rack').'</option>`;
            
            $.each(temp_racks_options, function(key, value){
                temp_options += `<option value="${value["rackid"]}">${value["rack_name"]}</option>`;
            });

            $("#select_rack").html(temp_options);

            $.each(temp_floors_options, function( index, value ){

                if($("#rack_plan").find("[name="+ index +"]")){

                    var ele = $("#rack_plan").find(`[name="${index}"]`);

                    if (index == "floor_cols" || index == "floor_rows") {

                        let select = ""
                        
                        // choosing which item need to inject in options
                        if(index == "floor_cols") {
                            select = document.getElementById("selected_floor_cols");
                        }else{
                            select = document.getElementById("selected_floor_rows");
                        }
                        
                        // clear existing options
                        select.innerHTML = "";

                        // convert to number
                        let total = parseInt(value);

                        for (let i = 1; i <= total; i++) {
                            let option = document.createElement("option");
                            option.value = i;
                            option.textContent = i;
                            select.appendChild(option);
                        }
                    }
                }
            });

            $("#rack_plan_details").show();
        }else{
            $("#rack_plan_details").hide();
        }
    }

    $(document).ready(function(){

        $("#rack_plan").submit(function(){
            
            let dcid = Number($("#selected_dc").val());

            if(!empty(dcid)){
                
                let act_url = "add_dcracks";
                let url = "'.$globals['index'].'&act="+act_url+"&api=json&jsnohf=1";

                let response = post_ajax_res(url, "rack_plan", "add_rack");

                response = JSON.parse(response);

                console.log(response);

                if(response.status == "success"){
                    
                    // we are adding the data in the next tab select
                    let response_data = response.data;
                    showalert(response.message);
                    $("#alert-modal").on("hidden.bs.modal", function (e) {
						// put your default event here
						window.location.href="'.$globals['ind'].'act=list_dcracks";
					});

                }else{
                    // showing alert if issue
                    let data = response.data;
                    let rack_name = data["rack_name"];
                    let rack_id = data["rackid"];

                    let message = `<b>"${rack_name}"</b> Rack position already exist </br> Do you want to edit that rack, then please <a href="'.$globals['index'].'act=edit_dcfloors&rackid='.'${rack_id}">click here<a>`;
                    showalert(message, 1);
                }

            }else{
                showalert("'.__j('PLease Select Datacenter to add floor').'", 1);
            }

            return false;

        });

        function formatOption(state) {
            if (!state.id) {
                return state.text; // default option (placeholder)
            }

            let img = $(state.element).data("image");

            if (!img) {
                return state.text;
            }

            let $state = $(`
                <span style="display:flex; align-items:center;">
                    <img src="${img}" style="width:22px; height:15px; margin-right:8px; object-fit:cover;">
                    ${state.text}
                </span>
            `);

            return $state;
        }

        $("#selected_dc").select2({
            templateResult: formatOption,
            templateSelection: formatOption,
        });

    });

    </script>
        <div class="card p-2 mx-3">
            <form accept-charset="'.$globals['charset'].'" name="edit_dcracks" method="post" action="" class="form-horizontal" id="rack_plan">
                <div class="row mx-auto w-100 ">
                    <div class="col-sm-12 col-md-6 my-2">
                        <label class="control-label">'.__('Datacenter Name').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('A unique name for your reference').'"><i class="fas text-primary fa-info-circle"></i></a></label>
                        <select class="custom-select form-select w-100" name="dcid" id="selected_dc" onchange="check_floor_plan(this);" required>
                            <option value="0" >'.__('Select Datacenter').'</option>';
                            foreach($list_datacenters as $dcid => $dcdetails){
                                echo'<option data-name="'.$dcdetails['name'].'" data-image="'.location_flag($dcdetails['country']).'" value='.$dcid.'. '.(POSTval('selected_dc') == $dcid ? 'selected="selected"' : '').' >'.$dcdetails['name'].' ('.$countries[$dcdetails['country']].')</option>';
                            }
                            echo'
                        </select>
                    </div>
                    <div class="col-sm-12 col-md-6 my-2">
                        <label class="control-label">'.__('Select Floor').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('Select option whether you want to add or use any existing user plan').'"><i class="fas text-primary fa-info-circle"></i></a></label>
                        <select class="custom-select virt-select w-100" name="flid" onchange="floor_plan_change(this);" id="select_rack_floor" required>
                            <option value="0" '.(POSTval('select_rack_floor') == 0 ?  'selected="selected"' : '').'>'.__('Select Floor').'</option>
                            <option disabled value="">'.__('No Floors Added. Please Choose Valid Datacenter').'</option>
                        </select>
                    </div>
                </div>
                <div class="row mx-auto w-100 mb-3" style="display:none;" id="rack_plan_details">
                    <div class="col-sm-12 col-md-6 my-2">
                        <label class="control-label">'.__('Floor Rows').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('A unique name for your reference').'"><i class="fas text-primary fa-info-circle"></i></a></label>
                        <select class="custom-select virt-select w-100" name="row_number" id="selected_floor_rows"></select>
                    </div>
                    <div class="col-sm-12 col-md-6 my-2">
                        <label class="control-label">'.__('Floor Columns').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('A unique name for your reference').'"><i class="fas text-primary fa-info-circle"></i></a></label>
                        <select class="custom-select virt-select w-100" name="col_number" id="selected_floor_cols"></select>
                    </div>
                    <div class="col-sm-12 col-md-6 my-2">
                        <label class="control-label">'.__('Rack Name').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('A unique name for your reference').'"><i class="fas text-primary fa-info-circle"></i></a></label>
                        <input type="text" class="form-control w-100" name="rack_name" id="rack_name" size="15" value="'.POSTval('rack_name', $floor_plans['rack_name']).'" required/>
                    </div>
                    <div class="col-sm-12 col-md-6 my-2">
                        <label class="control-label">'.__('Rack Height').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('A unique name for your reference').'"><i class="fas text-primary fa-info-circle"></i></a></label>
                        <select class="custom-select virt-select w-100" name="rack_height" id="rack_height">';
                            for($i=1; $i<121; $i++) {
                                echo'
                                    <option value="'.$i.'">'.$i.'</option>
                                ';
                            }
                        echo'
                        </select>
                    </div>
                </div>
                <div class="text-center">
                    <button type="submit" onclick="" name="save_user_plan_btn" class="go_btn my-5" value="'.__('Save User Plan').'">'.__('Save Rack').'</button>
                </div>
            </form>
        </div>
    ';
softfooter();

}
