<?php
session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header("Location: index.php");
    exit;
}
require_once('connection.php');
require_once('connectionUI.php');
$db = new Connection();
$dbui = new ConnectionUI();
$query = "SELECT users.username as username, crawlers.title, instances_running.*
                    FROM instances_running
                    JOIN users ON users.id = instances_running.user_id
                    JOIN crawlers ON crawlers.id = instances_running.crawler_id
                    AND users.username NOT LIKE '%DEMO%' AND users.username NOT LIKE '%TEST%'
                    ";

function generateStepButton($value)
{
    if ($value === 'completed') {
        return "<button class='green-button' style'font-size: 12px;    padding: 8px 7px 9px;'type='submit' onclick='buttonstatusClicked(\"Completed\")'>Completed</button>";
    } elseif ($value === 'running') {
        return "<button class='primary-button' style'font-size: 12px;    padding: 8px 7px 9px;'type='submit' onclick='buttonstatusClicked(\"Running\")'>Running</button>";
    } elseif ($value === 'pending') {
        return "<button class='mehroon-button' style'font-size: 12px;    padding: 8px 7px 9px;'type='submit' onclick='buttonstatusClicked(\"Pending\")'>Pending</button>";
    }elseif ($value === 'break') {
        return "<button class='yellow-button' style'font-size: 12px;    padding: 8px 7px 9px;'type='submit' onclick='buttonstatusClicked(\"Break\")'>Break</button>";
    } else {
        return $value;
    }
}
$website_name_query = "SELECT DISTINCT crawlers.title, crawlers.id as web_id
                            FROM user_crawlers
                            JOIN crawlers ON crawlers.id = user_crawlers.crawler_id
                            ORDER BY crawlers.title ASC";
$website_name_result = $dbui->Query($website_name_query);
$user_name_query = "SELECT DISTINCT users.username as username, users.id as user_id
                                FROM user_crawlers
                                JOIN users ON users.id = user_crawlers.user_id
                                WHERE users.username NOT LIKE '%DEMO%' AND users.username NOT LIKE '%TEST%'
                                ORDER BY users.username ASC";
$user_name_result = $dbui->Query($user_name_query);
$result = $db->Query($query);
?>
<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">
    <style>
        /* Default styles for the table */
        #dataTable {
            font-size: 12px;
            width: 100%;
            text-align: center;
            background-color: black;
            box-shadow: 0px 3px 8px 0 rgba(0, 0, 0, 0.5);
            border: 2px solid black;
            margin-bottom: 10px;
        }

        #dataTable thead {
            color: white;
            font-weight: 400;
            background-color: black;
        }

        #dataTable th {
            background-color: #000;
            border: 2px solid white;
            font-size: medium;
            font-weight: bolder;
        }

        #dataTable td {
            border: 1px solid black;
            font-family: Helvetica;
            font-size: 14px;
            line-height: 0.5;
            color: #545454;
        }

        #dataTable tbody {
            color: black;
            text-align: center;
            font-family: Arial, sans-serif;
        }

        /* Styles for sorted columns */
        #dataTable th.sorting_asc,
        #dataTable th.sorting_desc {
            background-color: #333;
            /* Change background color for sorted columns */
            color: white;
            /* Change text color for sorted columns */
        }

        .dataTables_wrapper .dataTables_paginate {
            margin-bottom: 11px;
            color: #333;
        }

        .dataTables_wrapper .dataTables_info .dataTable_paginate {
            padding: 15px 26px 37px 18px;
        }

        .dataTables_wrapper .dataTable_length {
            padding: 15px 26px 37px 18px;
        }

        .dataTables_paginate .paging_simple_numbers {
            padding: 15px 26px 37px 18px;
        }

        .dataTables_wrapper .paginate_button {
            padding: 15px 26px 37px 18px;
            margin: 0 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
            cursor: pointer;
            background-color: aqua;
            color: white;
            box-shadow: 0px 3px 8px 0 rgba(0, 0, 0, 0.5);
        }

        .top {
            --offset: 50px;
            opacity: 0.2;
            position: sticky;
            bottom: 20px;
            margin-right: 10px;
            place-self: end;
            margin-top: calc(100vh + var(--offset));
            /* visual styling */
            text-decoration: none;
            padding: 10px;
            font-family: sans-serif;
            color: #fff;
            background: #000;
            border-radius: 100px;
            white-space: nowrap;
        }

        .top:hover {
            opacity: 1;
            background-color: #ff9900;
        }

        a:hover {
            opacity: none;
            text-decoration: none;
            background-color: #ff9900;
            color: #fff;
            /* new color on hover */
        }
    </style>

