<?php

namespace Dolphy\Plugin\Security;

use Com\Tecnick\Barcode\Barcode;
use Com\Tecnick\Barcode\Exception as BarcodeException;
use Dolphy\Plugin\Exceptions\Exception;
use Dolphy\Plugin\Helpers\Crypto;
use Dolphy\Plugin\Helpers\DB;
use Exception as GlobalException;
use PHPGangsta_GoogleAuthenticator;
use WP_User;

require_once DOLPHY_VENDOR.'/PHPGangsta/GoogleAuthenticator.php';

final class TwoFABackup {

  final public static function table() {
    return DB::tbl('2fa_backup');
  }

  public static function hash($data) {
    return hash('sha256', $data);
  }

  public static function rand($length = 16) {
    if (!is_int($length)) $length = 16;
    $bytes = random_bytes(floor($length/2));
    return bin2hex($bytes);
  }

  public static function genarate($count = 5) {
    $codes = array();

    for ($i = 0; $i < $count; $i++) {
      $code = self::rand();

      for ($p = 3; $p >= 1; $p--) {
        $code = substr_replace($code, ' ', $p * 4, 0);
      }

      $codes[] = $code;
    }

    return $codes;
  }

  public static function save($userId, array $codes) {
    global $wpdb;

    self::clear($userId);

    $table = self::table();
    $query = "INSERT INTO {$table} (`userId`, `code`) VALUES ";
    $values = array();

    foreach ($codes as $code) {
      $code = str_replace(' ', '', $code);
      $code = self::hash($code);
      $values[] = $wpdb->prepare("(%s, %s)", $userId, $code);
    }

    if (!count($values)) {
      throw new Exception('No Backup code found!');
    }

    $query .= implode(', ', $values);
    $wpdb->query($query);
  }

  public static function verify($userId, $code) {
    //
  }

  public static function clear($userId) {
    //
  }

  public static function remove($id) {
    //
  }

}
