<?php

namespace Dolphy\Plugin\Security;

use Dolphy\Plugin\Core\BaseTable;
use Dolphy\Plugin\Exceptions\Exception;
use Dolphy\Plugin\Helpers\DB;
use Dolphy\Plugin\Helpers\User;
use WP_User;

final class DPLC extends BaseTable {

  const TABLE = 'dplc';

  public static function findByCode($code) {
    return self::findBy('code', $code);
  }

  public static function generate(WP_User $user) {
    $data = array($user->ID, time());
    return hash('sha256', implode('|||',$data));;
  }

  public static function create($userId, $remember = false, $secure = false) {
    global $wpdb;

    if (!is_bool($remember)) $remember = false;

    if (!($user = User::findBy('id', $userId))) {
      throw new Exception('No such user');
    }

    self::insert(array(
      'userId' => $user->ID,
      'code' => self::generate($user),
      'remember' => $remember,
      'secure' => $secure
    ));

    if ($wpdb->insert_id === false) {
      throw new Exception('Unable to create DPLC. Please try again later.');
    }

    return self::findBy('id', $wpdb->insert_id);
  }

  public static function removeBy($field, $value) {
    self::delete(array($field => $value));
  }

}
