<?php

require_once("includes/migration.php");

if (isset($_POST['charid']) && isset($_POST['name'])) {
  $new_accid    = (int)$account['id'];
  $old_charid   = (int)$_POST['charid'];
  $new_charid   = getMaxCharid() + 1;
  $new_charname = strtolower($_POST['name']);
  $new_charname = ucfirst($new_charname);

  if (in_array($new_charname, $badnames)) {
    echo getPanel("danger","Failed","Character name is not allowed!");
  }

  elseif (getCharacterByName($new_charname) != 'empty') {
    echo getPanel("danger","Failed","Character name is taken!");
  }

  elseif (strlen($new_charname) < 3) {
    echo getPanel("danger","Failed","Character name is too short!");
  }

  elseif (strlen($new_charname) > 15) {
    echo getPanel("danger","Failed","Character name is too long!");
  }

  elseif (!ctype_alpha($new_charname)) {
    echo getPanel("danger","Failed","Character name is not valid!");
  }

  // Verify this character is actually linked to this account
  elseif (!WingsMigration::isAccountLinkedToChar($new_accid, $old_charid)) {
    echo getPanel("danger","Failed","Unknown error");
  }

  else {
    $dblive = new PDO('mysql:host='.$configwrite['host'].':'.$configwrite['port'].';dbname='.$configwrite['name'].';charset=utf8mb4', $configwrite['user'], $configwrite['pass']);
    // $dblive->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

    $statement = $dblive->prepare("CALL `migrate_wings_char`(?, ?, ?, ?)");
    $statement->bindParam(1, $new_accid,  PDO::PARAM_INT);
    $statement->bindParam(2, $old_charid, PDO::PARAM_INT);
    $statement->bindParam(3, $new_charid, PDO::PARAM_INT);
    $statement->bindParam(4, $new_charname);

    if (!$statement->execute()) {
      watchdog($statement->errorInfo(),'SQL');
      echo getPanel("warning","Warning","Something didn't work");
    }
    else {
      echo getPanel("success","Success","Your character is now available on CatsEyeXI!");
    }
  }
}

?>
