<?php

class DASHBOARD
{
    public function __construct()
    {
        $random = rand(0, 1000000);
        echo "<link rel='stylesheet' href='/styles/dash_styles.css?v={$random}'>";
        echo "<link rel='preconnect' href='https://fonts.googleapis.com'>";
        echo "<link rel='preconnect' href='https://fonts.gstatic.com' crossorigin>";
        echo "<link href='https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap' rel='stylesheet'>";
        echo "<link href='https://fonts.googleapis.com/css2?family=Nunito+Sans:ital,opsz,wght@0,6..12,200..1000;1,6..12,200..1000&family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap' rel='stylesheet'>";
        echo "<link href='https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&display=swap' rel='stylesheet'>";
    }
    public function select_creator($dash_type, $dash_size, $dash_data, $condition, $title)
    {
        $item = new DASHBOARD;
        switch ($dash_type) {
            case 'create_graph':
                // echo'Graph';
                $item->create_graph($dash_size, $dash_data, $condition, $title);
                break;
            case 'create_details':
                // echo'Details';
                $item->create_details($dash_size, $dash_data, $condition, $title);
                break;
            case 'create_time':
                // echo'Details';
                $item->create_time($dash_size, $dash_data, $condition, $title);
                break;
            default:
                echo "Error: Invalid Dashboard Type";
        }
    }

    public function create_link($dash_size, $title, $link, $data)
    {
        $add_onclick = "onclick=\"window.location.href='{$link}'\"";
        switch ($dash_size) {
            case 'small':
                ?>
                <div <?php echo $add_onclick; ?>>
                    <div class='dashboard_small'>
                        <div class='dashboard_small_title poppins_light'><?php echo $title; ?></div>
                        <div class='dashboard_small_content nunito_sans_regular blue_neon'>
                            <?php echo $data; ?>
                        </div>
                    </div>
                </div>
                <?php

                break;

            case 'medium':
                echo "Medium Link Created";
                break;

            case 'large':
                echo "Large Link Created";
                break;

            default:
                echo "Error: Invalid Dashboard Size";
        }
    }

    public function create_link_new($dash_size, $data)
    {
        $add_onclick = "onclick=\"window.location.href='{$data['link']}'\"";

        switch ($dash_size) {
            case 'small':
                ?>
                <div <?php echo $data['link']; ?>>
                    <div class='dashboard_small'>
                        <div class='dashboard_small_title poppins_light'><?php echo $data['title']; ?></div>
                        <div class='dashboard_small_content nunito_sans_regular blue_neon'>
                            <?php echo $data['data']; ?>
                        </div>
                    </div>
                </div>
                <?php
                echo "Large Time Created";
                break;

            case 'medium':
                echo "Large Time Created";
                break;

            case 'large':
                echo "Large Time Created";
                break;

            default:
                echo "Error: Invalid Dashboard Size";
        }
    }

