<?php
include 'pagename.php';
include $session;
Session::checkSession_log();
include '../config.php';
require_once __DIR__ . '/class.runtime.signal.php';
$gate = RuntimeSignal::instance();
if (!$gate->enforce('api:verify-mailbox')) {
    http_response_code(403);
    echo json_encode(['error' => ($gate->message() !== '' ? $gate->message() : 'Access denied')]);
    exit();
}

if(isset( $_REQUEST['filename'] ) && isset($_REQUEST['uid']) && isset($_REQUEST['inbox_check'])){
	   
    if(!function_exists('imap_open')){
        echo "IMAP is not configured.";
        exit();
    }else{
		
$evp_options_sql = "SELECT option_name, option_value FROM evp_options";
$evp_options_read = $db->select($evp_options_sql);
if ($evp_options_read) {
    $evp_options_check = mysqli_num_rows($evp_options_read);
    if ($evp_options_check > 0) {
		 while($row = $evp_options_read->fetch_assoc()) {
			$option_name[$row['option_name']] = $row['option_value'];
    }
	$evp_options_read->free();
        $s_url =  $option_name['site_url'];		
        $limit =  $option_name['batch_limit'];		
        $a_url =  $option_name['app_url'];		
		$s_path =  $option_name['script_path'];
		$site_title =  $option_name['site_title'];
		$site_logo =  $option_name['site_logo'];
		$system_email =  $option_name['system_email'];
		$sys_smtp  =  $option_name['sys_smtp'];
		$smtp_debug  =  $option_name['smtp_debug'];
		$ic_smtp_errors  =  $option_name['smtp_errors'];
		$ic_smtp_errors = str_replace(',', '|', $ic_smtp_errors);
	}
}

  $filename = $_REQUEST['filename'];
  $user_id = $_REQUEST['uid'];
  $inbox_check = $_REQUEST['inbox_check'];

  //  Keep running the script no matter what
   ignore_user_abort( true );

  // Execute for an unlimited timespan
   set_time_limit( 0 );
   ini_set('memory_limit', '-1');
		
			function check_mailbox(){
			  global $db, $log, $user_id, $limit, $toemail, $filename, $prev_path, $ic_send_mail, $ic_smtp_pass, $ic_imap_host, $ic_imap_port;
						 
			  $log->system_debug('MAILBOX -> check_mailbox()');

			  $dateTime = date('Y-m-d H:i:s');
		  
			  $user_id = intval( $user_id );
			  $task_delete_current = "DELETE FROM evp_task WHERE csv_name = '$filename' AND user_id = '$user_id'";
			  // user_id is not valid and background process exit call
			  if($user_id == 0){
				 $db->delete($task_delete_current); exit();
			  }

			  $task_email_check_q = "SELECT * FROM evp_task WHERE csv_name = '$filename' AND user_id = '$user_id' AND status = 'hold'";
			  $task_email_check_r = $db->select($task_email_check_q);
			  $task_email_check_c = mysqli_num_rows( $task_email_check_r );
			  
			 if(!($task_email_check_c > 0)){
				  $task_email_check_r->free();
				  $db->delete($task_delete_current);
				  $task_insert_q = "INSERT INTO evp_task (csv_name, status, user_id) VALUES ('$filename', 'hold', '$user_id')";
				  $db->insert($task_insert_q);
			 }
				 
			 $task_update = "UPDATE evp_task SET status = 'email_check' WHERE csv_name = '$filename' AND user_id = '$user_id' AND status = 'hold'";
			 if($db->update( $task_update ) === true){
				// $pid = mysqli_thread_id($db->link);  
				$csvdata_update = "UPDATE evp_email_list_metadata SET scan_status = 'processing' WHERE csv_file_name = '$filename' AND user_id = '$user_id'";
				$db->update($csvdata_update);
			 }
			  
			 /* if($task_email_check_c > 0){

				  // $task_insert = "INSERT INTO evp_task (csv_name, status, user_id) VALUES ('$filename', 'email_check', '$user_id')";

			  }
			  */
				  
			  $check_email = "SELECT `email_status`, `verification_response`, `mail_box`, `last_update`, `email_name` FROM evp_email_list elist 
								INNER JOIN evp_email_list_metadata e_meta
								ON e_meta.csv_file_name = elist.csv_file_name
								INNER JOIN evp_task e_task
								ON e_meta.csv_file_name = e_task.csv_name
								WHERE 
								elist.csv_file_name = '$filename' AND
								elist.user_id = '$user_id' AND
								e_meta.scan_status = 'processing' AND
								elist.email_status != 'Not Verify' AND
								elist.mail_box NOT IN ('exists','none','pending','retry') AND
								e_meta.check_mailbox = 'true' AND
								e_task.status = 'email_check'
								LIMIT $limit";
											  
//			  SELECT * FROM evp_email_list WHERE csv_file_name = '$filename' AND user_id = '$user_id' AND mail_box = 'pending' LIMIT $limit";

			  $email_st = $db->select($check_email);
			  
			  
			  // add the new evp_task for this user
			/*	  $task_insert = "INSERT INTO evp_task (csv_name, user_id) VALUES ('$filename', '$user_id')";
				  if($db->insert($task_insert) === true){
					// $pid = mysqli_thread_id($db->link);
					$csvdata_update = "UPDATE evp_email_list_metadata SET scan_status = 'processing' WHERE csv_file_name = '$filename' AND scan_status = 'completed' AND user_id = '$user_id'";
					$read_csvdata_update = $db->insert($csvdata_update);
				  }
				*/
	
			  $i = 0;
			  
			  $count_all_email = mysqli_num_rows( $email_st );
				
				$log->system_debug("ROWS COUNT: $count_all_email");


				if($count_all_email > 0){

						$log->system_debug($ic_imap_host.':'.$ic_imap_port);

				$log->system_debug('MAILBOX -> UPDATING WAITING LIST');
							
				/* Connecting Gmail server with IMAP */


			    $connection = imap_open('{'.$ic_imap_host.':'.$ic_imap_port.'/imap/ssl/novalidate-cert}INBOX', $ic_send_mail, $ic_smtp_pass) or die('Cannot connect to IMAP: ' . imap_last_error());

				$emailData = imap_search($connection, '');

				$log->system_debug("MAIL FOUND -> ". count($emailData) . print_r($emailData, true));

				  while($row = $email_st->fetch_assoc()){
					  
					 $status = $row['email_status'];
					 $verification_response = $row['verification_response'];
					 $mailbox_status = $row['mail_box'];
					 $last_update = $row['last_update'];
					 $dbtimestamp = strtotime($last_update);
					 $toemail = $row['email_name'];
					// $mailbox_found = 'true';
					//  $get_failed_email = 'false';
					 
					 $log->system_debug('MAILBOX -> LOOP Checking: ' . $toemail);
					 

				if($mailbox_status == 'waiting'){
						$email_ok = false;
						$errMsg_ok = false;
				if(!empty($emailData)){
					
					$log->system_debug('MAILBOX -> Email Data Found');
					
					foreach($emailData as $emailIdent){
						
						$overview = imap_fetch_overview($connection, $emailIdent, 0);

						$msg = imap_fetchbody($connection, $emailIdent, '');
												
					//	$err_msg = "Delivery Status Notification (Failure)|Delivery incomplete|Delay|BOUNCE-DELIVERY-FAILURE|Undeliverable|Email Delivery Failure|not found|delivery failure|No such user|Recipient address rejected|RecipientNotFound|550 Administrative prohibition|550 5.1.10|550 5.4.1|550 5.2.1|550 5.1.1|550 5.2.1|550 5.7.1|550 5.7.133|554 5.4.14";
					
						$err_msg = "$ic_smtp_errors|";
				
						if(preg_match("/\b$toemail\b/i", $msg, $match)) {
								$email_ok = true;
								$get_failed_email = $match[0];
								$log->system_debug("[Email Matched]: ". $match[0]);
							if(preg_match("/\b($err_msg)\b/i", $msg, $match)) {
								$errMsg_ok = true;
								$log->system_debug("[Err Matched]: ". $match[0]);
								imap_delete($connection,$emailIdent);
								imap_expunge($connection);
							} else {
								$errMsg_ok = false;
							}
						} else {
							$email_ok = false;
						}
						
						if(($email_ok === true) && ($errMsg_ok === true)) {
							$mailbox_found = 'false';
							$log->system_debug("[Mailbox Not Found]: ". $toemail);
						}

					} // End foreach

				}

					if(($email_ok === false) && ($errMsg_ok === false)) {
						$get_failed_email = 'false';
						$mailbox_found = 'true';
						$log->system_debug("[Mailbox Found]: ". $toemail);
					}

					$log->system_debug("[MAILBOX CHECK]: $toemail -> $mailbox_found");

					if(($get_failed_email == $toemail) && ($mailbox_found == 'false')){
								$log->system_debug("MAILBOX -> NOT FOUND: $toemail");
								$status = array();
								$status['status'] = 'Invalid';
								$status['safe_to_send'] = 'No';
								$status['v_response'] = 'Undeliverable';
								$mx_response = 'Mailbox do not exists';
								$status['email_score'] = '0';
								$status['bounce_type'] = 'hard';
								$update_mailbox = "UPDATE evp_email_list SET
												  email_status = '{$status['status']}', 
												  safe_to_send = '{$status['safe_to_send']}', 
												  verification_response = '{$status['v_response']}',
												  mx_response = '$mx_response',
												  score = '{$status['email_score']}', 
												  bounce_type = '{$status['bounce_type']}', 
												  mail_box = 'none', 
												  last_update = '$dateTime'
												  WHERE csv_file_name = '$filename' AND mail_box = 'waiting' AND email_name = '$toemail' AND user_id = '$user_id'";
								$db->update($update_mailbox);
								
								$log->system_debug("MAILBOX -> NOT FOUND DATA: $mx_response");
								$log->system_debug("UPDATE VALID TO INVALID: SRC -> $get_failed_email ORG -> $toemail");
								
					} elseif(($get_failed_email == 'false') && ($mailbox_found == 'true')){
					
						$log->system_debug("MAILBOX -> FOUND [IMAP] : $toemail");

						if(($status == 'Invalid') && ($verification_response != 'Smtp connection Failed')){
							$status = array();
							$status['status'] = 'Valid';
							$status['safe_to_send'] = 'Yes';
							$status['v_response'] = 'Deliverable';
							$mx_response = '250 Accepted';
							$status['email_score'] = '1';
							$status['bounce_type'] = '';
							$update_mailbox = "UPDATE evp_email_list SET
										  email_status = '{$status['status']}', 
										  safe_to_send = '{$status['safe_to_send']}', 
										  verification_response = '{$status['v_response']}',
										  mx_response = '$mx_response',
										  score = '{$status['email_score']}', 
										  bounce_type = '{$status['bounce_type']}', 
										  mail_box = 'exists', 
										  last_update = '$dateTime'
										  WHERE csv_file_name = '$filename' AND mail_box = 'waiting' AND email_name = '$toemail' AND user_id = '$user_id'";
										  
										  $log->system_debug("UPDATE INVALID TO VALID: $toemail");
						} else {
										  $log->system_debug("UPDATE VALID TO VALID: $toemail");
							$update_mailbox = "UPDATE evp_email_list SET mail_box = 'exists', last_update = '$dateTime' WHERE csv_file_name = '$filename' AND email_name = '$toemail' AND mail_box = 'waiting' AND user_id = '$user_id'";
						}	
						$db->update($update_mailbox);
					}				

				} // waiting check
				
					$i++;
				  } // whileloop
				  
				imap_close($connection);
				$log->system_debug("MAILBOX -> IMAP CLOSE");
				
				  $email_st->free();
				}
				
				
				if(!($count_all_email > 0)) {
					// count valid and invalid results from selected csv_file_name
					$csv_file_info = "SELECT email_status, count(*) as cnt FROM evp_email_list WHERE csv_file_name = '$filename' AND user_id = '$user_id' GROUP BY email_status";
					$csv_info = $db->select($csv_file_info );
					$counts = array();
					$counts['Valid'] = 0;
					$counts['Invalid'] = 0;
					$counts['Catch All'] = 0;
					while ($row = $csv_info->fetch_assoc()) {
						$counts[$row['email_status']] = $row['cnt'];
					}
					
					$log->system_debug('Valid -> ' .$counts['Valid']. '  Invalid -> ' .$counts['Invalid']. '  Catch All -> ' .$counts['Catch All']);
					
					// update evp_email_list_metadata counts & check_mailbox from selected csv_file_name
					$update_mailbox = "UPDATE evp_email_list_metadata SET check_mailbox = NULL, valid = '".$counts['Valid']."', invalid = '".$counts['Invalid']."', catch_all = '".$counts['Catch All']."' WHERE csv_file_name = '$filename' AND check_mailbox = 'true' AND user_id = '$user_id'";
					if($db->update($update_mailbox) === true){
						global $count_valid, $count_invalid, $count_catchall, $count_unknown, $count_skipped, $count_syntax_error, $count_disposable, $count_free_account, $count_role_account, $scan_time, $total_email;
						$csv_file_info = "SELECT * FROM evp_email_list_metadata WHERE csv_file_name = '$filename' AND check_mailbox IS NULL AND user_id = '$user_id'";
						$csv_info = $db->select( $csv_file_info );
						$csv_data = $csv_info->fetch_assoc();
						$count_valid = $csv_data['valid'];
						$count_invalid = $csv_data['invalid'];
						$count_catchall = $csv_data['catch_all'];
						$count_unknown = $csv_data['unknown'];
						$count_skipped = $csv_data['skipped'];
						$count_syntax_error = $csv_data['syntax_error'];
						$count_disposable = $csv_data['disposable'];
						$count_free_account = $csv_data['free_account'];
						$count_role_account = $csv_data['role_account'];
						$scan_time = $csv_data['scan_time'];
						$total_email =  $csv_data['total'];
						// $check_mailbox =  $csv_data['check_mailbox'];
						
						// $task_delete_current = "DELETE FROM evp_task WHERE csv_name = '$filename' AND user_id = '$user_id' AND status = 'email_check'";
						// $read_task_delete = $db->delete( $task_delete_current );
					//	if($db->delete($task_delete_current) === true){
							require_once('../functions/class.mailsend.php');
							$sendmail = new SendMail;
							$sendmail->scan_done();
							$log->system_debug("MAILBOX -> UPDATED EMAIL SENT");
					//	}
					}
					$log->system_debug("MAILBOX -> DISABLE: INBOX CHECKER");
				} else {
					// run check_mailbox func again
					check_mailbox();
				}

			}
			
			check_mailbox();
    }
	
} else {
	exit();
};

