<?php
require_once('config.php');
require_once('connection.php');
require_once('connectionUI.php');
$db = new Connection();
$dbconn = new Config();
$dbui = new ConnectionUI();
$query = "SELECT
                users.username AS username,
                crawlers.title AS crawler_title,
                user_crawlers.*
                FROM
                user_crawlers
                JOIN
                users ON users.id = user_crawlers.user_id
                JOIN
                crawlers ON crawlers.id = user_crawlers.crawler_id
                WHERE
                user_crawlers.crawler_id = 4
                AND users.id IN (
                    SELECT id
                    FROM users
                    WHERE pid = 0 AND disabled = 0 AND id NOT IN (6, 118, 371, 150,1150)
                    AND users.username NOT LIKE '%DEMO%' AND users.username NOT LIKE '%TEST%'
                )";


$instance_query = "SELECT
            users.id AS user_id,
            users.username AS username,
            crawlers.id AS crawler_id,
            crawlers.title AS crawler_title,
            mysamm_8_crawling_instances.*,
            SUM(mysamm_8_crawling_instances.instance_limit)  AS total_urls,
            SUM(mysamm_8_crawling_instances.product_done) AS total_products,
            SUM(mysamm_8_crawling_instances.product_done) AS total_urls_crawled,
            SUM(mysamm_8_crawling_instances.instances) AS total_instances,
            MAX(mysamm_8_crawling_instances.instances) AS t_instance,
            SUM(CASE WHEN mysamm_8_crawling_instances.status = 'completed' THEN 1 ELSE 0 END) AS total_completed_instances,
            SUM(CASE WHEN mysamm_8_crawling_instances.status = 'running' THEN 1 ELSE 0 END) AS total_running_instances,
            SUM(CASE WHEN mysamm_8_crawling_instances.status = 'break' THEN 1 ELSE 0 END) AS total_break_instances,
            MAX(mysamm_8_crawling_instances.crawling_date) AS latest_crawl_start_date
            FROM
            mysamm_8_crawling_instances
            JOIN users ON users.id = mysamm_8_crawling_instances.user_id
            JOIN crawlers ON crawlers.id = mysamm_8_crawling_instances.crawler_id
            WHERE
            users.username NOT LIKE '%DEMO%'
            AND users.username NOT LIKE '%TEST%'
            GROUP BY
            users.id,
            users.username,
            crawlers.id,
            crawlers.title";

