<?php

if(!defined('VIRTUALIZOR')){
	die('Hacking Attempt');
}

function getSortHeader($header_name, $sort_column, $sort_column_by, $column ,$size = 90){

	global $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=backup_dashboard&sortcolumn='.$column.'&sortby=asc"><i class="fas fa-sort-up"></i></a><br>
			<a class="text-always-white" href="'.$globals['index'].'act=backup_dashboard&sortcolumn='.$column.'&sortby=desc"><i class="fas fa-sort-down"></i></a>
		</span>
	</div>';
	return $str;
}

function get_status_icon($progress){

    $icon = [
        -1 => '<a class="badge badge-danger">Failed</a>',
        2 => '<a class="badge badge-settings">Runnig</a>',
        1 => '<a class="badge badge-success">Successful</a>',
    ];

    return $icon[$progress];

}

function backup_dashboard_theme(){

    global $theme, $l, $globals, $servers, $error, $done, $backup_stats, $backup_tasks_data, $sort_column, $sort_column_by, $search;
    
	softheader($l['<title>']);
    // Some css tweaks
    echo '
    <style>
        td:not(:has(a)), #table_tasks th, #table_backuply th {
            text-align: left;
        }
    </style>';
    
    // JS
    echo '
    <script type="text/javascript" charset="utf8" src="'.$theme['url'].'/js2/jquery-simple-tree-table.js"></script>
    <script language="javascript" type="text/javascript"><!-- // --><![CDATA[

        function multi_action(ele, data){
            console.log(data);
        }
            
        function toggle_option(option){
            if ($("#"+option).is(":hidden")){
                $("#"+option).slideDown("slow");
                $("#"+option+"_toggle_indicator").text(" - ");
            }else{
                $("#"+option).slideUp("slow");
                $("#"+option+"_toggle_indicator").text(" + ");
            }
        }

        function dashboard_donut_chart(data, donut_chart_id){

            var options = {
                series: [data["data"][0], data["data"][1]],
                chart: {
                    type: "donut",
                    width: 100,
                    height: 100,
                },

                plotOptions: {
                    pie: {
                        donut: {
                            size: "70%", // Adjust the width of the circular bar
                        }
                    }
                },

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

                dataLabels: {
                    enabled: false,
                },

                labels: [data["label"][0], data["label"][1]],

                grid:{
                    padding: {
                        top: 0,
                        right: 0,
                        bottom: 0,
                        left: 0
                    },
                },

                colors: ["#6F58FF", "#F76775"],
            };

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

        }

        // Plot the charts
        $(document).ready(function(){

            var server_vps_chart_data = {
                                data : ['.$backup_stats['vps_with_backups'].', '.$backup_stats['vps_without_backups'].'],
                                label : ["'.__J('With Backups').'", "'.__J('Without Backups').'"]
                            };
            dashboard_donut_chart(server_vps_chart_data, "#server_vps_chart");

            if('.$backup_stats['backups_full'].' == 0 && '.$backup_stats['backups_inc'].' == 0){
                $("#backup_chart").html("<div class=\'no_data_circle\'>'.__J('! No Backups Found').'</div>");
            }else{
                var backup_chart_data = {
                                    data : ['.$backup_stats['backups_full'].', '.$backup_stats['backups_inc'].'],
                                    label : ["'.__J('Full Backups').'", "'.__J('Incremental Backups').'"]
                                };
                dashboard_donut_chart(backup_chart_data, "#backup_chart");
            }

            if('.$backup_stats['success_backup_tasks'].' == 0 && '.$backup_stats['failed_backup_tasks'].' == 0){
                $("#backup_task_chart").html("<div class=\'no_data_circle\'>'.__J('! No Backup Task Found').'</div>");
            }else{
                var backup_task_chart_data = {
                                    data : ['.$backup_stats['success_backup_tasks'].', '.$backup_stats['failed_backup_tasks'].'],
                                    label : ["'.__J('Successful Tasks').'", "'.__J('Successful Tasks').'"]
                                };
                dashboard_donut_chart(backup_task_chart_data, "#backup_task_chart");
            }

            if('.$backup_stats['success_restore_tasks'].' == 0 && '.$backup_stats['failed_restore_tasks'].' == 0){
                $("#restore_task_chart").html("<div class=\'no_data_circle\'>'.__J('! No Restore Task Found').'</div>");
            }else{
                var restore_task_chart_data = {
                                    data : ['.$backup_stats['success_restore_tasks'].', '.$backup_stats['failed_restore_tasks'].'],
                                    label : ["'.__J('Successful Tasks').'", "'.__J('Successful Tasks').'"]
                                };
                dashboard_donut_chart(restore_task_chart_data, "#restore_task_chart");
            }
        });

    // ]]></script>';

    echo '
    <div class="card2 p-3 mx-3 mt-3 card_title">
        <div class="row">
            <div class="card2-title col d-flex align-items-center justify-content-center">
                '.__('Backups').' '.(empty($search) ? '<span> | Last 7 Days </span>' : '').'
            </div>
        </div>
    </div>

    <div class="bg">

        <!-- Charts -->
        <div class="row dashboard_row mt-3 mx-auto w-100">
            <!-- Server vps data card start -->
            <div class="col-lg-3 col-sm-6 col-md-6 mb-3 res_card h-50">
                <div class="card3 cluster-card1 res_card h-25">
                    <div class="card_icon_title">
                        <h5 class="text-nowrap m-0 d-flex flex-fill align-items-center justify-content-between mx-1">
                            <div>
                                <img  src="'.$theme['svg'].'vms.svg" title="'.__('RAM').'"/>
                                <a href="'.$globals['ind'].'act=vs&serid='.$globals['server'].'&search=1">
                                    Total '.VM_SHORT.'
                                </a>
                            </div>
                            <span>'.$backup_stats['num_vps'].'</span>
                        </h5>
                    </div>
                    <div class="d-flex justify-content-center mt-1">
                        <div id="server_vps_chart" class="p-0"></div>
                        <div class="w-100 my-auto ml-2">
                            <div class="d-flex align-items-center justify-content-between card_content">
                                <div class="">
                                <span class="purple_dot"></span> 
                                <label class="">'.__('With Backups').'</label>
                                </div>
                                <div class="">'.$backup_stats['vps_with_backups'].'</div>
                            </div>
                            <div class="d-flex align-items-center justify-content-between card_content">
                                <div class="">
                                <span class="red_dot"></span>
                                <label class="">'.__('Without Backups').'</label>
                                </div>
                                <div class="">'.$backup_stats['vps_without_backups'].'</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Server vps data card end -->

            <!-- Total backup data card start -->
            <div class="col-lg-3 col-sm-6 col-md-6 mb-3 res_card h-50">
                <div class="card3 cluster-card1 res_card h-25">
                    <div class="card_icon_title">
                        <h5 class="text-nowrap m-0 d-flex flex-fill align-items-center justify-content-between mx-1">
                            <div>
                                <img  src="'.$theme['svg'].'vms.svg" title="'.__('RAM').'"/>
                                <a href="'.$globals['ind'].'act=backup_dashboard">
                                    '.__('Backups').'
                                </a>
                            </div>
                            <span>'.$backup_stats['total_backups'].'</span>
                        </h5>
                    </div>
                    <div class="d-flex justify-content-center mt-1">
                        <div id="backup_chart" class="p-0"></div>
                        <div class="w-100 my-auto ml-2">
                            <div class="d-flex align-items-center justify-content-between card_content">
                                <div class="">
                                <span class="purple_dot"></span> 
                                <label class="">'.__('Full').'</label>
                                </div>
                                <div class="">'.$backup_stats['backups_full'].'</div>
                            </div>
                            <div class="d-flex align-items-center justify-content-between card_content">
                                <div class="">
                                <span class="red_dot"></span>
                                <label class="">'.__('Incremental').'</label>
                                </div>
                                <div class="">'.$backup_stats['backups_inc'].'</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Total backup data card end -->

            <!-- Backup tasks count card start -->
            <div class="col-lg-3 col-sm-6 col-md-6 mb-3 res_card h-50">
                <div class="card3 cluster-card1 res_card h-25">
                    <div class="card_icon_title">
                        <h5 class="text-nowrap m-0 d-flex flex-fill align-items-center justify-content-between mx-1">
                            <div>
                                <img src="'.$theme['svg'].'vms.svg" title="'.__('RAM').'"/>
                                <a href="'.$globals['ind'].'act=backup_dashboard&action=backuply_vpsbackups_plan&search=1">
                                    '.__('Backup Tasks').'
                                </a>
                            </div>
                            <span>'.$backup_stats['total_backup_tasks'].'</span>
                        </h5>
                    </div>
                    <div class="d-flex justify-content-center mt-1">
                        <div id="backup_task_chart" class="p-0"></div>
                        <div class="w-100 my-auto ml-2">
                            <div class="d-flex align-items-center justify-content-between card_content">
                                <div class="">
                                <span class="purple_dot"></span>
                                <a style="color: var(--black);" href="'.$globals['ind'].'act=backup_dashboard&action=backuply_vpsbackups_plan&status=1&search=1">
                                <label class="cursor-pointer">'.__('Successful').'</label>
                                </a>
                                </div>
                                <div class="">'.$backup_stats['success_backup_tasks'].'</div>
                            </div>
                            <div class="d-flex align-items-center justify-content-between card_content">
                                <div class="">
                                <span class="red_dot"></span>
                                <a style="color: var(--black);" href="'.$globals['ind'].'act=backup_dashboard&action=backuply_vpsbackups_plan&status=-1&search=1">
                                <label class="cursor-pointer">'.__('Failed').'</label>
                                </a>
                                </div>
                                <div class="">'.$backup_stats['failed_backup_tasks'].'</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Backup tasks count card end -->

            <!-- Restore tasks count card start -->
            <div class="col-lg-3 col-sm-6 col-md-6 mb-3 res_card h-50">
                <div class="card3 cluster-card1 res_card h-25">
                    <div class="card_icon_title">
                        <h5 class="text-nowrap m-0 d-flex flex-fill align-items-center justify-content-between mx-1">
                            <div>
                                <img src="'.$theme['svg'].'vms.svg" title="'.__('RAM').'"/>
                                <a href="'.$globals['ind'].'act=backup_dashboard&action=backuply_restorevps_plan&search=1">
                                    '.__('Restore Tasks').'
                                </a>
                            </div>
                            <span>'.$backup_stats['total_restore_tasks'].'</span>
                        </h5>
                    </div>
                    <div class="d-flex justify-content-center mt-1">
                        <div id="restore_task_chart" class="p-0"></div>
                        <div class="w-100 my-auto ml-2">
                            <div class="d-flex align-items-center justify-content-between card_content">
                                <div class="">
                                <span class="purple_dot"></span>
                                <a style="color: var(--black);" href="'.$globals['ind'].'act=backup_dashboard&action=backuply_restorevps_plan&status=1&search=1">
                                <label class="cursor-pointer">'.__('Successful').'</label>
                                </a>
                                </div>
                                <div class="">'.$backup_stats['success_restore_tasks'].'</div>
                            </div>
                            <div class="d-flex align-items-center justify-content-between card_content">
                                <div class="">
                                <span class="red_dot"></span>
                                <a style="color: var(--black);" href="'.$globals['ind'].'act=backup_dashboard&action=backuply_restorevps_plan&status=-1&search=1">
                                <label class="cursor-pointer">'.__('Failed').'</label>
                                </a>
                                </div>
                                <div class="">'.$backup_stats['failed_restore_tasks'].'</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Restore tasks count card end -->

        </div>            
    </div>';
        
    error_handle($error);

    if(!empty($done)){
        show_alert(__('The VPS backup was created successfully'));
    }

    echo '
    <div class="card p-2 mx-3">

        <div class="row mx-auto w-100 mb-3 justify-content-between">
            <div class="col-sm-8 col-lg-8 col-md-6 d-flex align-items-center p-0 gap-2">';
                page_links($globals['num_res'], $globals['cur_page'], $globals['reslen']);
                echo get_num_records($globals['num_res']).'
            </div>
            <div>
                <span class="icon-fix d-flex align-items-center justify-content-center" style="float: right !important;">
                    <a href="javascript:showsearch();" class="text-light">
                        <i class="fas fa-search text-black"></i>
                    </a>
                </span>
            </div>
        </div>

        <!-- Seacrch Form -->
        <div id="showsearch" class="mb-3" style="display:'.(optREQ('search') || (!empty($backup_tasks_data) && !empty($globals['showsearch'])) ? "" : "none").';">
            <form accept-charset="'.$globals['charset'].'"  class="form-horizontal" name="backup_dashboard_search" method="GET" action="" id="task_search">
                <input type="hidden" name="act" value="backup_dashboard">
                <div class="form-group_head">
                    <div class="row mx-auto w-100">
                        <div class="col-sm-4">
                            <label>'.__('Actid').'</label>
                            <input type="text" class="form-control" name="actid" id="actid" size="15" value="'.REQval('actid','').'" />
                        </div>
                        <div class="col-sm-4">
                            <label>'.__('VPS ID').'</label>
                            <input type="text" class="form-control" name="vpsid" id="vpsid" size="15" value="'.REQval('vpsid','').'" />
                        </div>
                        <div class="col-sm-4">
                            <label>'.__('User').'</label>
                            <input type="text" class="form-control" name="username" id="username" size="15" value="'.REQval('username','').'" />
                        </div>
                    </div>

                    <div class="row mx-auto w-100">
                        <div class="col-sm-4">
                            <label>'.__('Status').'</label>
                            <select class="custom-select" name="status">
                                <option value="">---</option>
                                <option value="1" '.REQselect('status', 1).'>Success</option>
                                <option value="-1" '.REQselect('status', -1).'>Failed</option>
                                <option value="2" '.REQselect('status', 2).'>Running</option>
                            </select>
                        </div>
                        <div class="col-sm-4">
                            <label>'.__('Action').'</label>
                            <select class="custom-select" name="action">
                                <option value="">---</option>
                                <option value="backuply_vpsbackups_plan" '.REQselect('action', 'backuply_vpsbackups_plan').'>'.VM_SHORT.' Backuply Backup</option>
                                <option value="backuply_restorevps_plan" '.REQselect('action', 'backuply_restorevps_plan').'>'.VM_SHORT.' Backuply Restore</option>
                            </select>
                        </div>
                        <div class="col-sm-4">
                            <label>'.__('Server').'</label>
                            <select class="custom-select" name="server">
                                <option value="-1">---</option>';
                                foreach($servers as $id => $data){
                                    echo '<option value="'.$id.'" '.REQselect('server', $id).'>'.$data['server_name'].'</option>';
                                }
                            echo'
                            </select>
                        </div>
                    </div>

                    <div class="row mx-auto w-100 my-2">
                        <div class="col-sm-12 text-center">
                            <button type="submit" name="search" value="1" class="go_btn mt-2">'.__('Submit').'</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <!-- Seacrch Form End -->';

    // Not found any VPS with backup logs
    if(empty($backup_tasks_data)){
        optREQ('search') ? show_alert(__('No VPS found'), "2") : show_alert(__('No VPS Backup Tasks Found'), "2");
        echo '<div class="notice"><b>'.__('Note').' : </b> &nbsp; '.(optREQ('search') ? __('No VPS found') : __('No VPS Backup Tasks Found')).'</div>';
   
    } else {

        echo '
        <!-- Create Backup Logs Table -->
        <div class="panel-content scrollbar-virt">
            <div class="tab-content pt-2">
                <div class="tab-pane fade show active" id="tasks-justified" role="tabpanel" aria-labelledby="tasks-tab">
                    <table border="0" cellspacing="1" cellpadding="8" class="table table-hover tablesorter" align="left" width="100%">
                        <thead>
                            <tr>
                                <th>'.getSortHeader(__('Actid'), $sort_column, $sort_column_by, 'actid','50').'</th>
                                <th>'.getSortHeader(__('VPS ID'), $sort_column, $sort_column_by, 'vpsid').'</th>
                                <th>'.getSortHeader(__('User'), $sort_column, $sort_column_by, 'user','55').'</th>
                                <th>'.getSortHeader(__('Server'), $sort_column, $sort_column_by, 'server','55').'</th>
                                <th>'.getSortHeader(__('Status'), $sort_column, $sort_column_by, 'status', 70).'</th>
                                <th style="width: 5rem;">'.__('Progress').'</th>
                                <th>'.__('Logs').'</th>
                            </tr>
                        </thead>
                        <tbody>';

                        foreach($backup_tasks_data as $actid => $tasks_data){
                            echo '<tr>
                                <td>'.$actid.'</td>
                                <td>'.$tasks_data['vpsid'].'</td>
                                <td>'.((!empty($tasks_data['uid']) && !empty($tasks_data['email'])) ? $tasks_data['email'] : 'root').'</td>
                                <td>'.$servers[$tasks_data['serid']]['server_name'].'</td>
                                <td align="left">'.get_status_icon($tasks_data['status_icon']).'</td>
                                <td>'.$tasks_data['progress'].'</td>
                                <td><button class="btn px-2 py-1" onclick="loadlogs('.$actid.');">'.__('Show').'</button></td>
                            </tr>';
                        }

                        echo '
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>';

    }

    echo '
    </div>';
    
    softfooter();
}
