<?php
$title = 'List Validation';

include '../templates/backend/members/header.php';
global $deltaLatch, $deltaChatter;
$guardMessage = !empty($deltaChatter) ? $deltaChatter : (isset($_SESSION['evp_gate_msg']) ? $_SESSION['evp_gate_msg'] : __('License not active'));

$user_id = $_SESSION['id'];
$credit_payment = 0;
$cost_per_scan = 0;
$wallet_system = 'false';
$ext_server = 'false';

if (isset($option_name)) {
    if (isset($option_name['credit_payment'])) {
        $credit_payment = $option_name['credit_payment'];
    }
    if (isset($option_name['cost_per_scan'])) {
        $cost_per_scan = $option_name['cost_per_scan'];
    }
    if (isset($option_name['wallet_system'])) {
        $wallet_system = $option_name['wallet_system'];
    }
    if (isset($option_name['ext_server'])) {
        $ext_server = $option_name['ext_server'];
    }
}

if (!empty($cc_data)) {
    function cdata1($cc_data)
    {
        $data = '';
        foreach ($cc_data as $val) {
            $data .= "var $val = 0;" . PHP_EOL;
        }
        return $data;
    }
    function cdata2($cc_data)
    {
        $data = '';
        foreach ($cc_data as $val) {
            $data .= "$val = column_data.$val;" . PHP_EOL;
        }
        return $data;
    }
    function cdata3($cc_data)
    {
        $data = '';
        foreach ($cc_data as $val) {
            $data .= "$val:$val," . PHP_EOL;
        }
        return $data;
    }
    $cdata1 = cdata1($cc_data);
    $cdata2 = cdata2($cc_data);
    $cdata3 = cdata3($cc_data);
} else {
    $cdata1 = '';
    $cdata2 = '';
    $cdata3 = '';
}

?>

