<?php header('Content-Type: application/json');

include 'pagename.php';
include '../config.php';

function sanitize_text( $data ) { //filter value function
  
  global $db;
  
  return mysqli_real_escape_string( $db->link, strtolower( htmlspecialchars( stripslashes( trim( $data ) ) ) ) );
}

$filename = sanitize_text( $_POST['filename'] );

$user_id = intval( $_POST['uid'] );

if( ! empty( $filename ) ){
  
  $delete_task_sql = "SELECT * FROM evp_task WHERE csv_name = '$filename' AND user_id = '$user_id' AND status IN ('scanning', 'retry_emailsend')";
  
  $delete_task_read = $db->select( $delete_task_sql );
  
  $count_task = mysqli_num_rows( $delete_task_read );
  
  if ( $count_task > 0 ) {
	  
	$get_pid_sql = "SELECT pid FROM evp_email_list_metadata WHERE csv_file_name = '$filename' AND user_id = '$user_id' ";
	$get_pid = $db->select($get_pid_sql);
	$pidrow = $get_pid->fetch_assoc();
	$pid = $pidrow['pid'];
	
	if (is_numeric($pid) && $pid > 0) {
        mysqli_kill($db->link, $pid);
    }
	// mysqli_close($db->link);
	
	$csv_scan_status_sql = "UPDATE evp_email_list_metadata SET scan_status = 'pending', pid = NULL WHERE csv_file_name = '$filename' AND user_id = '$user_id' and scan_status = 'processing'";

	$csv_scan_status_read = $db->update($csv_scan_status_sql);
    
    $task_delete = "DELETE FROM evp_task WHERE csv_name = '$filename' AND user_id = '$user_id' AND status IN ('scanning', 'retry_emailsend')";
    $read_task_delete = $db->delete( $task_delete );
    
  }

  echo json_encode(['status' => 'ok', 'csv_name' => $filename]); exit();

}

if( ! isset( $_POST['filename'] ) ){
    echo json_encode(['status' => 'file_not_found']); exit();
}
