<?php

global $dblive;
$dblive = new PDO('mysql:host='.$configwrite['host'].':'.$configwrite['port'].';dbname='.$configwrite['name'].';charset=utf8mb4', $configwrite['user'], $configwrite['pass']);

global $dbwings;
$dbwings = new PDO('mysql:host='.$config['host'].':'.$config['port'].';dbname='.$wings_dbname.';charset=utf8mb4', $config['user'], $config['pass']);

class WingsMigration
{
  public static $hash_secret = "aaEc56gP4998.dl&fi8592/aDgM$6cDe";

  public static function checkPassword($username, $password) {
    global $dbwings;

    $statement = $dbwings->prepare("SELECT password, salt FROM ww_accounts WHERE username = :username LIMIT 1");
    $statement->bindValue(':username', $username);

    if (!$statement->execute()) {
      watchdog($statement->errorInfo(), 'SQL');
      return false;
    }
    else {
      $row = $statement->fetch();
      $real_hash = $row[0];
      $salt = $row[1];

      $entered_hash = hash_pbkdf2("sha256", $password, $salt . WingsMigration::$hash_secret, 2048);

      if (strcasecmp($entered_hash, $real_hash) == 0) {
        return true;
      }
    }

    return false;
  }

  public static function blockMigration($username) {
    global $dblive;
    global $dbwings;

    $statement = $dbwings->prepare("SELECT id FROM ww_accounts WHERE username = :username");
    $statement->bindValue(':username', $username);

    if (!$statement->execute()) {
      watchdog($statement->errorInfo(), 'SQL');
      return true;
    }
    else {
      $row = $statement->fetch();

      if (empty($row)) {
        return true;
      }
      else {
        $accid = $row[0];

        $statement = $dblive->prepare("SELECT * FROM wings_accounts WHERE wings_accid = :accid");
        $statement->bindValue(':accid', $accid);

        if (!$statement->execute()) {
          watchdog($statement->errorInfo(), 'SQL');
          return true;
        }
        else {
          $result = $statement->fetch();

          // Account ID isn't being processed, so we allow migration
          return !empty($result);
        }
      }
    }
  }

  public static function countLinked($username, $password) {
    global $dbwings;

    // Reject if already being processed
    if (WingsMigration::blockMigration($username)) {
      return 0;
    }

    // Reject if password does not match
    if (!WingsMigration::checkPassword($username, $password)) {
      return 0;
    }

    $strSQL = "SELECT COUNT(*) FROM ww_chars INNER JOIN ww_contents ON ww_chars.content_id = ww_contents.content_id INNER JOIN ww_accounts ON ww_contents.account_id = ww_accounts.id WHERE ww_accounts.username = :username AND ww_accounts.status <> 2 AND ww_chars.world_id = 100";

    $statement = $dbwings->prepare($strSQL);
    $statement->bindValue(':username', $username);

    if (!$statement->execute()) {
      watchdog($statement->errorInfo(), 'SQL');
      return 0;
    }
    else {
      $result = $statement->fetchColumn();

      if (empty($result)) {
        return 0;
      }
      else {
        return $result;
      }
    }
  }

  public static function createWings($catseye_accid, $wings_accid) {
    global $dblive;

    $statement = $dblive->prepare("INSERT INTO wings_accounts (catseye_accid, wings_accid) VALUES (:catseye_accid, :wings_accid)");
    $statement->bindValue(':catseye_accid', $catseye_accid);
    $statement->bindValue(':wings_accid', $wings_accid);

   if (!$statement->execute()) {
      watchdog($statement->errorInfo(),'SQL');
      return false;
    }
    else {
      return true;
    }
  }

  public static function getWingsAccId($username, $password) {
    global $dbwings;

    // Reject if already being processed
    if (WingsMigration::blockMigration($username)) {
      return 0;
    }

    // Reject if password does not match
    if (!WingsMigration::checkPassword($username, $password)) {
      return 0;
    }

    $strSQL = "SELECT id FROM ww_accounts WHERE ww_accounts.username = :username AND ww_accounts.status <> 2";

    $statement = $dbwings->prepare($strSQL);
    $statement->bindValue(':username', $username);

    if (!$statement->execute()) {
      watchdog($statement->errorInfo(), 'SQL');
      return 0;
    }
    else {
      $row = $statement->fetch();

      if (empty($row)) {
        return 0;
      }
      else {
        return $row[0];
      }
    }
  }

  public static function getLinkedId($accid) {
    global $dblive;

    $statement = $dblive->prepare("SELECT wings_accid FROM wings_accounts WHERE catseye_accid = :catseye_accid");
    $statement->bindValue(':catseye_accid', $accid);

    if (!$statement->execute()) {
      watchdog($statement->errorInfo(), 'SQL');
      return 0;
    }
    else {
      $row = $statement->fetch();
      return $row ? $row[0] : -1;
    }
  }

  public static function getWingsList($accid) {
    global $dbwings;

    $wings_accid = WingsMigration::getLinkedId($accid);

    if ($wings_accid == -1) {
      return [];
    }

    $strSQL = "SELECT * FROM ww_chars JOIN char_stats ON ww_chars.character_id=char_stats.charid JOIN char_jobs ON ww_chars.character_id=char_jobs.charid LEFT JOIN char_look ON ww_chars.character_id = char_look.charid JOIN ww_contents ON ww_chars.content_id = ww_contents.content_id WHERE ww_contents.account_id=:accid AND ww_chars.world_id = 100 AND ww_chars.catseye_charid IS NULL";

    $statement = $dbwings->prepare($strSQL);
    $statement->bindValue(':accid', $wings_accid);

    if (!$statement->execute()) {
      watchdog($statement->errorInfo(),'SQL');
      return [];
    }
    else {
      return $statement->fetchAll();
    }
  }

  public static function nameAvailable($charname) {
    global $dblive;

    $statement = $dblive->prepare("SELECT charname FROM chars WHERE charname = :charname");  
    $statement->bindValue(':charname', $charname);

    if (!$statement->execute()) {
      watchdog($statement->errorInfo(),'SQL');
      return $nameUnavailable;
    }
    else {
      return empty($statement->fetchAll());
    }
  }

  public static function isAccountLinkedToChar($accid, $charid) {
    global $dblive;
    global $dbwings;

    $statement = $dblive->prepare("SELECT wings_accid FROM wings_accounts WHERE catseye_accid = :accid");
    $statement->bindValue(':accid', $accid);

    if (!$statement->execute()) {
      watchdog($statement->errorInfo(), 'SQL');

      // We can't verify this char belongs to this acc
      // So bail out and prevent the transfer...
      return true;
    }
    else {
      $row = $statement->fetch();

      if (empty($row)) {
        return true;
      }
      else {
        $wings_accid = $row[0];

        $statement = $dbwings->prepare("SELECT * FROM ww_chars JOIN ww_contents ON ww_chars.content_id = ww_contents.content_id WHERE ww_contents.account_id = :accid");
        $statement->bindValue(':accid', $wings_accid);

        if (!$statement->execute()) {
          watchdog($statement->errorInfo(), 'SQL');
          return true;
        }
        else {
          $result = $statement->fetch();
          return !empty($result);
        }
      }
    }
  }
}

?>