<!-- Page Heading -->
<div class="container-fluid">
    <div class="page-header">
        <div class="pull-right">
            <?php if (!empty($deltaLatch)) { ?>
                <a href="#" id="add_list" data-toggle="modal" data-target="#addList"
                    class="d-sm-inline-block btn btn-sm btn-primary shadow-sm"><?php _e('Add List'); ?></a>
            <?php } else { ?>
                <button disabled
                    class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><?php _e('Add List'); ?></button>
            <?php } ?>
        </div>
        <div class="row">
            <div class="col-md-6 col-sm-12">
                <div class="title">
                    <h4><?php _e($title); ?></h4>
                </div>
                <nav aria-label="breadcrumb" role="navigation">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="index.php"><?php _e('Dashboard'); ?></a></li>
                        <li class="breadcrumb-item active" aria-current="page"><?php _e($title); ?></li>
                    </ol>
                </nav>
            </div>
        </div>
    </div>

    <!-- Content Row -->
    <div class="row" id="list-container">
        <?php

        $email_info = "SELECT csv_file_name FROM evp_email_list_metadata WHERE user_id = '$user_id' GROUP BY csv_file_name ORDER BY csv_file_name DESC ";

        $info = $db->select($email_info);

        $i = $c = 0;

        while ($result = $info->fetch_assoc()) {

            $csv_file_name = $result['csv_file_name'];
            $csv_file_name_escaped = $db->link->real_escape_string($csv_file_name);

            // Check if there is a task for this CSV
            $task_check_status = false;

            $task_check_sql = "SELECT * FROM evp_task WHERE csv_name = '$csv_file_name_escaped' ";

            $task_check_read = $db->select($task_check_sql);

            $task_count_check = ($task_check_read) ? mysqli_num_rows($task_check_read) : 0;

            if ($task_count_check > 0)
                $task_check_status = true;
            $c++;

            $csv_file_info = "SELECT * FROM evp_email_list_metadata e_mdata
                                    LEFT JOIN evp_task e_task
                                    ON e_mdata.csv_file_name=e_task.csv_name
                                WHERE e_mdata.csv_file_name = '$csv_file_name_escaped' AND e_mdata.user_id = '$user_id'";

            $csv_info = $db->select($csv_file_info);

            $csv_result = $csv_info->fetch_assoc();

            $csv_display_name = !empty($csv_result['csv_new_name']) ? $csv_result['csv_new_name'] : $csv_file_name;

            $create_time = $csv_result['creation_date'];

            $completed_time = $csv_result['completed_date'];

            $count_valid = $csv_result['valid'];

            $count_invalid = $csv_result['invalid'];

            $count_catchall = $csv_result['catch_all'];

            $count_unknown = $csv_result['unknown'];

            $count_skipped = $csv_result['skipped'];

            $scan_status = $csv_result['scan_status'];

            $count_free = $csv_result['free_account'];

            $count_role = $csv_result['role_account'];

            $count_disposable = $csv_result['disposable'];

            $count_syntax = $csv_result['syntax_error'];

            $total_verify = $count_valid + $count_invalid + $count_catchall + $count_unknown + $count_skipped;

            $total_email = $csv_result['total'];

            $task_status = $csv_result['status'];

            $check_inbox = $csv_result['check_mailbox'];

            $count_not_verify = $total_email - $total_verify;

            $csv_name_ex = preg_replace('/\\.[^.\\s]{3,4}$/', '', $csv_file_name);

            $verify_per_status = 0;
            if ($total_email > 0) {
                $verify_per_status = ceil((($total_verify) / $total_email) * 100);
            }

            $sql_user_list_valid = "SELECT COUNT(*) as count FROM evp_email_list elist
                                    INNER JOIN evp_email_list_metadata e_meta
                                        ON e_meta.csv_file_name = elist.csv_file_name
                                        WHERE elist.csv_file_name = '$csv_file_name_escaped' AND
                                            elist.user_id = '$user_id' AND
                                            e_meta.scan_status = 'completed'";

            $sql_user_list_read = $db->select($sql_user_list_valid);

            $sql_user_list_chk = 0;
            if ($sql_user_list_read) {
                $row_count = $sql_user_list_read->fetch_assoc();
                $sql_user_list_chk = $row_count['count'];
            }
            ?>

            <div class="col-md-4 mb-4 scan_list" id="mega_bar_<?php echo $csv_name_ex; ?>">
                <div class="card">
                    <div class="card-body">
                        <div class="header-row d-flex justify-content-between align-items-center">
                            <h6 class="font-weight-bold text-primary mb-0">
                                <?php _e('File'); ?>: <span id="filename"><?php echo $csv_display_name; ?></span>
                            </h6>
                            <div class="action-menu">
                                <button type="button" class="btn btn-light dropdown-toggle d-md-none" data-toggle="modal"
                                    data-target="#actionModal">
                                    <i class="icon-copy dw dw-menu-2"></i>
                                </button>
                                <button type="button"
                                    class="btn btn-light dropdown-toggle d-none d-md-inline dropdown-toggle-btn">
                                    <i class="icon-copy dw dw-menu-2"></i>
                                </button>
                                <div class="dropdown-menu dropdown-menu-right">
                                    <a class="dropdown-item" href="#" data-toggle="modal"
                                        data-target="#model_<?php echo $csv_name_ex; ?>">
                                        <i class="icon-copy dw dw-file-37"></i> <?php _e('Download'); ?>
                                    </a>
                                    <a class="dropdown-item btn export-pdf-btn" href="#"
                                        data-csv-file-name="<?php echo $csv_file_name; ?>"
                                        data-total="<?php echo $total_email; ?>" data-valid="<?php echo $count_valid; ?>"
                                        data-invalid="<?php echo $count_invalid; ?>"
                                        data-catchall="<?php echo $count_catchall; ?>"
                                        data-unknown="<?php echo $count_unknown; ?>"
                                        data-skipped="<?php echo $count_skipped; ?>"
                                        data-syntax-error="<?php echo $count_syntax; ?>"
                                        data-disposable="<?php echo $count_disposable; ?>"
                                        data-free-account="<?php echo $count_free; ?>"
                                        data-role-account="<?php echo $count_role; ?>"
                                        data-completed-time="<?php echo $completed_time; ?>"
                                        data-site-title="<?php echo $site_title; ?>" data-s-url="<?php echo $s_url; ?>">
                                        <i class="icon-copy dw dw-file"></i> Export PDF
                                    </a>
                                    <a class="dropdown-item" href="#" data-toggle="modal"
                                        data-target="#model_assign_<?php echo $csv_name_ex; ?>">
                                        <i class="icon-copy dw dw-list"></i> Assign Tag
                                    </a>
                                    <a class="dropdown-item file_delete_btn btn btn-warning" href="#" data-toggle="modal"
                                        data-target="<?php echo $csv_name_ex; ?>">
                                        <i class="icon-copy dw dw-delete-3"></i> Remove
                                    </a>
                                </div>
                            </div>
                        </div>

                        <p class="mt-1 mb-0 small text-muted font-italic">
                            <span class="font-weight-medium">CSV. Ref:</span>
                            <?php echo htmlspecialchars($csv_file_name); ?>
                        </p>

                        <p class="text-muted mb-2 mt-2"><?php _e('Created'); ?>: <?php echo $create_time ?></p>

                        <?php $check_tags = $db->select("SELECT * FROM evp_tag_list WHERE target_csv_name = '" . $csv_file_name_escaped . "' and user_id = '" . $user_id . "'");
                        if (!$check_tags || !mysqli_num_rows($check_tags)):
                        else:
                            ?>
                            <div class="assigned_tag"><span class="title"><?php _e('Assigned Tag'); ?>:</span>
                                <?php
                                while ($tags = mysqli_fetch_array($check_tags)):
                                    $tag = $tags['list_name'];
                                    echo "<span class='tags'>" . $tag . "</span>";
                                    //	echo "<input type='text' name='tag_name' hidden value=".$tag.">";
                                endwhile;
                                ?>
                            </div>
                        <?php endif; ?>



                        <div class="action-row mt-3">
                            <div class="progress-bar-container mb-3">
                                <div class="progress-bar-wrapper">
                                    <div class="progress-bar <?php echo ($scan_status === 'processing' && $verify_per_status < 100) ? 'animated' : 'no-animation'; ?>"
                                        id="progress-bar_<?php echo $csv_name_ex; ?>" role="progressbar"
                                        style="width: <?php echo $verify_per_status; ?>%;"
                                        aria-valuenow="<?php echo $verify_per_status; ?>" aria-valuemin="0"
                                        aria-valuemax="100">
                                    </div>
                                    <div class="progress-bar-label">
                                        <?php echo $verify_per_status; ?>
                                        %
                                    </div>
                                </div>
                            </div>

                            <style>
                                /* Center the label inside the progress bar */
                                .progress-bar-wrapper {
                                    position: relative;
                                    width: 100%;
                                    height: 100%;
                                }

                                .progress-bar-label {
                                    position: absolute;
                                    top: 50%;
                                    left: 50%;
                                    transform: translate(-50%, -50%);
                                    color: #fff;
                                    font-weight: bold;
                                    z-index: 1;
                                    pointer-events: none;
                                    /* Prevent interaction with the label */
                                }

                                .progress-bar {
                                    height: 100%;
                                    position: relative;
                                    z-index: 0;
                                    /* Ensure the label is above the progress bar */
                                }
                            </style>

                            <?php if ($verify_per_status < 100 && $verify_per_status != 0) {
                                // Only start live updates if there is an active scanning task
                                $task_status_c = $db->select("SELECT * FROM evp_task WHERE csv_name = '$csv_file_name' AND user_id = '$user_id' AND status = 'scanning'");

                                if (mysqli_num_rows($task_status_c) > 0) {
                                    $log->system_debug("Active scanning task found for CSV: $csv_file_name, User: $user_id");
                                    ?>
                                    <!-- Per-CSV polling script removed: now handled by batch polling only. -->
                                <?php }
                            } // End if $verify_per_status check ?>

                            <div class="action-buttons d-flex flex-wrap gap-2">

                                <div class="email_amnt" id="email_amnt_<?php echo $csv_name_ex; ?>">
                                    <?php echo $total_verify . '/' . $total_email; ?>
                                </div>
                                <span class="countdown-timer"
                                    style="margin-left:8px;color:#007bff;font-weight:bold;display:none;">(60)</span>

                                <div style="display: flex; gap: 5px;">

                                    <button class="btn btn-info btn-details" data-toggle="modal"
                                        data-target="#detailsModal">
                                        <i class="icon-copy dw dw-pie-chart"></i> Details
                                    </button>

                                    <?php

                                    if (($count_not_verify != 0) || ($task_status == 'retry_emailsend')) {

                                        if ($task_check_status && ($task_status != 'completed')) { ?>
                                            <button style="display:none;" id="verify_<?php echo $csv_name_ex; ?>"
                                                class="btn btn-success btn-verify" data-target='<?php echo $csv_file_name; ?>'>
                                                <i class="icon-copy dw dw-magnifying-glass"></i> <?php _e('Verify'); ?>
                                            </button>

                                            <?php if ($scan_status === 'processing') { ?>
                                                <button style="display:block;" class="btn btn-danger btn-sm task-cancel-btn"
                                                    data-target='<?php echo $csv_file_name; ?>' id="cancel_<?php echo $csv_name_ex; ?>"
                                                    name="button">
                                                    <i class="spinner-border spinner-border-sm" role="status"></i>
                                                </button>
                                            <?php } ?>

                                        <?php } elseif (($credit_payment >= $cost_per_scan) || ($wallet_system !== 'true')) { ?>
                                            <button class="btn btn-success btn-verify" data-target='<?php echo $csv_file_name; ?>'
                                                id="verify_<?php echo $csv_name_ex; ?>">
                                                <i class="icon-copy dw dw-magnifying-glass"></i> <?php _e('Verify'); ?>
                                            </button>

                                            <button class="btn btn-danger btn-sm task-cancel-btn"
                                                data-target='<?php echo $csv_file_name; ?>' id="cancel_<?php echo $csv_name_ex; ?>"
                                                name="button">
                                                <i class="spinner-border spinner-border-sm" role="status"></i>
                                            </button>

                                        <?php } elseif (($credit_payment < $cost_per_scan) || ($wallet_system === 'true')) { ?>

                                            <div class="verify_email">

                                                <a href="../members/store.php" title="<?php _e('Buy Credits'); ?>!"
                                                    class="btn btn-danger btn-icon-split  text-white"><i
                                                        class="icon-copy dw dw-money-2"></i></a>
                                            </div>

                                        <?php } ?>

                                    <?php } elseif (($count_not_verify == 0) && ($task_check_status) && ($scan_status == 'processing')) { ?>

                                        <div class="spinner-border text-info" role="status">
                                            <span class="sr-only"><?php _e('Loading'); ?>...</span>
                                        </div>

                                    <?php } elseif (($task_check_status) && ($task_status == 'importing')) { ?>

                                        <div class="spinner-border text-info" role="status">
                                            <span class="sr-only"><?php _e('Loading'); ?>...</span>
                                        </div>

                                    <?php } ?>




                                    <?php if ($sql_user_list_chk > 0):
                                        if ($check_inbox == 'true'):
                                            $diff_time = 0;
                                            $time_now = time();
                                            $unblock_check = !empty($completed_time) ? strtotime($completed_time) + 300 : 0;
                                            $diff_time = floor(($unblock_check - $time_now) / 60);
                                            $disabled = 'true';
                                            if ($time_now > ($unblock_check)) {
                                                $disabled = 'false';
                                            }
                                            ?>
                                            <button class="btn btn-success check_inbox" type="button"
                                                title="<?php _e('Validate Mailbox'); ?>"
                                                data-target="<?php echo $csv_file_name; ?>">
                                                <i class="icon-copy dw dw-email2"></i>
                                                <input type="hidden" data-status="<?php echo $disabled ?>"
                                                    data-wtime="<?php echo $diff_time; ?>" value="email_check" />
                                            </button>
                                        <?php endif; ?>


                                    <?php endif; ?>

                                </div>


                            </div>

                            <?php if (isset($chart_display) && $chart_display): ?>
                                <div class="verify-chart mt-3">
                                    <div class="chart-pie pt-4 pb-2">
                                        <canvas id='myChart_<?php echo $csv_name_ex; ?>'></canvas>
                                        <canvas id='new_myChart_<?php echo $csv_name_ex; ?>' style="display:none;"></canvas>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>


            </div>

            <!-- Modals specific to this scan_list -->
            <div class="csv_assign modal fade" id="model_assign_<?php echo $csv_name_ex; ?>" tabindex="-1" role="dialog"
                aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel"><?php _e('Assign A Tag'); ?></h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <form id="tag_maker" action="#" method="post">
                            <input type="text" name="filename" hidden value="<?php echo $csv_file_name; ?>">
                            <input type="text" name="user_id" hidden value="<?php echo $user_id; ?>">



                            <div class="modal-body row">
                                <div class="col-sm-12">
                                    <div class="form-group">

                                        <div id="new_list"><a href="/#" class="news_list_btn"
                                                data-dismiss="modal"><?php _e('Create a New Tag?'); ?></a></div>

                                        <p><?php _e('or select an existing tag'); ?>
                                        <p>

                                            <select class="selectpicker pre_tags" data-live-search="true">
                                                <option disabled selected value style="display:none;">
                                                    <?php _e('Select Tag'); ?>
                                                </option>
                                                <?php $check_tags = $db->select("SELECT DISTINCT list_name FROM evp_tag_list WHERE user_id = '" . $user_id . "'");
                                                while ($tags = mysqli_fetch_array($check_tags)):
                                                    $tag = $tags['list_name'];
                                                    ?>
                                                    <option data-tokens="<?php echo $tag; ?>"><?php echo $tag; ?></option>
                                                <?php endwhile; ?>
                                            </select>

                                            <script>                                             (function ($) { "use strict"; $(document).on('click', "#tag_maker .news_list_btn", function (event) { event.preventDefault(); var csvName = $(this).closest("#tag_maker").find("input[name='filename']").val(); var userId = $(this).closest("#tag_maker").find("input[name='user_id']").val(); Swal.fire({ title: "<?php _e('Tag Name'); ?>", html: "<?php _e('type in a new tag name'); ?>", input: 'text', showCancelButton: true, confirmButtonText: '<?php _e('Add'); ?>', showLoaderOnConfirm: true, heightAuto: false, preConfirm: function (text) { return new Promise(function (resolve) { setTimeout(function () { $.ajax({ url: "../functions/tag_func.php", type: 'POST', data: { target_csv_name: csvName, user_id: userId, list_name: text }, dataType: "json" }).done(function () { Swal.fire({ title: "<?php _e('Complete'); ?>", showConfirmButton: true, type: "success", html: '<?php _e('Scanned list added into newly created tag'); ?>', heightAuto: false }).then(function () { location.reload(); }); }).fail(function () { Swal.fire("<?php _e('Error'); ?>", "<?php _e('Cannot add blank name!'); ?>", 'error'); }); }, 1000); }); } }); }); })(jQuery);
                                            </script>

                                    </div>
                                </div>
                            </div>

                            <div class="modal-footer">
                                <button id="assign_tag" name="assign_tag" type="submit" class="btn btn-primary"
                                    disabled><?php _e('Assign Tag'); ?></button>
                                <button id="clear_tag" name="clear_tag" type="button"
                                    class="btn btn-dark"><?php _e('Clear Tag'); ?></button>
                                <button type="button" class="btn btn-secondary"
                                    data-dismiss="modal"><?php _e('Close'); ?></button>
                            </div>
                            <script>                             (function ($) {
                                    "use strict"; $(document).on('change', '#tag_maker select.pre_tags', function () { var selectedTag = this.value; $(this).closest("#tag_maker").find('#assign_tag').prop("disabled", false); });
                                    $(document).on('click', "#tag_maker #assign_tag", function (event) { event.preventDefault(); var formContext = $(this).closest("#tag_maker"); var csvName = formContext.find("input[name='filename']").val(); var userId = formContext.find("input[name='user_id']").val(); var selectedTag = formContext.find('select.pre_tags').val(); Swal.fire({ title: "<?php _e('Are you sure?'); ?>", html: "<?php _e('You are applying'); ?> <span style='color:red;'>" + selectedTag + "</span> <?php _e('tag for scanned'); ?> <span style='color:red;'>" + csvName + "</span>", showCancelButton: true, confirmButtonText: '<?php _e('Yes, I confirm!'); ?>', showLoaderOnConfirm: true, heightAuto: false, preConfirm: function () { return new Promise(function (resolve) { setTimeout(function () { $.ajax({ url: "../functions/tag_func.php", type: 'POST', data: { target_csv_name: csvName, user_id: userId, selected_tag_name: selectedTag }, dataType: "json" }).done(function () { Swal.fire({ title: "<?php _e('Complete'); ?>", showConfirmButton: true, heightAuto: false, type: "success", html: '<?php _e('Scanned list'); ?> <span style=color:red;>' + csvName + '</span> <?php _e('assigned in'); ?> <span style=color:red;>' + selectedTag + '</span> <?php _e('tag'); ?>' }).then(function () { location.reload(); }); }).fail(function () { Swal.fire("<?php _e('Error'); ?>", "<?php _e('Unable to assign on selected tag!'); ?>", 'error'); }); }, 1000); }); } }); });
                                    $(document).on('click', "#tag_maker #clear_tag", function (event) { event.preventDefault(); var formContext = $(this).closest("#tag_maker"); var csvName = formContext.find("input[name='filename']").val(); var userId = formContext.find("input[name='user_id']").val(); var tag = $('#mega_bar_' + csvName).find("span.tags").text(); Swal.fire({ title: "Are you sure?", html: "You want to remove <span style='color:red;'>" + tag + "</span> tag for scanned <span style='color:red;'>" + csvName + "</span>", showCancelButton: true, confirmButtonText: 'Yes, I confirm!', showLoaderOnConfirm: true, heightAuto: false, preConfirm: function () { return new Promise(function (resolve) { setTimeout(function () { $.ajax({ url: "../functions/tag_func.php", type: 'POST', data: { target_csv_name: csvName, user_id: userId, clear_tag: tag }, dataType: "json" }).done(function () { Swal.fire({ title: "Complete", showConfirmButton: true, heightAuto: false, type: "success", html: 'Scanned list <span style=color:red;>' + csvName + '</span> Unassigned from <span style=color:red;>' + tag + '</span> tag' }).then(function () { location.reload(); }); }).fail(function () { Swal.fire("Error", "Unable to clear from selected tag!", 'error'); }); }, 1000); }); } }); });
                                })(jQuery);
                            </script>

                        </form>
                    </div>

                </div>
            </div>




            <!-- Download Modal -->
            <div class="csv_download modal fade" id="model_<?php echo $csv_name_ex; ?>" tabindex="-1" role="dialog"
                aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel"><?php _e('CSV Download'); ?></h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <form action="../functions/<?php echo $download_file_func; ?>" method="post">
                            <input type="text" name="filename" hidden value="<?php echo $csv_file_name; ?>">
                            <input type="text" name="user_id" hidden value="<?php echo $user_id; ?>">
                            <div class="modal-body row">
                                <div class="col-sm-6">
                                    <div class="form-group form-check">
                                        <input type="checkbox" name="all"
                                            class="form-check-input check_all_<?php echo $i ?>" value="all" checked
                                            onchange="allChange<?php echo $i; ?>(this)" id="checkbox_<?php echo $c; ?>"
                                            <?php if ($total_email == 0) {
                                                echo 'disabled';
                                            } ?>>
                                        <label class="form-check-label" for="checkbox_<?php echo $c; ?>"><?php _e('ALL'); ?>
                                            <span class="badge badge-primary"><?php echo $total_email; ?></span></label>
                                    </div>
                                    <div class="form-group form-check">
                                        <input type="checkbox" name="valid" value="valid"
                                            class="form-check-input check_sub_<?php echo $i ?>"
                                            onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c; ?>"
                                            <?php if ($count_valid == 0) {
                                                echo 'disabled';
                                            } ?>>
                                        <label class="form-check-label"
                                            for="checkbox_<?php echo $c; ?>"><?php _e('Deliverables'); ?> <span
                                                class="badge badge-success"><?php echo $count_valid; ?></span></label>
                                    </div>
                                    <div class="form-group form-check">
                                        <input type="checkbox" name="invalid" value="invalid"
                                            class="form-check-input check_sub_<?php echo $i ?>"
                                            onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c; ?>"
                                            <?php if ($count_invalid == 0) {
                                                echo 'disabled';
                                            } ?>>
                                        <label class="form-check-label"
                                            for="checkbox_<?php echo $c; ?>"><?php _e('Non Deliverables'); ?> <span
                                                class="badge badge-danger"><?php echo $count_invalid + $count_skipped; ?></span></label>
                                    </div>
                                    <div class="form-group form-check">
                                        <input type="checkbox" name="catchall" value="catchall"
                                            class="form-check-input check_sub_<?php echo $i ?>"
                                            onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c; ?>"
                                            <?php if ($count_catchall == 0) {
                                                echo 'disabled';
                                            } ?>>
                                        <label class="form-check-label"
                                            for="checkbox_<?php echo $c; ?>"><?php _e('Deliverables with Risk'); ?> <span
                                                class="badge badge-info"><?php echo $count_catchall; ?></span></label>
                                    </div>

                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group form-check">
                                        <input type="checkbox" name="free" value="free"
                                            class="form-check-input check_sub_<?php echo $i ?>"
                                            onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c; ?>"
                                            <?php if ($count_free == 0) {
                                                echo 'disabled';
                                            } ?>>
                                        <label class="form-check-label"
                                            for="checkbox_<?php echo $c; ?>"><?php _e('Free Account'); ?> <span
                                                class="badge badge-dark"><?php echo $count_free; ?></span></label>
                                    </div>
                                    <div class="form-group form-check">
                                        <input type="checkbox" name="role" value="role"
                                            class="form-check-input check_sub_<?php echo $i ?>"
                                            onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c; ?>"
                                            <?php if ($count_role == 0) {
                                                echo 'disabled';
                                            } ?>>
                                        <label class="form-check-label"
                                            for="checkbox_<?php echo $c; ?>"><?php _e('Role Account'); ?> <span
                                                class="badge badge-light"><?php echo $count_role; ?></span></label>
                                    </div>
                                    <div class="form-group form-check">
                                        <input type="checkbox" name="disposable" value="disposable"
                                            class="form-check-input check_sub_<?php echo $i ?>"
                                            onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c; ?>"
                                            <?php if ($count_disposable == 0) {
                                                echo 'disabled';
                                            } ?>>
                                        <label class="form-check-label"
                                            for="checkbox_<?php echo $c; ?>"><?php _e('Disposable Account'); ?> <span
                                                class="badge badge-secondary"><?php echo $count_disposable; ?></span></label>
                                    </div>
                                    <div class="form-group form-check">
                                        <input type="checkbox" name="syntax" value="syntax"
                                            class="form-check-input check_sub_<?php echo $i ?>"
                                            onchange="cbChange<?php echo $i; ?>(this)" id="checkbox_<?php echo ++$c; ?>"
                                            <?php if ($count_syntax == 0) {
                                                echo 'disabled';
                                            } ?>>
                                        <label class="form-check-label"
                                            for="checkbox_<?php echo $c; ?>"><?php _e('Syntex Error'); ?> <span
                                                class="badge badge-warning"><?php echo $count_syntax; ?></span></label>
                                    </div>
                                </div>
                            </div>
                            <script>                             (function ($) { "use strict"; window['cbChange<?php echo $i ?>'] = function () { var cbs = document.getElementsByClassName("check_all_<?php echo $i ?>"); if (cbs.length) { cbs[0].checked = false; } }; window['allChange<?php echo $i ?>'] = function () { var cbs = document.getElementsByClassName("check_sub_<?php echo $i ?>"); for (var idx = 0; idx < cbs.length; idx++) { cbs[idx].checked = false; } }; })(jQuery);
                            </script>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary"
                                    data-dismiss="modal"><?php _e('Close'); ?></button>
                                <button type="submit" class="btn btn-primary"><?php _e('Download'); ?></button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Mobile Action Modal -->
            <div class="modal fade mobile-action-modal" id="actionModal" tabindex="-1" role="dialog"
                aria-labelledby="actionModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="actionModalLabel">Actions</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <a class="dropdown-item" href="#" data-toggle="modal"
                                data-target="#model_<?php echo $csv_name_ex; ?>">
                                <i class="icon-copy dw dw-file-37"></i> <?php _e('Download'); ?>
                            </a>
                            <a class="dropdown-item btn btn-danger export-pdf-btn" href="#"
                                data-csv-file-name="<?php echo $csv_file_name; ?>" data-total="<?php echo $total_email; ?>"
                                data-valid="<?php echo $count_valid; ?>" data-invalid="<?php echo $count_invalid; ?>"
                                data-catchall="<?php echo $count_catchall; ?>" data-unknown="<?php echo $count_unknown; ?>"
                                data-skipped="<?php echo $count_skipped; ?>"
                                data-syntax-error="<?php echo $count_syntax; ?>"
                                data-disposable="<?php echo $count_disposable; ?>"
                                data-free-account="<?php echo $count_free; ?>"
                                data-role-account="<?php echo $count_role; ?>"
                                data-completed-time="<?php echo $completed_time; ?>"
                                data-site-title="<?php echo $site_title; ?>" data-s-url="<?php echo $s_url; ?>">
                                <i class="icon-copy dw dw-file"></i> Export PDF
                            </a>
                            <a class="dropdown-item" href="#" data-toggle="modal"
                                data-target="#model_assign_<?php echo $csv_name_ex; ?>">
                                <i class="icon-copy dw dw-list"></i> Assign Tag
                            </a>
                            <a class="dropdown-item file_delete_btn btn btn-warning" href="#" data-toggle="modal"
                                data-target="<?php echo $csv_name_ex; ?>">
                                <i class="icon-copy dw dw-delete-3"></i> Remove
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Mobile Action Modal End -->


            <?php
            $i++; // Increment counter inside the loop
        } // End while loop 
        ?>
    </div>