</head>

<body>
    <div id='crawler_content_Container'>
        <div class='row'>
            <div class='col-md-4'>
                <label style='margin-left: -169px;margin-bottom: -137px;margin-top:4px'>Client : </label>
                <select id='searchByname' class='form-control' style='font-weight: bold;font-size: 12px;border: 2px solid black;height: 31px;margin-bottom: 12px;top: 20px;right: 20px;z-index: 1000;width:auto;margin-left:-112px;margin-top:-2px'>
                    <option value='all'>All</option>
                    <?php
                    foreach ($user_name_result as $row) {
                        echo "<option value='" . $row['user_id'] . "'>" . $row['username'] . "</option>";
                    } ?>
                </select>
            </div>
            <div class='col-md-4'>
                <label style='margin-left: -215px; margin-bottom: -132px;margin-top:4px'>Website : </label>
                <select id='searchByweb' class='form-control' style='font-weight: bold;font-size: 12px;border: 2px solid black;height: 32px;margin-bottom: -17px;top: 20px;right: 20px;z-index: 1000;width:51%;margin-left: -143px'>
                    <option value='all'>All</option>
                    <?php
                    foreach ($website_name_result as $row) {
                        echo "<option value='" . $row['web_id'] . "'>" . $row['title'] . "</option>";
                    } ?>
                </select>
            </div>
            <div class='col-md-4'>
                <label style='margin-left: -253px; margin-bottom: -132px;margin-top:4px'>Status : </label>
                <select id='searchByStatus' class='form-control' style='font-weight: bold;font-size: 12px;border: 2px solid black;height: 31px;margin-bottom: -17px;top: 20px;right: 20px;z-index: 1000;width:52%;margin-left:-194px'>
                    <option value='all'>All</option>
                    <option value='2'>Completed</option>
                    <option value='1'>Running</option>
                    <option value='0'>Pending</option>
                    <option value='3'>Break</option>
                </select>
            </div>
            <!-- <div class="col-md-4">
                <label style='margin-left: 101px; margin-bottom: -132px;margin-top:-7px'>Date : </label>
                <input id="searchByDate" type="date" style='margin-left: 152px; margin-bottom: -132px;margin-top:-14px; width:45%' class="form-control">
            </div> -->
            <!-- <div class="col-md-4">
                <button class="primary-button" id="download_data_crawler" style="width: 60%; margin-left:629px;margin-top:-78px;padding:11px;margin-bottom:-37px;background-color:coral">Download Crawled Report</button>
            </div> -->
        </div>
        <div id='tableContainer' style='margin: -172px'>
            <table id='dataTable' style='font-size: 12px;width:100%;text-align:center;background-color:black;box-shadow: 0px 3px 8px 0 rgba(0, 0, 0, 0.5);border: 2px solid black;margin-bottom: 10px;'>
                <!-- <thead class='thead-dark'> -->
                <thead style="color:white;font-weight:400;background-color:black">
                    <tr>
                        <th class='fixed-width' style="background-color: #000;border: 2px solid white;font-size: medium;font-weight: bolder;">Client</th>
                        <th class='fixed-width' style='background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;'>Website</th>
                        <th style="background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;">Instances</th>
                        <th style="background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;">Row Limit</th>
                        <th style="background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;">Number Of Products Done</th>
                        <th style="background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;">Start Date</th>
                        <th style="background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;">Status</th>
                    </tr>
                </thead>
                <tbody style="color: black; text-align: center; font-family: Arial, sans-serif;">
                    <?php
                    $counter = 0;
                    $current_day = date('d-m-Y');
                    foreach ($result as $row) {
                        echo "<tr style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;'>";
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;'>" . $row['username'] . "</td>";
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'>" . $row['title'] . "</td>";
                        $step1Value = $row['status'];
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'>" . $row['instances'] . "</td>";
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'>" . $row['row_limit'] . "</td>";
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'>" . $row['products_done'] . "</td>";
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'>" . /*$current_day*/  date('Y-m-d', strtotime($row['created']))  . "</td>";
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;    padding: 8px 7px 9px;'>" . generateStepButton($step1Value) . "</td>";
                        echo "</tr>";
                        $counter++;
                    }
                    ?>
                </tbody>
            </table>
            <a href="#" class="top">Back to Top &#8593;</a>
        </div>
        <!-- <a href="#" class="top">Back to Top &#8593;</a> -->
    </div>
    <script async></script>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/datatables@1.10.18/media/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function() {

            $('#crawler_content_Container').show();

            $('#cloneStatusButton').addClass('passive-info');
            $('#crawlersStatusButton').addClass('active-button');
            $('#loadingContainer').hide();
            var currentDate = new Date();
            var currentDay = currentDate.getDay();
            var ajaxSettings = {
                method: 'GET',
                success: function(response) {
                    console.log(response);
                    if (typeof response === 'object' && response.data) {
                        var data = response.data;
                        dataTable = $('#dataTable').DataTable({
                            columns: columns,
                            data: data
                        });
                    } else {
                        console.error('Invalid JSON response');
                    }
                    $('#tableContainer').show();
                },
                error: function(xhr, status, error) {
                    console.error(error);
                }
            };
            var columns = [{
                    data: '0'
                },
                {
                    data: '1'
                },
                {
                    data: '2'
                },
                {
                    data: '3'
                },
                {
                    data: '4'
                },
                {
                    data: '5'
                },
                {
                    data: '6',
                    render: generateStepButtons
                }
            ];
            var dataTable = $('#dataTable').DataTable({
                pageLength: 100,
                searching: false,
                lengthChange: false,
            });

            function generateStepButtons(data, type, row) {
                var value = data || '';
                if (value === 'completed') {
                    return "<button class='green-button' style'font-size: 12px;' type='submit' onclick='buttonstatusClicked(\"" + 'Completed' + "\")'>" + 'Completed' + "</button>";
                } else if (value === 'running') {
                    return "<button class='primary-button' style'font-size: 12px;'type='submit' onclick='buttonstatusClicked(\"" + 'Running' + "\")'>" + 'Running' + "</button>";
                }else if (value === 'break') {
                    return "<button class='yellow-button' style'font-size: 12px;'type='submit' onclick='buttonstatusClicked(\"" + 'Break' + "\")'>" + 'Break' + "</button>";
                } else {
                    return "<button class='mehroon-button' style'font-size: 12px;'type='submit' onclick='buttonstatusClicked(\"" + 'Pending' + "\")'>" + 'Pending' + "</button>";
                }
            }

            function updateDataTable(statusId, name, web, date) {
                $('#loadingContainer').show();
                $.ajax({
                    url: 'code.php',
                    method: 'GET',
                    data: {
                        statusId: statusId,
                        name: name,
                        web: web,
                        date: date
                    },
                    success: function(response) {
                        $('#loadingContainer').hide();
                        if (dataTable) {
                            dataTable.clear().destroy();
                        }
                        dataTable = $('#dataTable').DataTable({
                            pageLength: 100,
                            lengthChange: false,
                            columns: columns,
                            searching: false,
                            data: response.data
                        });
                    },
                    error: function() {
                        $('#loadingContainer').hide();
                    }
                });
            }

            $('#searchByStatus').on('change', function() {
                var statusId = $(this).val();
                var name = $('#searchByname').val();
                var web = $('#searchByweb').val();
                var date = $('#searchByDate').val();
                updateDataTable(statusId, name, web, date);
            });

            $('#searchByweb').on('change', function() {
                var statusId = $('#searchByStatus').val();
                var name = $('#searchByname').val();
                var web = $(this).val();
                var date = $('#searchByDate').val();
                updateDataTable(statusId, name, web, date);
            });

            $('#searchByname').on('change', function() {
                var statusId = $('#searchByStatus').val();
                var name = $(this).val();
                var web = $('#searchByweb').val();
                var date = $('#searchByDate').val();
                updateDataTable(statusId, name, web, date);
            });

            $('#searchByDate').on('change', function() {
                var statusId = $('#searchByStatus').val();
                var name = $('#searchByname').val();
                var web = $('#searchByweb').val();
                var date = $(this).val();
                updateDataTable(statusId, name, web, date);

            })
            $('#cloneStatusButton').on('click', function() {
                $('#filter_status_content_container').show();
                $('#crawler_content_Container').hide();
                $('#loadingContainer').show();
                $('#cloneStatusButton').addClass('active-button');
                $('#crawlersStatusButton').addClass('passive-info');
                $.ajax({
                    url: 'filer_status.php',
                    method: 'GET',
                    success: function(response) {
                        $('#filter_status_content_container').html(response);
                        $('#cloneStatusButton').addClass('active-button');
                        $('#loadingContainer').hide();
                    },
                    error: function(xhr, status, error) {
                        console.error(error);
                    }
                });
            });

            $('#crawlersStatusButton').on('click', function() {
                $('#filter_status_content_container').hide();
                $('#clone_status_content_container').hide();
                $('#crawler_content_Container').show();
                $('#crawlersStatusButton').addClass('active-button');
                $('#cloneStatusButton').addClass('passive-info');
                cloneStatusButton.classList.remove('active-button');
                crawlersStatusButton.classList.remove('passive-info');
            });
        });

        function buttonstatusClicked(value) {
            console.log("Button clicked with value: " + value);
        }
        $('#download_data_crawler').on('click', function() {
            var tableRows = $('#dataTable tbody tr');
            var data = [];
            var headerRow = [];
            $('#dataTable thead th').each(function(index) {
                var headerItem = {
                    id: index,
                    v: $(this).text(),
                    s: {
                        font: {
                            bold: true,
                            color: {
                                rgb: "#000000"
                            },
                        },
                        fill: {
                            fgColor: {
                                rgb: "343a40"
                            }
                        },
                        border: {
                            bottom: {
                                style: 'thin',
                                color: {
                                    rgb: "000000"
                                }
                            }
                        },
                        alignment: {
                            horizontal: 'center'
                        }
                    }
                };
                headerRow.push(headerItem);
            });

            var filteredHeaderRow = headerRow.filter(hr => parseInt(hr.id) < 7);
            filteredHeaderRow.forEach(hr => {});
            data.push(filteredHeaderRow);
            tableRows.each(function(index, row) {
                var rowData = [];
                $(row).find('td').each(function(cellIndex, cell) {
                    var rowItem = {
                        id: index,
                        v: $(this).text(),
                    };
                    rowData.push(rowItem);
                });
                if (rowData.length !== 7) {
                    return;
                } else {
                    data.push(rowData);
                }

            });
            var ws = XLSX.utils.aoa_to_sheet(data);
            var wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            ws['!cols'] = [{
                width: 15
            }, {
                width: 20
            }, {
                width: 30
            }];
            var currentDate = new Date();
            var formattedDate = currentDate.toISOString().split('T')[0];
            XLSX.writeFile(wb, 'Crawler_Status_' + formattedDate + '.xlsx');
        });
    </script>

</body>

</html>