<?php
/**
* Plugin Name:Email Confirmation
* Description: Send an email to the user with confirmation code and store form data in database until user confirms.
* Version: 1.0
* Author: Cedric Ruiz
**/
//if(! defined( 'ABSPATH' )) exit; // Exit if accessed directly
class EmailConfirmation
{
  const PREFIX = 'email-confirmation-';
  const OTPPREFIX = 'otp-confirmation-';

  public static function send($to, $subject, $message, $headers)
  {
    $token = sha1(uniqid());

    $oldData = get_option(self::PREFIX .'data') ?: array();
    $data = array();
    $data[$token] = $_POST;
    update_option(self::PREFIX .'data', array_merge($oldData, $data));

    wp_mail($to, $subject, sprintf($message, $token), $headers);
  }

  public static function check($token)
  {
    $data = get_option(self::PREFIX .'data');
    $userData = $data[$token];

    if (isset($userData)) {
      unset($data[$token]);
      update_option(self::PREFIX .'data', $data);
    }

    return $userData;
  }

  public static function sendOtp($to, $name, $subject, $message, $headers)
  {
    //$token = sha1(uniqid());
    $otp = rand ( 4125 , 9999);
    //$token = $otp .'-'.time();
    $token = $otp .'-'.$to;
    $oldData = get_option(self::OTPPREFIX .'data') ?: array();
    $data = array();
    $data[$token] = $_POST;
    update_option(self::OTPPREFIX .'data', array_merge($oldData, $data));
    wp_mail($to, $subject, sprintf($message,$name,$otp), $headers);
  }

  public static function checkOtp($otp,$email)
  {
    $data = get_option(self::OTPPREFIX .'data');
    $token = $otp.'-'.$email;
    $userData = $data[$token];
    if (isset($userData)) {
      unset($data[$token]);
      update_option(self::OTPPREFIX .'data', $data);
      return true;
    }
    return false;
  }
}

//global $EmailConfirmation;
//$EmailConfirmation = new EmailConfirmation();
//register_activation_hook( __FILE__,  array( 'EmailConfirmation', 'activate')  );
//register_deactivation_hook( __FILE__,  array( 'EmailConfirmation', 'deactivate')  );