</div>

<!-- ALL MODALS -->

<!-- Details Modal -->
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="detailsModalLabel"
    aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content details-modal">
            <div class="modal-header">
                <h5 class="modal-title" id="detailsModalLabel"><?php _e('File Details'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-6">
                        <?php
                        // Initialize variables to avoid notices
                        $total_email_safe = isset($total_email) ? $total_email : 0;
                        $count_valid_safe = isset($count_valid) ? $count_valid : 0;
                        $count_invalid_safe = isset($count_invalid) ? $count_invalid : 0;
                        $count_catchall_safe = isset($count_catchall) ? $count_catchall : 0;
                        $count_unknown_safe = isset($count_unknown) ? $count_unknown : 0;
                        $count_skipped_safe = isset($count_skipped) ? $count_skipped : 0;
                        $count_syntax_safe = isset($count_syntax) ? $count_syntax : 0;
                        $count_disposable_safe = isset($count_disposable) ? $count_disposable : 0;
                        $count_free_safe = isset($count_free) ? $count_free : 0;
                        $count_role_safe = isset($count_role) ? $count_role : 0;
                        $csv_name_ex_safe = isset($csv_name_ex) ? $csv_name_ex : '';
                        ?>
                        <p><?php _e('Total'); ?>: <span class="value total"
                                id="total_<?php echo $csv_name_ex_safe; ?>"><?php echo $total_email_safe; ?></span></p>
                        <p><?php _e('Valid'); ?>: <span class="value valid"
                                id="valid_<?php echo $csv_name_ex_safe; ?>"><?php echo $count_valid_safe; ?></span></p>
                        <p><?php _e('Invalid'); ?>: <span class="value invalid"
                                id="invalid_<?php echo $csv_name_ex_safe; ?>"><?php echo $count_invalid_safe; ?></span>
                        </p>
                        <p><?php _e('Catch All'); ?>: <span class="value catchall"
                                id="catchall_<?php echo $csv_name_ex_safe; ?>"><?php echo $count_catchall_safe; ?></span>
                        </p>
                        <p><?php _e('Unknown'); ?>: <span class="value unknown"
                                id="unknown_<?php echo $csv_name_ex_safe; ?>"><?php echo $count_unknown_safe; ?></span>
                        </p>
                    </div>
                    <div class="col-6">
                        <p><?php _e('Skipped'); ?>: <span class="value skipped"
                                id="skipped_<?php echo $csv_name_ex_safe; ?>"><?php echo $count_skipped_safe; ?></span>
                        </p>
                        <p><?php _e('Syntax Error'); ?>: <span class="value syntax"
                                id="syntax_<?php echo $csv_name_ex_safe; ?>"><?php echo $count_syntax_safe; ?></span>
                        </p>
                        <p><?php _e('Disposable'); ?>: <span class="value disposable"
                                id="disposable_<?php echo $csv_name_ex_safe; ?>"><?php echo $count_disposable_safe; ?></span>
                        </p>
                        <p><?php _e('Free Account'); ?>: <span class="value free_account"
                                id="free_account_<?php echo $csv_name_ex_safe; ?>"><?php echo $count_free_safe; ?></span>
                        </p>
                        <p><?php _e('Role Account'); ?>: <span class="value role_account"
                                id="role_account_<?php echo $csv_name_ex_safe; ?>"><?php echo $count_role_safe; ?></span>
                        </p>
                    </div>
                </div>
                <div class="chart-container" style="max-width:280px;max-height:280px;margin:0 auto;">
                    <canvas id="detailsChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>


<!-- ALL MODALS END -->



<!-- SCRIPTS -->

<script>
    (function ($) {
        "use strict";
        var desktopMenuSelector = '#desktopDropdownMenu';
        var toggleSelector = '.dropdown-toggle.d-none.d-md-inline';

        function toggleDropdownMenu() {
            var dropdownMenu = document.getElementById('desktopDropdownMenu');
            if (!dropdownMenu) {
                return;
            }
            dropdownMenu.style.display = dropdownMenu.style.display === 'block' ? 'none' : 'block';
        }

        $(document).on('click', toggleSelector, function (event) {
            event.preventDefault();
            event.stopPropagation();
            toggleDropdownMenu();
        });

        $(document).on('click', function (event) {
            var dropdownMenu = document.getElementById('desktopDropdownMenu');
            var toggleButton = document.querySelector(toggleSelector);
            if (!dropdownMenu || !toggleButton) {
                return;
            }
            if (!dropdownMenu.contains(event.target) && !toggleButton.contains(event.target)) {
                dropdownMenu.style.display = 'none';
            }
        });
    })(jQuery);
</script>

<script>
    (function ($) {
        "use strict";

        $(document).on('click', '.export-pdf-btn', function (event) {
            event.preventDefault();
            var button = $(this);
            var data = {
                csv_file_name: button.data('csv-file-name'),
                total: button.data('total'),
                valid: button.data('valid'),
                invalid: button.data('invalid'),
                catchall: button.data('catchall'),
                unknown: button.data('unknown'),
                skipped: button.data('skipped'),
                syntax_error: button.data('syntax-error'),
                disposable: button.data('disposable'),
                free_account: button.data('free-account'),
                role_account: button.data('role-account'),
                completed_time: button.data('completed-time'),
                site_title: button.data('site-title'),
                s_url: button.data('s-url')
            };
            var form = $('<form>', {
                method: 'POST',
                action: '../functions/export_pdf.php'
            });
            $.each(data, function (key, value) {
                form.append($('<input>', {
                    type: 'hidden',
                    name: key,
                    value: value
                }));
            });
            $('body').append(form);
            form.submit();
            form.remove();
        });

        $(document).on('click', '.dropdown-toggle-btn', function (event) {
            event.preventDefault();
            event.stopPropagation();
            var dropdownMenu = $(this).next('.dropdown-menu');
            $('.dropdown-menu').not(dropdownMenu).hide();
            dropdownMenu.toggle();
        });

        $(document).on('click', function (event) {
            if (!$(event.target).closest('.action-menu').length) {
                $('.dropdown-menu').hide();
            }
        });

        $(document).on('click', '.btn-details', function (event) {
            event.preventDefault();
            var csvNameEx = $(this).closest('.scan_list').attr('id').replace('mega_bar_', '');
            var detailsModal = $('#detailsModal');
            detailsModal.find('.value').text('Loading...');
            $.ajax({
                url: '../functions/fetch_metadata.php',
                type: 'POST',
                data: { csv_file_name: csvNameEx },
                dataType: 'json'
            }).done(function (response) {
                if (response.success) {
                    detailsModal.find('.value.total').text(response.data.total || 0);
                    detailsModal.find('.value.valid').text(response.data.valid || 0);
                    detailsModal.find('.value.invalid').text(response.data.invalid || 0);
                    detailsModal.find('.value.catchall').text(response.data.catch_all || 0);
                    detailsModal.find('.value.unknown').text(response.data.unknown || 0);
                    detailsModal.find('.value.skipped').text(response.data.skipped || 0);
                    detailsModal.find('.value.syntax').text(response.data.syntax_error || 0);
                    detailsModal.find('.value.disposable').text(response.data.disposable || 0);
                    detailsModal.find('.value.free_account').text(response.data.free_account || 0);
                    detailsModal.find('.value.role_account').text(response.data.role_account || 0);
                    var ctxDetails = document.getElementById('detailsChart').getContext('2d');
                    if (window.detailsChart && window.detailsChart.data) {
                        window.detailsChart.data.datasets[0].data = [
                            response.data.valid || 0,
                            response.data.invalid || 0,
                            response.data.catch_all || 0,
                            response.data.unknown || 0
                        ];
                        window.detailsChart.update();
                    } else {
                        window.detailsChart = new Chart(ctxDetails, {
                            type: 'doughnut',
                            data: {
                                labels: [
                                    "<?php _e('Valid'); ?>",
                                    "<?php _e('Invalid'); ?>",
                                    "<?php _e('Catch All'); ?>",
                                    "<?php _e('Unknown'); ?>"
                                ],
                                datasets: [{
                                    data: [
                                        response.data.valid || 0,
                                        response.data.invalid || 0,
                                        response.data.catch_all || 0,
                                        response.data.unknown || 0
                                    ],
                                    backgroundColor: ['#28a745', '#dc3545', '#17a2b8', '#6c757d'],
                                    borderColor: ['#28a745', '#dc3545', '#17a2b8', '#6c757d'],
                                    borderWidth: 1
                                }]
                            },
                            options: {
                                responsive: true,
                                plugins: {
                                    legend: {
                                        display: true,
                                        position: 'bottom'
                                    }
                                }
                            }
                        });
                    }
                } else {
                    detailsModal.find('.value').text('Error fetching data.');
                }
            }).fail(function () {
                detailsModal.find('.value').text('Error fetching data.');
            }).always(function () {
                detailsModal.modal('handleUpdate');
            });

            detailsModal.modal('show');
        });
    })(jQuery);
</script>

<script>
    (function ($) {
        "use strict";

        $(document).on('click', '.file_delete_btn', function (event) {
            event.preventDefault();
            var button = $(this);
            var csvfileName = button.data('target');
            var userId = "<?php echo $user_id; ?>";
            if (!confirm("<?php _e('Are you sure?'); ?>")) {
                return;
            }
            $.ajax({
                url: "../functions/delete_csv_file.php",
                type: "POST",
                data: { filename: csvfileName, uid: userId },
                dataType: "json"
            }).done(function (response) {
                console.log(response);
                if (response.success) {
                    var rowId = `#mega_bar_${csvfileName.replace(/\.[^/.]+$/, "")}`;
                    $(rowId).remove();
                    alert("<?php _e('File deleted successfully.'); ?>");
                } else {
                    alert("<?php _e('Failed to delete the file.'); ?>");
                }
            }).fail(function () {
                alert("<?php _e('An error occurred while deleting the file. Please try again.'); ?>");
            });
        });
    })(jQuery);

</script>

<?php if (!empty($deltaLatch)) { ?>

    <script>     (function ($) {
            "use strict";
            $(document).on('click', '.task-cancel-btn', function (event) {
                event.preventDefault(); var $button = $(this); var csvFileName = $button.attr('data-target'); var userId = "<?php echo $user_id; ?>"; var csvNameEx = csvFileName.replace(/\.[^/.]+$/, ""); $button.prop('disabled', true).find('i').removeClass('icon-copy dw dw-stop').addClass('spinner-border'); $.ajax({ url: "../functions/<?php echo $task_cancel_func; ?>", type: 'post', data: { filename: csvFileName, uid: userId } }).done(function () {
                    $('#verify_' + csvNameEx).show().find('i').removeClass('spinner-border'); $('#cancel_' + csvNameEx).prop('disabled', false).hide().find('i').removeClass('spinner-border').addClass('icon-copy dw dw-stop'); if (typeof progressIntervals !== 'undefined' && progressIntervals[csvNameEx]) {
                        clearInterval(progressIntervals[csvNameEx]);
                        delete progressIntervals[csvNameEx];
                        console.log('Interval cleared for ' + csvNameEx);
                    }
                }).fail(function () {
                    alert('Failed to cancel the task. Please try again.');
                    $('#cancel_' + csvNameEx)
                        .prop('disabled', false)
                        .find('i')
                        .removeClass('spinner-border')
                        .addClass('icon-copy dw dw-stop');
                });
            });

            $(document).on('click', '.btn-verify', function (event) {
                event.preventDefault();
                var $button = $(this);
                var fromMail = '<?php echo $scan_mail; ?>';
                var timeOut = '<?php echo (!empty($scan_timeout) ? $scan_timeout : 10); ?>';
                var scanPort = '<?php echo (!empty($scan_port) ? $scan_port : 25); ?>';
                var extServers = '<?php echo $ext_server; ?>';
                var redirectUrl = '<?php echo $a_url; ?>';

                if (!fromMail.length) {
                    alert('<?php _e('Please set time out and a from mail in settings page for continue scan'); ?>');
                    return;
                }

                var csvFileName = $button.attr('data-target');

                <?php if ($multi_scan == 'false') { ?>
                    //   $('.preloader').each(function(index,node){
                    //     if( $(node).attr('id') !== '#preloader_'+csvFileName ){
                    //       $('#'+$(node).attr('id')).css('display','none');
                    //       $('#cancel_'+$(node).attr('id').replace('preloader_','')).css('display','block');
                    //     }
                    //   });
                <?php } ?>

                var csvNameEx = csvFileName.replace(/\.[^/.]+$/, "");
                var cancelButton = $('#cancel_' + csvNameEx);
                $button.hide();
                cancelButton.css('display', 'block');
                var userId = "<?php echo $user_id ?>";
                var totalWorkers = "<?php echo $total_workers ?>";

                if (extServers === 'true') {
                    $.ajax({
                        url: "../functions/check_servers.php",
                        type: 'POST',
                        dataType: 'json'
                    }).done(function (response) {
                        if (response.status === 'success' && response.server_path) {
                            $.ajax({
                                url: "../functions/email_verify.php",
                                type: 'post',
                                data: {
                                    filename: csvFileName,
                                    uid: userId,
                                    total_workers: totalWorkers,
                                    frommail: fromMail,
                                    timeout: timeOut,
                                    scan_port: scanPort
                                }
                            }).done(function () {
                                window.location.reload(false);
                            });
                        } else {
                            alert('Please add good External Servers in the Email Scanner Settings page.');
                            window.location.href = redirectUrl + '/settings.php#scanner_sys';
                        }
                    }).fail(function () {
                        alert('Error checking external servers. Please try again.');
                        $button.show();
                        cancelButton.hide();
                    });
                } else {
                    $.ajax({
                        url: "../functions/email_verify.php",
                        type: 'post',
                        data: {
                            filename: csvFileName,
                            uid: userId,
                            total_workers: totalWorkers,
                            frommail: fromMail,
                            timeout: timeOut,
                            scan_port: scanPort
                        }
                    }).fail(function () {
                        $button.show();
                        cancelButton.hide();
                    });
                }
            });
        })(jQuery);
    </script>

    <div class="modal fade" id="addList" data-backdrop="static" data-keyboard="false" role="dialog">
        <div class="modal-dialog modal-lg">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <h5><?php _e('Only CSV file can add'); ?></h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <ul class="nav nav-tabs" style="border-bottom: 0px;" id="myTab" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab"
                                aria-controls="home" aria-selected="true"><i
                                    class="fas fa-file-upload"></i><?php _e('Upload'); ?></a>
                        </li>
                    </ul>
                    <div class="tab-content" id="myTabContent">
                        <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
                            <div class="row" id="upload_area">
                                <form method="post" id="upload_form2" enctype="multipart/form-data">
                                    <div
                                        style="border: 1px solid #dddfeb;margin: 0 auto;text-align: center;padding: 150px;">
                                        <input type="file" name="file" id="csv_filename">
                                    </div>
                                </form>
                            </div>
                            <div class="table-responsive" id="process_area"></div>

                            <div class="uplogin_file" style="display: none; text-align: center; padding: 20px;">
                                <div class="spinner"></div>
                                <p><?php _e('File processing. Please wait...'); ?></p>
                                <div class="progress" style="height: 20px; margin-top: 20px;">
                                    <div id="uploadProgressBar"
                                        class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"
                                        style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
                                </div>
                            </div>

                            <!-- CSS for the loading spinner -->
                            <style>
                                @keyframes spinner {
                                    0% {
                                        transform: rotate(0deg);
                                    }

                                    100% {
                                        transform: rotate(360deg);
                                    }
                                }

                                .spinner {
                                    margin: 100px auto;
                                    width: 50px;
                                    height: 50px;
                                    border: 5px solid rgba(0, 0, 0, 0.1);
                                    border-left-color: #000;
                                    border-radius: 50%;
                                    animation: spinner 1.1s linear infinite;
                                }
                            </style>

                            <div style="margin-top: 20px; " class="uploading_succes">
                                <h3 id="success_msg"> </h3>
                                <p class="" id="store-status"> </p>
                                <p style="color: green; text-align: center;"><?php _e('The page will reload in '); ?><span
                                        id="countdown">10</span> <?php _e('seconds.'); ?></p>
                                <p style="text-align: center;"><button
                                        onclick="location.reload();"><?php _e('Reload Now'); ?></button></p>
                            </div>
                            <br>
                        </div>
                        <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
                        </div>
                        <div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <script type="text/javascript">
        $(document).ready(function () {
            $(".uplogin_file").hide();
            $(".uploading_succes").hide();
            <?php echo $cdata1; ?>
            var email_name = 0;
            var user_id = <?php echo $_SESSION['id']; ?>;
            var column_data = [];

            $(document).on('change', '.set_column_data', function () {
                var column_name = $(this).val();
                var column_number = $(this).data('column_number');
                if (column_name in column_data) {
                    alert('<?php _e('You have already define'); ?> ' + column_name + ' <?php _e('column'); ?>');
                    $(this).val('');
                    delete column_data[column_name];
                    return false;
                }
                if (column_name != '') {
                    column_data[column_name] = column_number;
                } else {
                    const entries = Object.entries(column_data);
                    for (const [key, value] of entries) {
                        if (value == column_number) {
                            delete column_data[key];
                        }
                    }
                }
                total_selection = Object.keys(column_data).length;
                console.log(column_data.email_name, total_selection);
                if (total_selection > 0 && column_data.email_name != undefined) {
                    $('#import').attr('disabled', false);
                    <?php echo $cdata2; ?>
                    console.log(<?php echo json_encode($cdata2); ?>);
                    email_name = column_data.email_name;
                    // user_id = column_data.user_id;
                } else {
                    $('#import').attr('disabled', 'disabled');
                }
            });

            $(document).on('click', '#import', function (event) {
                $('#process_area').css('display', 'none');
                $('.uplogin_file').show();
                const csvNewName = $("#csv_new_name").val();
                const get_check_mailbox = $(this).closest('#process_area').find("input[name='check_mailbox']").prop('checked');
                const ext = $("input#csv_filename").val().split(".").pop().toLowerCase();
                const fname = $('#csv_filename').val().replace(/\s/g, "_");
                const cc_data = {};

                $('.set_column_data').each(function () {
                    const column_name = $(this).val();
                    const column_number = $(this).data('column_number');
                    if (column_name) {
                        cc_data[column_name] = column_number;
                    }
                });

                event.preventDefault();
                $.ajax({
                    url: "../functions/save_email.php",
                    method: "POST",
                    data: {
                        filename: fname,
                        cc_data: JSON.stringify(cc_data),
                        check_mailbox: get_check_mailbox,
                        uid: user_id,
                        csv_new_name: csvNewName
                    },
                    beforeSend: function () {
                        $('#import').attr('disabled', 'disabled').text('<?php _e('Importing'); ?>...');
                    },
                    success: function (data) {
                        console.log(data);
                        $('#import').attr('disabled', false).text('<?php _e('Import'); ?>');
                        $('#process_area').css('display', 'none');
                        $('#upload_area').css('display', 'block');
                        $('#upload_form2')[0].reset();
                        const response = jQuery.parseJSON(data);
                        if (response.error) {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: response.error,
                            });
                            $('.uplogin_file').hide();
                        } else {
                            $('#message').html("<div class='alert alert-success'>" + data + "</div>");
                            const obj = jQuery.parseJSON(data);
                            if (obj.task === 'import') {
                                $('#success_msg').html('<?php _e('Thank you'); ?> - <?php _e('Your list is now in import queue.'); ?>.');
                                $('#store-status').html('<p><?php _e('Duplicate emails will auto remove after successful import and total amount will be calculated.<br> Details will be forwarded via email after import finished.'); ?></p>');
                            } else if (obj.task === 'direct') {
                                $('#success_msg').html('<?php _e('Thank you'); ?> - <?php _e('Your list has been uploaded successfully'); ?>.');
                                $('#store-status').html('<?php _e('Total'); ?>: <span class="text-primary">' + obj.total + '</span>  <?php _e('Save'); ?>: <span class="text-success">' + obj.save + '</span>  <?php _e('Duplicate'); ?>: <span class="text-danger">' + obj.duplicate + '</span> (<?php _e('duplicate emails has been removed from scan queue'); ?>)');
                            }
                            $('#count_total_export').text('');
                            $(".uplogin_file").hide();
                            $("#myTab").hide();
                            $("#upload_form2").hide();
                            $(".uploading_succes").show();
                            $("#filename").empty(" ");
                            let countdown = 10;
                            const countdownInterval = setInterval(function () {
                                countdown--;
                                $("#countdown").text(countdown);
                                if (countdown <= 0) {
                                    clearInterval(countdownInterval);
                                    location.reload();
                                }
                            }, 1000);
                        }
                    },
                    error: function (xhr, status, error) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: xhr.responseText,
                        });
                        $('.uplogin_file').hide();
                    }
                });
            });
        });
    </script>


    <script>
        $(function () {
            $(".check_inbox").on('click', function () {
                var disabled = $(this).find("input[type='hidden']").attr("data-status");
                if (disabled == 'true') {
                    var time_left = $(this).find("input[type='hidden']").attr("data-wtime");
                    Swal.fire({
                        title: "<?php _e('Sorry, Not Yet!'); ?>",
                        showConfirmButton: true,
                        heightAuto: false,
                        type: "caution",
                        html: '<?php _e('You cannot start Mailbox Validation right now. At least wait'); ?> ' + time_left + ' <?php _e('more minutes. This cooldown assigned to get all return emails from undelivered addresses for higher validation accuracy before final validations.'); ?>'
                    }).then((result) => {
                        location.reload();
                    });
                } else {
                    event.preventDefault();
                    var csvfile_name = $(this).attr("data-target");
                    var csv_name_ex = csvfile_name.replace(/\.[^/.]+$/, "");
                    //   $(this).parents('.verify-chart').hide();
                    //   $('#preloader_'+csv_name_ex).css('display','block');
                    var inbox_check = $(this).find("input[type='hidden']").val();
                    var user_id = "<?php echo $user_id ?>";
                    $.ajax({
                        url: "../functions/email_verify.php",
                        type: "post",
                        data: {
                            filename: csvfile_name,
                            uid: user_id,
                            inbox_check: inbox_check
                        },
                        success: function (response) {
                            Swal.fire("<?php _e('Inbox Getting Checked For This List!'); ?>", "<?php _e('Once inbox checking completes, you will receive a notification email with updated results. Check back after a few minutes!'); ?>", "success").then((result) => {
                                location.reload();
                            });
                            // window.location.reload( false );
                        }
                    });
                }
            });
        });
    </script>


    <!-- add list script -->
    <script>
        $(".uplogin_file").hide();
        $(".uploading_succes").hide();
        $(document).ready(function () {
            $("#csv_filename").attr("autocomplete", "off");
            $("#csv_filename").change(function (e) {
                $('#store-status').html('');
                var ext = $("input#csv_filename").val().split(".").pop().toLowerCase();

                function randomNumberFromRange(min, max) {
                    return Math.floor(Math.random() * (max - min + 1) + min);
                }

                var fname = $('#csv_filename').val();
                fname = fname.replace(/\s/g, "_");
                if ($.inArray(ext, ["csv"]) == -1) {
                    alert('Upload CSV');
                    return false;
                }
                // File size check
                var fileSize = e.target.files[0].size / 1024 / 1024; // in MB
                if (fileSize > '<?php echo $file_size_limit; ?>') { // limit
                    alert('File size exceeds the limit of <?php echo $file_size_limit; ?> MB. Please reduce the file size and try again.');
                    return false;
                }
                $('#upload_area').css('display', 'none');
                $("#myTab").hide();
                $(".uplogin_file").show();
                if (e.target.files != undefined) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $(".uploading_succes").hide();
                        $('#count_total_export').text('');
                        var lines = e.target.result.split('\r\n');
                        if (lines.length == 1) {
                            lines = e.target.result.split('\n');
                        }
                        var c = 0;
                        var t = 0;
                        var title_row = lines[0].split(',');
                        var email_row_check = false;
                        for (r = 0; r < title_row.length; r++) {
                            var column_name = title_row[r].trim();
                            column_name = title_row[r].toLowerCase();


                            email_row_check = true;
                            var target_column_index = r;
                            break;
                        }
                        var data_array = '';
                        if (email_row_check) {
                            for (i = 1; i < lines.length; ++i) {
                                var email_column = lines[i].split(',');
                                var email = email_column[target_column_index];
                                if (email != '') {
                                    email = $.trim(email);
                                }
                                if (email != '') {
                                    t++;
                                    data_array += email + ',';
                                    $('#count_total_export').text(t);
                                    var user_id = '<?php echo $_SESSION['id']; ?>';
                                }
                            }
                            var formData = new FormData()
                            var file_obj = document.getElementById("csv_filename")
                            var newFileName = '<?php echo time(); ?>' + randomNumberFromRange(10, 99) + '<?php echo $_SESSION['id']; ?>' + '_csv_file.csv';
                            var renamedFile = new File([file_obj.files[0]], newFileName, {
                                type: file_obj.files[0].type
                            });
                            // $('#image')[0].files[0];
                            formData.append('file', renamedFile);
                            formData.append('inbox_checker', '<?php echo $inbox_checker; ?>');
                            <?php $cc_data = serialize($cc_data); ?>
                            formData.append('cc_data', '<?php echo $cc_data; ?>');
                            // formData.append('file', fname);
                            // console.log(data_array.length);
                            if (data_array.length !== 0) {
                                $.ajax({
                                    url: "../functions/upload.php",
                                    method: "POST",
                                    data: formData,
                                    dataType: 'json',
                                    contentType: false,
                                    cache: false,
                                    processData: false,
                                    beforeSend: function () {
                                        $("#uploadProgressBar").css("width", "0%");
                                        $("#uploadProgressBar").attr("aria-valuenow", 0);
                                        $("#uploadProgressBar").text("0%");
                                    },
                                    success: function (data) {
                                        if (data.csv_file) {
                                            $('#csvFileName').val(data.csv_file);
                                        }
                                        if (data.error != '') {
                                            $('#message').html('<div class="alert alert-danger">' + data.error + '</div>');
                                        } else {
                                            // Simulate processing progress after upload
                                            let processingProgress = 0;
                                            const interval = setInterval(function () {
                                                if (processingProgress < 100) {
                                                    processingProgress += 10; // Increment by 10%
                                                    $("#uploadProgressBar").css("width", processingProgress + "%");
                                                    $("#uploadProgressBar").attr("aria-valuenow", processingProgress);
                                                    $("#uploadProgressBar").text(processingProgress + "%");
                                                } else {
                                                    clearInterval(interval);
                                                    $(".uplogin_file").hide();
                                                    $('#process_area').html(data.output);
                                                    $('#upload_area').css('display', 'none');
                                                }
                                            }, 300); // Simulate processing every 300ms
                                        }
                                    }
                                });
                            } else {
                                $(".uplogin_file").hide();
                                $("#filename").empty(" ");
                                alert('<?php _e('No email column found'); ?>');
                            }
                        }
                    };
                    reader.readAsText(e.target.files.item(0));
                }
                return false;
            });
        });

    </script>