    public function create_time($dash_size, $dash_data, $condition, $title)
    {
        if (isset($condition) && $condition != "") {
            $new_con = "AND" . $condition;
        }
        $db = new db_safeguard();
        switch ($dash_size) {
            case 'small':
                if ($dash_data == "") {
                    // $results = $db->select_query("{$dash_data}", '*', "user_id_assigned = {$_SESSION['user_id']} {$new_con}");
                    $results_wo = $db->select_query("work_orders", '*', "user_id_assigned = {$_SESSION['user_id']} {$new_con}");
                    $results_st = $db->select_query("service_tickets", '*', "user_id_assigned = {$_SESSION['user_id']} {$new_con}");
                    // create total time recorded - irrispective of ST or WO
                    $total_time = new DateInterval('PT0S');
                    $total_time = DateInterval::createFromDateString('0 seconds');
                    $last_month_start = date('Y-m-d H:m', strtotime('first day of last month 00:01:00 - 1 minutes'));
                    $last_month_end = date('Y-m-d H:m', strtotime('last day of last month 23:59:00 '));
                    $start = "";
                    $end = "";
                    $total_tickets_completed = $results_st->num_rows;
                    while ($row = $results_st->fetch_assoc()) {
                        $times = $db->select_query("service_ticket_timeline", '*', "service_ticket_id = {$row['record_id']} AND date_time>= '{$last_month_start}' AND date_time<='{$last_month_end}' ORDER BY record_id ASC");
                        while ($time = $times->fetch_assoc()) {
                            if ($time['status'] == "start" && $start == "") {
                                $start = $time['date_time'];
                            } elseif ($time['status'] == "stop" && $start != "") {
                                $end = $time['date_time'];
                                $total_time += $this->time_between($start, $end);
                                $start = "";
                                $end = "";
                            } elseif ($time['status'] == "stop" && $start == "") {
                                $end = $time['date_time'];
                                $start = $last_month_start;
                                $total_time += $this->time_between($start, $end);
                                $start = "";
                                $end = "";
                            } elseif ($time['status'] == "completed" && $start != "" && $end == "") {
                                $end = $time['date_time'];
                            } elseif ($time['status'] == "completed" && $start == "" && $end == "") {
                            } elseif ($start != "" && $end != "") {
                                $total_time += $this->time_between($start, $end);
                                $start = "";
                                $end = "";
                            } else {
                                echo "Error: Time not calculated";
                            }
                        }
                    }
                    echo "start: $start <BR>";
                    echo "end: $end <BR>";
                    $start = "";
                    $end = "";

                    while ($row = $results_wo->fetch_assoc()) {
                        $times = $db->select_query("work_order_timeline", '*', "work_order_id = {$row['record_id']} AND date_time>= '{$last_month_start}' AND date_time<='{$last_month_end}' ORDER BY record_id ASC");
                        while ($time = $times->fetch_assoc()) {
                            if ($time['status'] == "start" && $start == "") {
                                $start = $time['date_time'];
                            } elseif ($time['status'] == "stop" && $start != "") {
                                $end = $time['date_time'];
                                $total_time += $this->time_between($start, $end);
                                $start = "";
                                $end = "";
                            } elseif ($time['status'] == "stop" && $start == "") {
                                $end = $time['date_time'];
                                $start = $last_month_start;
                                $total_time += $this->time_between($start, $end);
                                $start = "";
                                $end = "";
                            } elseif ($time['status'] == "sent_for_review" && $start == "" && $end == "") {
                                // $end = $time['date_time'];
                            } elseif ($time['status'] == "review_start" && $start == "" && $end == "") {
                                $start = $time['date_time'];
                            } elseif ($time['status'] == "review_stop" && $start != "" && $end == "") {
                                $end = $time['date_time'];
                                $total_time += $this->time_between($start, $end);
                                $start = "";
                                $end = "";
                            } elseif ($time['status'] == "review_stop" && $start == "" && $end == "") {
                                // $end = $time['date_time'];
                                echo "Error: DB error - review_stop without start";
                            } elseif ($time['status'] == "sent_for_review" && $start == "" && $end == "") {
                            } elseif ($time['status'] == "completed" && $start != "" && $end == "") {
                                $end = $time['date_time'];
                            } elseif ($time['status'] == "completed" && $start == "" && $end == "") {
                            } elseif ($start != "" && $end != "") {
                                $total_time += $this->time_between($start, $end);
                                $start = "";
                                $end = "";
                            } else {
                                echo "Error: Time not calculated record_id: {$row['record_id']} time_id: {$time['record_id']}<br>";
                            }
                        }
                    }


                } else {
                    $results = $db->select_query("{$dash_data}", '*', "user_id_assigned = {$_SESSION['user_id']} {$new_con}");
                    $total_time = new DateInterval('PT0S');
                    $total_time = DateInterval::createFromDateString('0 seconds');
                    $last_month_start = date('Y-m-d H:m', strtotime('first day of last month 00:01:00 - 1 minutes'));
                    $last_month_end = date('Y-m-d H:m', strtotime('last day of last month 23:59:00 '));
                    $start = "";
                    $end = "";
                    $total_tickets_completed = $results->num_rows;
                    while ($row = $results->fetch_assoc()) {
                        $times = $db->select_query("service_ticket_timeline", '*', "service_ticket_id = {$row['record_id']} AND date_time>= '{$last_month_start}' AND date_time<='{$last_month_end}' ORDER BY record_id ASC");
                        while ($time = $times->fetch_assoc()) {
                            if ($time['status'] == "start" && $start == "") {
                                $start = $time['date_time'];
                            } elseif ($time['status'] == "stop" && $start != "") {
                                $end = $time['date_time'];
                                $total_time += $this->time_between($start, $end);
                                $start = "";
                                $end = "";
                            } elseif ($time['status'] == "stop" && $start == "") {
                                $end = $time['date_time'];
                                $start = $last_month_start;
                                $total_time += $this->time_between($start, $end);
                                $start = "";
                                $end = "";
                            } elseif ($time['status'] == "completed" && $start != "" && $end == "") {
                                $end = $time['date_time'];
                            } elseif ($time['status'] == "completed" && $start == "" && $end == "") {
                            } elseif ($start != "" && $end != "") {
                                $total_time += $this->time_between($start, $end);
                                $start = "";
                                $end = "";
                            } else {
                                echo "Error: Time not calculated";
                            }
                        }
                    }
                }
                ?>
                <div>
                    <div class='dashboard_small'>
                        <div class='dashboard_small_title poppins_light'><?php echo $title; ?></div>
                        <div class='dashboard_small_content nunito_sans_regular blue_neon'>
                            <?php echo number_format($total_time / 60, 2, ".", ","); ?>
                        </div>
                    </div>
                </div>
                <?php
                break;
            case 'medium':
                $results = $db->select_query("{$dash_data}", '*', "user_id_assigned = {$_SESSION['user_id']} {$new_con}");
                $total_time = new DateInterval('PT0S');
                $total_time = DateInterval::createFromDateString('0 seconds');
                $last_month_start = date('Y-m-d H:m', strtotime('first day of last month 00:01:00 - 1 minutes'));
                $last_month_end = date('Y-m-d H:m', strtotime('last day of last month 23:59:00 '));
                $start = "";
                $end = "";
                // $results_tickets = $db->select_query("{$dash_data}", '*', "user_id_assigned = {$_SESSION['user_id']} AND completed = 'COMPLETED' ");

                $total_tickets_completed = 0;
                while ($row = $results->fetch_assoc()) {
                    $times = $db->select_query("service_ticket_timeline", '*', "service_ticket_id = {$row['record_id']} AND date_time>= '{$last_month_start}' AND date_time<='{$last_month_end}' ORDER BY record_id ASC");
                    while ($time = $times->fetch_assoc()) {
                        if ($time['status'] == "start" && $start == "") {
                            $start = $time['date_time'];
                        } elseif ($time['status'] == "stop" && $start != "") {
                            $end = $time['date_time'];
                            $total_time += $this->time_between($start, $end);
                            $start = "";
                            $end = "";
                        } elseif ($time['status'] == "stop" && $start == "") {
                            $end = $time['date_time'];
                            $start = $last_month_start;
                            $total_time += $this->time_between($start, $end);
                            $start = "";
                            $end = "";
                        } elseif ($time['status'] == "completed" && $start != "" && $end == "") {
                            $end = $time['date_time'];
                            $total_tickets_completed++;
                        } elseif ($time['status'] == "completed" && $start == "" && $end == "") {
                            $total_tickets_completed++;
                        } elseif ($start != "" && $end != "") {
                            $total_time += $this->time_between($start, $end);
                            $start = "";
                            $end = "";
                        } else {
                            echo "Error: Time not calculated";
                        }
                    }
                }
                $total_time_in_hours = number_format($total_time / 60, 2, ".", ",");
                ?>
                <div>
                    <div class='dashboard_medium'>
                        <div class="dashboard_medium_stats_list">
                            <div class='dashboard_medium_stats poppins_light'><?php echo $title; ?></div>
                            <div class='dashboard_medium_stats nunito_sans_regular blue_neon' style="font-size: 2em;">
                                <?php echo $total_time_in_hours; ?>
                            </div>
                            <div class='dashboard_medium_stats poppins_light'>Total Complete Service Tickets:</div>
                            <div class='dashboard_medium_stats nunito_sans_regular blue_neon' style="font-size: 2em;">
                                <?php echo $total_tickets_completed; ?>
                            </div>
                            <div class='dashboard_medium_stats poppins_light'>Average Time Spent on Service Tickets:</div>
                            <div class='dashboard_medium_stats nunito_sans_regular blue_neon' style="font-size: 2em;">
                                <?php echo $total_tickets_completed == 0 ? "How dare you not finish a service ticket !!!!! " : number_format($total_time_in_hours / $total_tickets_completed, 2, ".", ","); ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php

                break;
            case 'large':
                echo "Large Time Created";
                break;
            default:
                echo "Error: Invalid Dashboard Size";
        }
    }