function generateStepButton($value, $websiteId, $client_id)
{
    if ($value === 'completed') {
        return "<button class='green-button' style='font-size: 12px;padding: 11px 10px;'type='submit' onclick='buttonstatusClicked(\"Completed\", \"$websiteId\", \"$client_id\")'>Ready To Manage</button>";
    } elseif ($value === 'running') {
        return "<button class='primary-button' style='font-size: 12px;padding: 8px 7px 9px;'type='submit'>Running</button>";
    } elseif ($value === 'pending') {
        return "<button class='mehroon-button' style='font-size: 12px;padding: 8px 7px 9px;'type='submit' onclick='buttonstatusClicked(\"Pending\", \"$websiteId\", \"$client_id\")'>Pending</button>";
    } elseif ($value === 'break') {
        return "<button class='red-button' style='background-color: red;color: white;padding: 11px 10px;border: none;border-radius: 4px;font-size: 12px;    padding: 8px 7px 9px;'type='submit' onclick='buttonbreakClicked(\"Break\", \"$websiteId\", \"$client_id\")'>Break/Resumed</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
                                    WHERE
                                    crawlers.id = 4
                                    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
                                        user_crawlers.crawler_id = 4
                                        AND pid = 0 AND disabled = 0 AND users.id NOT IN (6, 118, 371, 150,1150)
                                        AND users.username NOT LIKE '%DEMO%' AND users.username NOT LIKE '%TEST%'
                                        ORDER BY users.username ASC";
$user_name_result = $dbui->Query($user_name_query);
$instance_query_result = $dbconn->Query($instance_query);
$instance_total_urls_data = array();
$instance_instance_limit_data = array();
$instance_total_urls_crawled_data = array();
$instance_t_instance_data = array();
$instance_total_break_instances_data = array();
$instance_total_completed = array();
$crawler_date = array();
foreach ($instance_query_result as $status) {
    $key = $status['user_id'] . "**" . $status['crawler_id'];
    $instance_total_urls_data[$key] = $status['total_urls'];
    $instance_instance_limit_data[$key] = $status['instance_limit'];
    $instance_total_urls_crawled_data[$key] = $status['total_products'];
    $instance_t_instance_data[$key] = $status['t_instance'];
    $instance_total_break_instances_data[$key] = $status['total_break_instances'];
    $instance_total_completed[$key] = $status['total_completed_instances'];
    $instance_total_running[$key] = $status['total_running_instances'];
    $crawler_date[$key] = $status['crawling_date'];
}
$result = $db->Query($query);
?>
<html>

<head>
    <style>
        #dataTable td:nth-child(7),
        #dataTable td:nth-child(8),
        #dataTable td:nth-child(9) {
            border: 1px solid #ddd;
            padding: 8px;
            position: relative;
            transition: box-shadow 0.3s ease;
            box-shadow: inset 0 0 10px rgba(255, 127, 80, 0.5);
        }
    </style>
</head>

<body>
    <div id='crawler_content_Container'>
        <div class='' style="width:100%; justify-content: center; align-items: center;">
            <div class='row filter-container' style="width: 100%;">
                <div class='col-md-4'>
                    <label style='margin-left: -148px;margin-bottom: -137px;margin-top: -68px;'>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:134px;margin-left:-93px;margin-top:-71px;'>
                        <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: -182px; margin-bottom: -132px;margin-top:-68px'>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: -114px;margin-top: -71px;'>
                        <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: -171px; margin-bottom: -132px;margin-top:-68px'>Crawler 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:-57px;margin-top: -71px;'>
                        <option value='all'>All</option>
                        <option value='completed'>Ready to Manage</option>
                        <option value='running'>Running</option>
                        <option value='break'>Break</option>
                    </select>
                </div>
                <div class='col-md-4'>
                    <button class="primary-button" id="combined_break" style="width: 30%;margin-top: -77px;margin-bottom: -37px;margin-left: 951px;display:none">Break Action</button>
                </div>
            </div>
        </div>
        <div id='tableContainer' style="margin: -172px">
            <table id='dataTable' style='font-size: 12px;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 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;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">Client</th>
                        <th class='fixed-width' style='background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;'>Website</th>
                        <th class='fixed-width' style="background-color: #000;border: 2px solid white;font-size: medium;font-weight: bolder;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">Total Urls</th>
                        <th style="background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;">Prod. Inst.</th>
                        <th style="background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;">Urls Crawled</th>
                        <th style="background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">Total Inst</th>
                        <th class='fixed-width' style="background-color: #000;border: 2px solid white;font-size: medium;font-weight: bolder;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">Inst Comp.</th>
                        <th class='fixed-width' style="background-color: #000;border: 2px solid white;font-size: medium;font-weight: bolder;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">Inst Running</th>
                        <th class='fixed-width' style="background-color: #000;border: 2px solid white;font-size: medium;font-weight: bolder;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">Inst Break</th>
                        <th style="background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;width:84.2125px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">Crawl Date</th>
                        <th style="background-color: #000;font-size: medium;border: 2px solid white;font-weight: bolder;">Crawler Status</th>
                    </tr>
                </thead>
                <tbody style="color: black; text-align: center; font-family: Arial, sans-serif;">
                    <?php
                    $counter = 0;
                    $completedCount = 0;
                    $pendingCount = 0;
                    $breakCount = 0;
                    $runningCount = 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;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;'>" . $row['username'] . ' (' . $row['user_id'] . ')' . "</td>";
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;'>" . $row['crawler_title'] . "</td>";
                        $step1Value = $row['status'];
                        $status_key = $row['user_id'] . "**" . $row['crawler_id'];
                        $total_url__value = isset($instance_total_urls_data[$status_key]) ? $instance_total_urls_data[$status_key] : '<button class="mehroon-button" style="font-size: 12px;" type="submit">-</button>';
                        $instance_limit__value = isset($instance_instance_limit_data[$status_key]) ? $instance_instance_limit_data[$status_key] : '<button class="mehroon-button" style="font-size: 12px;" type="submit">-</button>';
                        $total_urls_crawled__value = isset($instance_total_urls_crawled_data[$status_key]) ? $instance_total_urls_crawled_data[$status_key] : '<button class="mehroon-button" style="font-size: 12px;" type="submit">-</button>';
                        $t_instance_value = isset($instance_t_instance_data[$status_key]) ? $instance_t_instance_data[$status_key] : '<button class="mehroon-button" style="font-size: 12px;" type="submit">-</button>';
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;'>" . $total_url__value . "</td>";
                        echo "<td class=''style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'>" . $instance_limit__value . "</td>";
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'>" . $total_urls_crawled__value . "</td>";
                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'>" . $t_instance_value . "</td>";
                        $total_break_values = isset($instance_total_break_instances_data[$status_key]) ?
                            $instance_total_break_instances_data[$status_key] :
                            '0';
                        $total_break_values = isset($instance_total_break_instances_data[$status_key]) ?
                            $instance_total_break_instances_data[$status_key] : '0';
                        $total_completed_values = isset($instance_total_completed[$status_key]) ?
                            $instance_total_completed[$status_key] : '0';
                        $total_running_values = isset($instance_total_running[$status_key]) ?
                            $instance_total_running[$status_key] : '0';
                        $crawling_date = isset($crawler_date[$status_key]) ?
                            $formattedDate = date("d-m-Y", strtotime($crawler_date[$status_key])) : '<button class="mehroon-button" style="font-size: 12px;" type="submit">-</button>';
                        if ($t_instance_value === '<button class="mehroon-button" style="font-size: 12px;" type="submit">-</button>') {
                            $action_button = '<button class="mehroon-button" style="font-size: 12px;" type="submit">-</button>';
                            $step1Value_1 = '<button class="mehroon-button" style="font-size: 12px;" type="submit">-</button>';
                        } else {
                            $action_button = ($total_break_values > 0) ?
                                "<button class='mehroon-button' style='font-size: 12px; padding: 8px 7px 9px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;' type='button' onclick='buttonbreakClicked(\"{$row['crawler_id']}\", \"{$row['user_id']}\")'>Resume Crawler for broken instances</button>" :
                                "<button class='Teal-button' style='font-size: 12px; padding: 8px 7px 9px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;' type='button'>Active</button>";
                        }
                        if ($total_completed_values > 0) {
                            if ($total_completed_values === $t_instance_value) {
                                $row['status'] = 'completed';
                                $step1Value_1 = $row['status'];
                            }
                            $row['status'] = 'completed';
                            echo "<td class='instanceof' style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'><button class='modal-button transparent-button' onclick='openModal(\"{$row['crawler_id']}\", \"{$row['user_id']}\", \"{$row['status']}\")'>" . $instance_total_completed[$status_key] . "</button></td>";
                        } else {

                            echo "<td style='text-align:center;border:1px solid black;box-shadow:none'>0</td>";
                        }

                        if ($total_running_values > 0) {
                            $row['status'] = 'running';
                            $step1Value_1 = $row['status'];
                            echo "<td class='instanceof' style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'><button class='modal-button transparent-button' onclick='openModal(\"{$row['crawler_id']}\", \"{$row['user_id']}\", \"{$row['status']}\")'>"  . $instance_total_running[$status_key] . "</button></td>";
                        } else {
                            echo "<td style='text-align:center; border:1px solid black;box-shadow:none'>0</td>";
                        }

                        if ($total_break_values > 0) {
                            $row['status'] = 'break';
                            $step1Value_1 = $row['status'];
                            echo "<td class='instanceof' style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;'><button class='modal-button transparent-button' onclick='openModal(\"{$row['crawler_id']}\", \"{$row['user_id']}\", \"{$row['status']}\")'>"  . $total_break_values . "</button></td>";
                        } else {
                            echo "<td style='text-align:center;border:1px solid black;box-shadow:none'>0</td>";
                        }

                        echo "<td style='border: 1px solid black;font-family:Helvetica;font-size: 14px;line-height: 0.5;color: #545454;text-align: center;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;'>"  . $crawling_date . "</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_1, $row['crawler_id'], $row['user_id']) . "</td>";
                        echo "</tr>";
                        $counter++;
                    }
                    ?>
                </tbody>
            </table>
            <a href="#" class="top">Back to Top &#8593;</a>
        </div>
    </div>
    <div id='myModal' class='modal'>
        <div class='modal-content'>
            <span class='close' onclick='closeModal()'>&times;</span>
            <p id='modalContent'></p>
            <table id="new_table_datatable">
                <thead>
                    <th>Username</th>
                    <th>Website</th>
                    <th>Instance </th>
                    <th>Status</th>
                </thead>
                <tbody>
                    <td id="username"></td>
                    <td id="title"></td>
                    <td id="instances"></td>
                    <td id="status"></td>

                </tbody>
            </table>
        </div>
    </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) {
                    if (typeof response === 'object' && response.data) {
                        var data = response.data;

                        dataTable = $('#dataTable').DataTable({
                            columns: columns,
                            data: data,
                            deferLoading: 57
                        });
                    } 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'
                },
                {
                    data: '7'
                },
                {
                    data: '8'
                },
                {
                    data: '9'
                },

                {
                    data: '10',
                },
            ];

            var dataTable = $('#dataTable').DataTable({
                pageLength: 100,
                searching: false,
                lengthChange: false,
            });

            function generatetd(row, data, dataIndex) {
                if (parseFloat(data[6]) > 0) {
                    applyCellStyle(row, 6);
                }
                if (parseFloat(data[7]) > 0) {
                    applyCellStyle(row, 7);
                }
                if (parseFloat(data[8]) > 0) {
                    applyCellStyle(row, 8);
                }
            }

            function applyCellStyle(row, columnIndex) {
                $('td', row).eq(columnIndex).css({
                    'border': '1px solid #ddd',
                    'padding': '8px',
                    'position': 'relative',
                    'transition': 'box-shadow 0.3s ease',
                    'box-shadow': 'inset 0 0 10px rgba(255, 127, 80, 0.5)'
                });
            }

            // 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();
            //             // console.log('Before DataTable destroy');
            //             if (dataTable) {
            //                 dataTable.clear().destroy();
            //             }
            //             // console.log('After DataTable destroy');

            //             dataTable = $('#dataTable').DataTable({
            //                 pageLength: 100,
            //                 lengthChange: false,
            //                 columns: columns,
            //                 deferLoading: 57,
            //                 searching: false,
            //                 data: response.data,

            //             });
            //             // console.log('After DataTable initialization');

            //         },
            //         error: function() {
            //             $('#loadingContainer').hide();
            //         }
            //     });
            // }
            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();

                        // Destroy DataTable if it exists
                        if (dataTable) {
                            dataTable.clear().destroy();
                        }

                        // Initialize DataTable with new data
                        dataTable = $('#dataTable').DataTable({
                            pageLength: 100,
                            lengthChange: false,
                            columns: columns,
                            deferLoading: 57,
                            searching: false,
                            data: response.data,

                            // Callback after each draw event
                            drawCallback: function() {
                                // Remove existing styles from specified cells
                                dataTable.cells().nodes().to$().filter(':nth-child(7), :nth-child(8), :nth-child(9)').css({
                                    'border': '1px solid #ddd',
                                    'padding': '8px',
                                    'position': 'relative',
                                    'transition': 'box-shadow 0.3s ease',
                                    'box-shadow': 'inset 0 0 10px rgba(255, 127, 80, 0.5)'
                                });

                                // Add conditional styling for cells with value 0
                                dataTable.cells().every(function() {
                                    var cellData = this.data();
                                    if (cellData === '0') {
                                        $(this.node()).css({
                                            'border': '1px solid black',
                                            'box-shadow': 'none',
                                            'transition': 'none'
                                        });
                                    }
                                });
                            }
                        });
                    },
                    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 tableData = [];
            var headerRow = [];
            $('#dataTable thead th').each(function() {
                headerRow.push($(this).text());
            });
            tableData.push(headerRow);

            $('#dataTable tbody tr').each(function(index, row) {
                var rowData = [];
                $(row).find('td').each(function(cellIndex, cell) {
                    rowData.push($(cell).text());
                });
                tableData.push(rowData);
            });
            $.ajax({
                type: 'POST',
                url: 'code.php',
                data: {
                    CtableData: JSON.stringify(tableData)
                },
                success: function(response) {
                    console.log('Download Successfully');
                    console.log(console);
                },
                error: function(error) {
                    console.error(error);
                }
            });

        });

        // function buttonbreakClicked(value, breakcrawlerId, breakuserId) {
        //     console.log("Button clicked with crawler_id: " + breakcrawlerId + " and user_id: " + breakuserId);
        //     $.ajax({
        //         url: 'code.php',
        //         method: 'GET',
        //         data: {
        //             breakcrawlerId: breakcrawlerId,
        //             breakuserId: breakuserId,
        //         },
        //         success: function(response) {
        //             var responseData = JSON.parse(response);
        //             if (responseData.success) {
        //                 alert(responseData.success);
        //                 var dataTable = $('#DataTable').DataTable();
        //                 dataTable.clear().draw();
        //                 dataTable.ajax.reload();
        //             }
        //         },
        //     });
        // }
        function buttonbreakClicked(value, breakcrawlerId, breakuserId) {
            console.log("Button clicked with crawler_id: " + breakcrawlerId + " and user_id: " + breakuserId);
            $.ajax({
                url: 'code.php',
                method: 'GET',
                data: {
                    breakcrawlerId: breakcrawlerId,
                    breakuserId: breakuserId,
                    value: value // Pass the 'value' parameter to the data object
                },
                success: function(response) {
                    var responseData = JSON.parse(response);
                    if (responseData.success) {
                        alert(responseData.success);
                        var dataTable = $('#DataTable').DataTable();
                        dataTable.clear().draw();

                        if (dataTable) {
                            dataTable.clear().destroy();
                        }

                        // Initialize DataTable with new data
                        dataTable = $('#dataTable').DataTable({
                            pageLength: 100,
                            lengthChange: false,
                            columns: columns,
                            deferLoading: 57,
                            searching: false,
                            data: response.data,

                            // Callback after each draw event
                            drawCallback: function() {
                                // Remove existing styles from specified cells
                                dataTable.cells().nodes().to$().filter(':nth-child(7), :nth-child(8), :nth-child(9)').css({
                                    'border': '1px solid #ddd',
                                    'padding': '8px',
                                    'position': 'relative',
                                    'transition': 'box-shadow 0.3s ease',
                                    'box-shadow': 'inset 0 0 10px rgba(255, 127, 80, 0.5)'
                                });

                                // Add conditional styling for cells with value 0
                                dataTable.cells().every(function() {
                                    var cellData = this.data();
                                    if (cellData === '0') {
                                        $(this.node()).css({
                                            'border': '1px solid black',
                                            'box-shadow': 'none',
                                            'transition': 'none'
                                        });
                                    }
                                });
                            }
                        });
                    
                    }
                },
            });
        }


        function openModal(crawlerId, userId, crawler_status) {
            $.ajax({
                url: 'code.php',
                method: 'GET',
                data: {
                    crawlerId: crawlerId,
                    userId: userId,
                    crawler_status: crawler_status
                },
                success: function(response) {
                    var responseData = JSON.parse(response);
                    var modalTbody = document.getElementById('new_table_datatable').getElementsByTagName('tbody')[0];
                    modalTbody.innerHTML = '';
                    for (var i = 0; i < responseData.length; i++) {
                        var row = responseData[i];
                        var username = row[0];
                        var title = row[1];
                        var instances = row[2];
                        var status = row[3];
                        var newRow = modalTbody.insertRow();
                        var cell1 = newRow.insertCell(0);
                        var cell2 = newRow.insertCell(1);
                        var cell3 = newRow.insertCell(2);
                        var cell4 = newRow.insertCell(3);
                        cell1.innerHTML = username;
                        cell2.innerHTML = title;
                        cell3.innerHTML = instances;
                        cell4.innerHTML = status;
                    }
                    document.getElementById('myModal').style.display = 'block';
                },
                error: function() {
                    hideLoader();
                }
            });
        }

        function closeModal() {
            document.getElementById('myModal').style.display = 'none';
        }


        document.getElementById('searchByStatus').addEventListener('change', function() {
            var breakButton = document.getElementById('combined_break');
            if (this.value === 'break') {
                breakButton.style.display = 'block';
            } else {
                breakButton.style.display = 'none';
            }
        });

        $('#combined_break').click(function() {
            var allRowsData = [];
            var firstRowData = []
            $('#dataTable tbody tr:contains("Break/Resumed")').each(function(index, row) {
                var rowData = {
                    firstRowData: [
                        $(row).find('td').eq(0).text(),
                    ],
                };
                allRowsData.push(rowData);
            });

            console.log(allRowsData);
            $.ajax({
                type: 'GET',
                url: 'code.php',
                contentType: 'application/json',
                data: {
                    allRowsData: allRowsData
                },
                success: function(response) {
                    alert(responseData.success);
                    console.log('Rows updated successfully');
                },
                error: function(error) {
                    console.error('Error updating rows');
                }
            });
        });

        /*function runCodeIfScheduled() {
            var currentHour = new Date().getHours();
            var currentMinute = new Date().getMinutes();

            if ((currentHour === 10 && currentMinute === 0) || (currentHour === 18 && currentMinute === 30)) {
                var tableData = [];
                var headerRow = [];
                console.log('time : ' + currentHour);
                $('#dataTable thead th').each(function() {
                    headerRow.push($(this).text());
                });

                tableData.push(headerRow);

                $('#dataTable tbody tr').each(function(index, row) {
                    var rowData = [];
                    $(row).find('td').each(function(cellIndex, cell) {
                        rowData.push($(cell).text());
                    });
                    tableData.push(rowData);
                });

                $.ajax({
                    type: 'POST',
                    url: 'code.php',
                    data: {
                        CtableData: JSON.stringify(tableData)
                    },
                    success: function(response) {
                        console.log('Download Successfully');
                    },
                    error: function(error) {
                        console.error('Error:', error);
                    }
                });
            } else {
                console.log('Not the scheduled time. Skipping the execution.');
            }
        }*/

        // setInterval(runCodeIfScheduled, 60000);
    </script>


</body>

</html>