<?php } else { ?>
    <div class="container-fluid">
        <div class="alert alert-danger text-center" style="margin:40px 0;">
            <?php echo htmlspecialchars($guardMessage, ENT_QUOTES, 'UTF-8'); ?>
        </div>
    </div>
<?php } ?>
<input type="hidden" id="csvFileName" value="">

<!-- SCRIPTS END -->

<script src="../assets/scripts/chart.min.js"></script>
<script src="../assets/scripts/progress-animation-controller.js"></script>

<!-- Add this script to handle btn-verify clicks and reload persistence -->
<script>
    $(document).ready(function () {
        // Add countdown timer span after each .email_amnt if not present
        $('.email_amnt').each(function () {
            if ($(this).next('.countdown-timer').length === 0) {
                $(this).after('<span class="countdown-timer" style="margin-left:8px;color:#007bff;font-weight:bold;display:none;">(60)</span>');
            }
        });

        var countdowns = {};

        function getActiveCSVsFromDOM() {
            var csvs = [];
            $('.scan_list').each(function () {
                var csvName = $(this).attr('id').replace('mega_bar_', '');
                var progress = parseInt($(this).find('.progress-bar-label').text());
                var status = $(this).find('.progress-bar').hasClass('animated');
                if (status && progress < 100) {
                    csvs.push(csvName);
                }
            });
            return csvs;
        }

        function showCountdownForActiveCSVs() {
            var activeCSVs = getActiveCSVsFromDOM();
            $('.countdown-timer').hide();
            activeCSVs.forEach(function (csvName) {
                $('#email_amnt_' + csvName).next('.countdown-timer').show();
            });
        }

        function resetCountdown(csvName) {
            countdowns[csvName] = 60;
            $('#email_amnt_' + csvName).next('.countdown-timer').text('(60)');
        }

        function updateUIWithBatchData(data) {
            if (!data || typeof data !== 'object') return;
            Object.keys(data).forEach(function (csvFileName) {
                var result = data[csvFileName];
                var csvNameEx = csvFileName.replace(/\.[^/.]+$/, "");
                if (result && result.success) {
                    // Update progress bar
                    var progressBar = $('#progress-bar_' + csvNameEx);
                    if (progressBar.length) {
                        var progressBarLabel = progressBar.siblings('.progress-bar-label');
                        var emailAmountElement = $('#email_amnt_' + csvNameEx);
                        progressBar.css('width', result.percent + '%').attr('aria-valuenow', result.percent);
                        if (progressBarLabel.length) {
                            progressBarLabel.text(result.percent + '% (' + result.total_verify + ')');
                        }
                        if (emailAmountElement.length) {
                            emailAmountElement.text(result.total_verify + ' / ' + (result.total || ''));
                        }
                        // Set animation class based on status
                        if (result.status === 'processing') {
                            progressBar.addClass('animated').removeClass('no-animation');
                        } else {
                            progressBar.removeClass('animated').addClass('no-animation');
                        }
                        // Robustly hide cancel button if scan is done (percent >= 100 or status is completed)
                        if (result.percent >= 100 || result.status === 'completed') {
                            $('#cancel_' + csvNameEx).hide();
                            // Hide countdown-timer when complete
                            $('#email_amnt_' + csvNameEx).next('.countdown-timer').hide();
                        }
                    }
                    // Update other stats
                    if (result.details && Array.isArray(result.details)) {
                        $.each(result.details, function (index, item) {
                            if (item) {
                                var key = Object.keys(item)[0];
                                var value = item[key];
                                try { $('#' + key).text(value); } catch (e) { }
                            }
                        });
                    }
                    if (result.percent >= 100 || result.status === 'completed') {
                        $('#mega_bar_' + csvNameEx + ' .spinner-border.text-info').hide();
                    }
                }
            });
        }

        function startCountdowns() {
            if (window.globalCountdownInterval) clearInterval(window.globalCountdownInterval);
            window.globalCountdownInterval = setInterval(function () {
                var activeCSVs = getActiveCSVsFromDOM();
                var trigger = false;
                activeCSVs.forEach(function (csvName) {
                    if (typeof countdowns[csvName] === 'undefined') countdowns[csvName] = 60;
                    countdowns[csvName]--;
                    if (countdowns[csvName] <= 0) {
                        countdowns[csvName] = 0;
                        $('#email_amnt_' + csvName).next('.countdown-timer').text('(0)');
                        trigger = true;
                    } else {
                        $('#email_amnt_' + csvName).next('.countdown-timer').text('(' + countdowns[csvName] + ')');
                    }
                });
                if (trigger) {
                    batchPollProgress(function (polledCSVs, responseData) {
                        // Reset only those that were just polled
                        polledCSVs.forEach(function (csvName) {
                            countdowns[csvName] = 60;
                            $('#email_amnt_' + csvName).next('.countdown-timer').text('(60)');
                        });
                        updateUIWithBatchData(responseData);
                    });
                }
            }, 1000);
        }

        function batchPollProgress(callback) {
            var activeCSVs = getActiveCSVsFromDOM();
            if (activeCSVs.length === 0) {
                if (typeof callback === 'function') callback([], {});
                return;
            }
            var filenames = [];
            activeCSVs.forEach(function (csvName) {
                var fullName = '';
                var el = $('#mega_bar_' + csvName);
                if (el.length && el.data('filename')) {
                    fullName = el.data('filename');
                } else {
                    fullName = csvName;
                }
                filenames.push(fullName);
            });
            $.ajax({
                url: "../functions/verify_per_count.php",
                type: "POST",
                dataType: "json",
                data: {
                    filenames: filenames,
                    uid: "<?php echo $user_id; ?>"
                },
                timeout: 60000,
                success: function (data) {
                    if (typeof callback === 'function') callback(filenames.map(function (name) { return name.replace(/\.[^/.]+$/, ""); }), data);
                },
                error: function (xhr, status, error) {
                    if (typeof callback === 'function') callback(filenames.map(function (name) { return name.replace(/\.[^/.]+$/, ""); }), {});
                }
            });
        }

        // On load, show countdown only for active CSVs
        showCountdownForActiveCSVs();
        startCountdowns();
        // Call once on load
        batchPollProgress(function (polledCSVs, responseData) {
            polledCSVs.forEach(function (csvName) { resetCountdown(csvName); });
            updateUIWithBatchData(responseData);
        });

        // Optionally, update visible countdowns when DOM changes (e.g. after AJAX)
        setInterval(showCountdownForActiveCSVs, 5000);
    });
