<?php

//////////////////////////////////////////////////////////////
//===========================================================
// add_dcfloors_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_dcfloors_theme(){

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


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

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

    echo page_header(__('Add Datacenter Floors'), '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;
    }

    $(document).ready(function(){
        
        var floor_form = document.getElementById("floor_form");
        var floor_table_body = document.getElementById("floor_table");

        document.getElementById("addFloorBtn").addEventListener("click", () => {
            
            let floor_name = document.getElementById("floor_name").value.trim();
            let floor_number = document.getElementById("floor_number").value.trim();
            let floor_rows = document.getElementById("floor_rows").value.trim();
            let floor_columns = document.getElementById("floor_columns").value.trim();
            let floors = floor_table_body.rows.length;
            let floor_id = floors + 1 ;

            console.log(floors);
            if (!floor_name || !floor_number || !floor_rows || !floor_columns){
                showalert("Please check the Floor plan again", 1);
                return false;
            }

            let tr = document.createElement("tr");
            
            tr.innerHTML = `
                <td>${floor_id}</td>
                <td>${floor_name}</td>
                <td>${floor_number}</td>
                <td>${floor_rows}</td>
                <td>${floor_columns}</td>
                <td class="text-center action-btns">
                    <div class="badge_container">
                        <a class="badge badge-purple"><i class="fas fa-eye view" title="View"></i></a>
                        <a class="badge badge-yellow"><i class="fas fa-pencil-alt edit" title="Edit"></i></a>
                        <a class="badge badge-trash"><i class="fas fa-trash delete" title="Delete"></i></a>
                    </div>
                </td>
            `;

            floor_table_body.appendChild(tr);

            // Append hidden inputs inside the main form for PHP submission
            let inputSet = document.createElement("div");

            inputSet.innerHTML = `
                <input type="hidden" name="floors[${floor_id}][id]" value="${floor_id}">
                <input type="hidden" name="floors[${floor_id}][name]" value="${floor_name}">
                <input type="hidden" name="floors[${floor_id}][number]" value="${floor_number}">
                <input type="hidden" name="floors[${floor_id}][rows]" value="${floor_rows}">
                <input type="hidden" name="floors[${floor_id}][cols]" value="${floor_columns}">
            `;
            
            document.getElementById("floor_plan").appendChild(inputSet);
            document.getElementById("floor_plan").appendChild(inputSet);
        });

        // Table action handling
        floor_table_body.addEventListener("click", (e) => {
            const target = e.target;
            const row = target.closest("tr");
            const floor_id = row.cells[0].innerText.trim();

            if (target.classList.contains("view")) {
                const floorName = row.children[1].innerText;
                console.log(floorName);
                const rows = parseInt(row.children[3].innerText);
                const cols = parseInt(row.children[4].innerText);
                showFloorLayout(floorName, rows, cols);
            }

            function showFloorLayout(name, rows, cols) {
                const container = document.getElementById("floorPreview");
                container.innerHTML = `
                    <h6>${name} (${rows} X ${cols})</h6>
                    <div id="grid" class="mt-2"></div>
                `;

                const grid = document.getElementById("grid");

                // proper grid structure
                grid.style.display = "grid";
                // horizontal count
                grid.style.gridTemplateColumns = `repeat(${cols}, 30px)`;
                // vertical count
                grid.style.gridTemplateRows = `repeat(${rows}, 30px)`;
                // spacing between cells
                grid.style.gap = "4px";
                // center the grid
                grid.style.justifyContent = "center";
                grid.style.marginTop = "10px";

                for (let i = 0; i < rows * cols; i++) {
                    const cell = document.createElement("div");
                    cell.classList.add("floor-cell");
                    cell.style.width = "30px";
                    cell.style.height = "30px";
                    cell.style.background = "#cce5ff";
                    cell.style.border = "1px solid #99c";
                    cell.style.borderRadius = "4px";
                    cell.style.cursor = "pointer";
                    cell.style.transition = "background 0.3s ease";

                    const rowNum = Math.floor(i / cols) + 1;
                    const colNum = (i % cols) + 1;
                    cell.title = `Row ${rowNum}, Col ${colNum}`;

                    // toggle color on click
                    cell.addEventListener("click", () => {
                        cell.style.background = cell.style.background === "lightgreen" ? "#cce5ff" : "lightgreen";
                    });

                    grid.appendChild(cell);
                }

                const myModalElement = document.getElementById("floor_preview_div");
                const myModal = new bootstrap.Modal(container);
                myModal.show();


            }

            // Edit
            // this section is for the edit the row of the floor
            if (target.classList.contains("edit")) {
                row.classList.add("editing");
                const cells = row.querySelectorAll("td");

                // Convert text cells to inputs (except action cell)
                for (let i = 1; i < 5; i++) {
                    const val = cells[i].innerText.trim();
                    cells[i].innerHTML = `<input type="text" class="form-control form-control-sm" value="${val}">`;
                }

                // Change icons to save/cancel
                const actionCell = row.querySelector(".action-btns");
                actionCell.outerHTML = `
                    <td>
                        <div class="badge_container">
                            <a class="badge badge-manage"><i class="fas fa-check text-success save" title="Save"></i></a>
                            <a class="badge badge-yellow"><i class="fas fa-times text-secondary cancel" title="Cancel"></i></a>
                            <a class="badge badge-trash"><i class="fas fa-trash delete" title="Delete"></i></a>
                        </div>
                    </td>
                    `;

            } else if (target.classList.contains("save")) {
                
                // save
                // this section is for the save the changes of the floor if we did anything

                const inputs = row.querySelectorAll("input");
                const values = Array.from(inputs).map(inp => inp.value.trim() || "—");

                row.innerHTML = `
                    <td>${floor_id}</td>
                    <td>${values[0]}</td>
                    <td>${values[1]}</td>
                    <td>${values[2]}</td>
                    <td>${values[3]}</td>
                    <td class="text-center action-btns">
                        <div class="badge_container">
                            <a class="badge badge-purple"><i class="fas fa-eye view" title="View"></i></a>
                            <a class="badge badge-yellow"><i class="fas fa-pencil-alt edit" title="Edit"></i></a>
                            <a class="badge badge-trash"><i class="fas fa-trash delete" title="Delete"></i></a>
                        </div>
                    </td>
                    `;

                update_floor_inputs(floor_id, values[0], values[1], values[2], values[3]);
                
            } else if (target.classList.contains("cancel")) {
                
                // its need to cancel the changes
                // this section is for the save the changes of the floor if we did anything
                const cells = row.querySelectorAll("td");

                // get the current input values before cancel
                const original = Array.from(row.querySelectorAll("input")).map(inp => inp.defaultValue);

                // restore table
                row.innerHTML = `
                    <td>${floor_id}</td>
                    <td>${original[0]}</td>
                    <td>${original[1]}</td>
                    <td>${original[2]}</td>
                    <td>${original[3]}</td>
                    <td class="text-center action-btns">
                        <div class="badge_container">
                            <a class="badge badge-purple"><i class="fas fa-eye view" title="View"></i></a>
                            <a class="badge badge-yellow"><i class="fas fa-pencil-alt edit" title="Edit"></i></a>
                            <a class="badge badge-trash"><i class="fas fa-trash delete" title="Delete"></i></a>
                        </div>
                    </td>
                `;
                
            } else if (target.classList.contains("delete")) {
                
                // getting the floor_id of the row to delete the row
                showalert("'.__J('Are you sure you wish to delete floor ?').'", 3, function(confirm) {
                    if(confirm == false) {
                        return false;
                    }
                    
                    row.remove();

                    delete_floor_inputs(floor_id);
                    
                });
            }

        });

        // function to update the input hidden after the floor changed in ui
        function update_floor_inputs(id, name, number, rows, cols) {
            document.querySelector(`input[name="floors[${id}][name]"]`).value = name;
            document.querySelector(`input[name="floors[${id}][number]"]`).value = number;
            document.querySelector(`input[name="floors[${id}][rows]"]`).value = rows;
            document.querySelector(`input[name="floors[${id}][cols]"]`).value = cols;
        }

        // function to delete the hidden input
        function delete_floor_inputs(id) {
            document.querySelectorAll(`input[name^="floors[${id}]"]`).forEach(el => el.remove());
        }

        $("#floor_plan").submit(function(e){
            e.preventDefault();

            var dcid = $("#selected_dc").val();
            console.log(dcid);

            // here we check that the user sending any datacenter id if yes then we should call the edit_datacenter with dcid not the add_dcfloors
            if(!empty(dcid)){

                $("#selected_dc").prop("disabled", false);
                
                let act_url = "add_dcfloors";
                let url = "'.$globals['index'].'&act="+act_url+"&api=json&jsnohf=1";

                response = post_ajax_res(url, "floor_plan", "floor_plan");

                response = JSON.parse(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['index'].'act=list_dcfloors";
					});

                }else{
                    // showing alert if issue
                    showalert(response.message, 1);
                }

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

        });

        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">
            <!-- Add Floor Form -->
            <form accept-charset="'.$globals['charset'].'" name="floor_plan" method="post" action="" class="form-horizontal" id="floor_plan">
                <div class="floor-section">
                    <div class="row m-0 w-100 mb-3">
                        <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="selected_dc" id="selected_dc" required>
                                <option value="0" '.(POSTval('selected_dc') == 0 ?  'selected="selected"' : '').'>'.__('Select Datacenter').'</option>';
                                foreach($list_datacenters as $dcid => $dcdeatils){
                                    echo'<option data-image="'.location_flag($dcdeatils['country']).'" value='.$dcid.'. '.(POSTval('selected_dc') == $dcid ? 'selected="selected"' : '').' >'.$dcdeatils['name'].' ('.$countries[$dcdeatils['country']].')</option>';
                                }
                                // <option value="10" selected >softaculous</option>
                            echo'
                            </select>
                        </div>
                        <div class="col-sm-0 col-md-6 my-2"></div>
                        <div class="col-sm-12 col-md-6 my-2">
                            <label class="control-label">'.__('Floor 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" id="floor_name" size="15" value="'.POSTval('floor_name', $floor_plans['floor_name']).'" />
                        </div>
                        <div class="col-sm-12 col-md-6 my-2">
                            <label class="control-label">'.__('Floor Number').'&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="number" class="form-control w-100" id="floor_number" size="15" value="'.POSTval('floor_number', $floor_plans['floor_number']).'" />
                        </div>
                        <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>
                            <input type="number" class="form-control w-100" placeholder="e.g. 5" id="floor_rows" size="15" value="'.POSTval('floor_rows', $floor_plans['floor_rows']).'" />
                        </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>
                            <input type="number" class="form-control w-100" placeholder="e.g. 10" id="floor_columns" size="15" value="'.POSTval('floor_columns', $floor_plans['floor_columns']).'" />
                        </div>
                        <div class="d-flex align-items-center justify-content-center col-12 mt-2">
                            <button id="addFloorBtn" type="button" class="go_btn">
                                '.__('Add Floor').'
                            </button>
                        </div>
                    </div>
                    <!--
                    <div class="w-1/2 m-0 row w-100 mb-3">
                        <div id="floorPreview" class="mx-3 p-3 border text-center rounded w-100">
                            <em>No floor selected yet</em>
                        </div>
                    </div>
                    -->
                    <hr>
                    <!-- Floor Table -->
                    <div class="table-responsive">
                        <table class="table table-hover tablesorter common-table">
                            <thead class="">
                                <tr class="table_heading">
                                    <th class="min_width">'.__('ID').'</th>
                                    <th>'.__('Floor Name').'</th>
                                    <th class="w_40_tp">'.__('Floor Number').'</th>
                                    <th class="w_40_tp">'.__('Floor Rows').'</th>
                                    <th class="w_40_tp">'.__('Floor Columns').'</th>
                                    <th class="width-12 text-right">'.__('Actions').'</th>
                                </tr>
                            </thead>
                            <tbody id="floor_table">
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="form-group text-center mt-4">
                    <button type="submit" onclick="" class="go_btn mt-5 mb-3" value="'.__('Save floors').'">
                        </i>'.__('Save Floor Plan').'
                    </button>
                </div>
            </form>
        </div>
    ';
softfooter();

}