    private function create_graph($dash_size, $dash_data, $condition, $title)
    {
        if (isset($condition) && $condition != "") {
            $new_con = "AND" . $condition;
        }

        $db = new db_safeguard();
        $results = $db->select_query("{$dash_data}", '*', "user_id_assigned = {$_SESSION['user_id']} {$new_con}");

        switch ($dash_size) {
            case 'small':
                $result = $results->num_rows();
                echo "{$result}";

                echo "Small Graph Created";
                break;
            case 'medium':
                echo "Medium Graph Created";
                break;
            case 'large':
                echo "Large Graph Created";
                break;
            default:
                echo "Error: Invalid Dashboard Size";
        }
    }

    private function create_details($dash_size, $dash_data, $condition, $title)
    {
        if (isset($condition) && $condition != "") {
            $new_con = " AND " . $condition;
        } else {
            $new_con = "";
        }
        $db = new db_safeguard();
        $results = $db->select_query("$dash_data", '*', "user_id_assigned = {$_SESSION['user_id']} $new_con");
        if ($dash_data == "work_orders") {
            $redirect_to = "/app/work_orders/active_work_orders.php";
        } elseif ($dash_data == "service_tickets") {
            $redirect_to = "/app/service_tickets/active_tickets.php";
        } else {
            $redirect_to = "";
        }



        switch ($dash_size) {
            case 'small':
                $result = $results->num_rows;
                echo "<div class='dashboard_small'>
                <div class='dashboard_small_title poppins_light'>{$title}</div>
                    <div class='dashboard_small_content nunito_sans_regular'>
                        <a style='color: #04ccfb;text-decoration:none;' href='{$redirect_to}'>{$result}</a>
                    </div>
                </div>";

                break;
            case 'medium':
                $result = $results->num_rows;
                echo "<div class='dashboard_medium'>
                <div class='dashboard_medium_title poppins_light'>
                <div class='dashboard_small_title poppins_light'>{$title}</div>
                <div class='dashboard_medium_number nunito_sans_regular'><a style='color: #04ccfb;text-decoration:none;' href='{$redirect_to}'>{$result}</a></div>
                </div>";
                echo "<div class='dashboard_medium_list'>";
                while ($row = $results->fetch_assoc()) {
                    // echo $row['client_id'];
                    if ($dash_data == "service_tickets") {
                        $clients = $db->select_query("clients", '*', "record_id = {$row['client_id']}");

                        if (!is_string($clients)) {
                            if ($clients->num_rows > 0) {
                                $client = $clients->fetch_assoc();
                            } else {
                                $project = $db->select_query("projects", '*', "record_id = {$row['project_id']}");
                                if ($project->num_rows > 0) {
                                    $project = $project->fetch_assoc();
                                    $client = $db->select_query("clients", '*', "record_id = {$project['client_id']}")->fetch_assoc();
                                } else {
                                    $client['name'] = "No Client";
                                }
                            }
                        }
                        echo "<div class='list_items'>
                        <button inactive class='list_button'>{$row['name']}</button>
                        <button inactive class='list_button'>{$client['name']}</button>
                        <button inactive class='list_button'>{$row['date_time_created']}</button>";
                    } else {

                        echo "<div class='list_items'>
                        <button inactive class='list_button'>{$row['name']}</button>
                        <button inactive class='list_button'>SJ PROBLEM</button>
                        <button inactive class='list_button'>{$row['date_time_created']}</button>";
                    }
                    ?>
                    <button class='list_button' style="background-color: #04ccfb"
                        onclick="redirect('<?php echo $row['record_id'] ?>','<?php echo "$dash_data"; ?>')"> View </button>
                    <?php
                    echo "</div>";
                }
                ?>
                <script>
                    function redirect(id, type) {
                        if (type == "work_orders") {
                            window.location.assign("/app/work_orders/work_order.php?record_id=" + id);
                        } else if (type == "service_tickets") {
                            window.location.assign("/app/service_tickets/complete_service_tickets.php?record_id=" + id);
                        }
                    }
                </script>
                <?php
                echo "</div>";
                ;
                echo "</div>";

                // echo "Medium details Created";
                break;
            case 'large':
                echo "Large details Created";
                break;
        }
    }

    private function time_between($start, $end)
    {
        $start = new DateTime($start);
        $end = new DateTime($end);
        $time_difference = $start->diff($end);
        $total_minutes = 0;
        $total_minutes += $time_difference->h * 60;
        $total_minutes += $time_difference->i;
        return $total_minutes;
    }
}