</script>

<script>
    $(document).ready(function () {
        // Helper: Get activeCSVs from localStorage
        function getActiveCSVsFromStorage() {
            var taskInfo = JSON.parse(localStorage.getItem('evpTaskInfo') || '{}');
            return Array.isArray(taskInfo.activeCSVs) ? taskInfo.activeCSVs : [];
        }
        // Helper: Save activeCSVs to localStorage
        function setActiveCSVsToStorage(activeCSVs) {
            var taskInfo = JSON.parse(localStorage.getItem('evpTaskInfo') || '{}');
            taskInfo.activeCSVs = activeCSVs;
            localStorage.setItem('evpTaskInfo', JSON.stringify(taskInfo));
        }
        // On page load, always re-initialize activeCSVs from localStorage
        var activeCSVs = getActiveCSVsFromStorage();
        // Remove any that are not in DOM
        activeCSVs = activeCSVs.filter(function (csv) {
            return $('#mega_bar_' + csv).length > 0;
        });
        // Further filter out completed CSVs (progress 100% or not processing)
        activeCSVs = activeCSVs.filter(function (csv) {
            var progress = parseInt($('#mega_bar_' + csv).find('.progress-bar-label').text());
            var isProcessing = $('#mega_bar_' + csv).find('.progress-bar').hasClass('animated');
            return isProcessing && progress < 100;
        });
        setActiveCSVsToStorage(activeCSVs);

        // When clicking verify, add to activeCSVs in localStorage
        $(document).on('click', '.btn-verify', function () {
            var csvfile_name = $(this).attr('data-target');
            var csvNameEx = csvfile_name.replace(/\.[^/.]+$/, "");
            var activeCSVs = getActiveCSVsFromStorage();
            if (!activeCSVs.includes(csvNameEx)) {
                activeCSVs.push(csvNameEx);
                setActiveCSVsToStorage(activeCSVs);
            }
        });

        // In updateUIWithBatchData, remove from activeCSVs if percent >= 100
        function updateUIWithBatchData(data) {
            if (!data || typeof data !== 'object') return;
            var activeCSVs = getActiveCSVsFromStorage();
            Object.keys(data).forEach(function (csvFileName) {
                var result = data[csvFileName];
                var csvNameEx = csvFileName.replace(/\.[^/.]+$/, "");
                if (result && result.percent >= 100) {
                    // Remove from activeCSVs in localStorage
                    var idx = activeCSVs.indexOf(csvNameEx);
                    if (idx !== -1) {
                        activeCSVs.splice(idx, 1);
                        setActiveCSVsToStorage(activeCSVs);
                    }
                }
            });
        }
    });
</script>

<?php include '../templates/backend/members/footer.php'; ?>