<?php

/**
 * @file
 * Install, update and uninstall functions for the Basket module.
 */

use Drupal\Core\Database\Database;
use Drupal\Component\Serialization\Yaml;
use Drupal\basket\BasketInstall;
use Drupal\basket\BasketUninstall;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;

/**
 * Implements hook_install().
 */
function basket_install() {
  (new BasketInstall)->run();
}

/**
 * Implements hook_uninstall().
 */
function basket_uninstall() {
  (new BasketUninstall)->run();
}

/**
 * Implements hook_requirements().
 */
function basket_requirements($phase) {
  $requirements = [];
  if ($phase == 'runtime') {
    \Drupal::service('Basket')->getClass('Drupal\basket\Requirements')->info($requirements);
  }
  return $requirements;
}

/**
 * Implements hook_schema().
 */
function basket_schema() {
  $schema['basket'] = [
    'fields'        => [
      'id'            => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'sid'           => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => TRUE,
        'description'   => 'Unique User ID',
      ],
      'nid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => TRUE,
        'description'   => 'Item ID',
      ],
      'count'         => [
        'type'          => 'numeric',
        'precision'     => 22,
        'scale'         => 6,
        'not null'      => TRUE,
        'description'   => 'Quantity.',
      ],
      'add_time'      => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => TRUE,
        'description'   => 'Time to add / update to cart.',
      ],
      'all_params'    => [
        'type'          => 'text',
        'size'          => 'big',
        'not null'      => FALSE,
        'description'   => 'Additional parameters of the goods.',
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'sid'           => ['sid'],
      'nid'           => ['nid'],
      'add_time'      => ['add_time'],
      'all_params'    => [['all_params', 255]],
    ],
  ];
  $schema['basket_orders'] = [
    'fields'        => [
      'id'            => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'nid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => TRUE,
      ],
      'price'         => [
        'type'          => 'numeric',
        'precision'     => 10,
        'scale'         => 2,
        'not null'      => FALSE,
      ],
      'add_price'     => [
        'type'          => 'numeric',
        'precision'     => 10,
        'scale'         => 2,
        'not null'      => FALSE,
      ],
      'delivery_price' => [
        'type'          => 'numeric',
        'precision'     => 10,
        'scale'         => 2,
        'not null'      => FALSE,
      ],
      'goods'         => [
        'type'          => 'numeric',
        'precision'     => 22,
        'scale'         => 6,
      ],
      'currency'      => [
        'type'          => 'int',
        'size'          => 'big',
      ],
      'status'        => [
        'type'          => 'int',
        'size'          => 'big',
      ],
      'fin_status'    => [
        'type'          => 'int',
        'size'          => 'big',
      ],
      'pay_price'     => [
        'type'          => 'numeric',
        'precision'     => 10,
        'scale'         => 2,
        'not null'      => FALSE,
      ],
      'pay_currency'  => [
        'type'          => 'int',
        'size'          => 'big',
      ],
      'first_view_uid' => [
        'type'          => 'int',
        'size'          => 'big',
      ],
      'is_delete'     => [
        'type'          => 'int',
        'not null'      => FALSE,
        'description'   => 'Is delete order',
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'nid'           => ['nid'],
      'price'         => ['price'],
      'goods'         => ['goods'],
      'currency'      => ['currency'],
      'status'        => ['status'],
      'is_delete'     => ['is_delete'],
    ],
  ];
  $schema['basket_orders_delivery'] = [
    'fields'        => [
      'id'            => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'nid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => TRUE,
        'description'   => 'Delivery NID',
      ],
      'did'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => FALSE,
        'description'   => 'Delivery ID',
      ],
      'address'       => [
        'type'          => 'text',
        'size'          => 'big',
        'not null'      => FALSE,
        'description'   => 'Delivery address info',
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'nid'           => ['nid'],
      'did'           => ['did'],
    ],
  ];
  $schema['basket_orders_payment'] = [
    'fields'       => [
      'id'           => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'nid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => TRUE,
        'description'   => 'Payment NID',
      ],
      'pid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => FALSE,
        'description'   => 'Payment ID',
      ],
      'payInfo'       => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => FALSE,
        'description'   => 'Payment info',
      ],
      'payUrl'        => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => FALSE,
        'description'   => 'Payment redirect url',
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'nid'           => ['nid'],
      'pid'           => ['pid'],
    ],
  ];
  $schema['basket_orders_item'] = [
    'fields'        => [
      'id'            => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'nid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => TRUE,
        'description'   => 'Product ID',
      ],
      'order_nid'     => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => TRUE,
        'description'   => 'Order ID',
      ],
      'price'         => [
        'type'          => 'numeric',
        'precision'     => 10,
        'scale'         => 2,
        'not null'      => FALSE,
        'description'   => 'Product price',
      ],
      'count'         => [
        'type'          => 'numeric',
        'precision'     => 22,
        'scale'         => 6,
        'description'   => 'Product count',
      ],
      'fid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => FALSE,
        'description'   => 'Product image ID',
      ],
      'params'        => [
        'type'          => 'text',
        'size'          => 'big',
        'not null'      => FALSE,
      ],
      'params_html'   => [
        'type'          => 'text',
        'size'          => 'big',
        'not null'      => FALSE,
      ],
      'add_time'      => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => FALSE,
        'description'   => 'Time to add / update to cart.',
      ],
      'node_fields'   => [
        'type'          => 'text',
        'size'          => 'big',
        'not null'      => FALSE,
        'description'   => 'Product node fields',
      ],
      'discount'      => [
        'type'          => 'text',
        'size'          => 'big',
        'not null'      => FALSE,
        'description'   => 'Product discount info',
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'nid'           => ['nid'],
      'order_nid'     => ['order_nid'],
      'price'         => ['price'],
      'count'         => ['count'],
      'fid'           => ['fid'],
    ],
  ];
  $schema['basket_orders_export'] = [
    'fields'        => [
      'id'            => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'uid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => TRUE,
        'description'   => 'User ID',
      ],
      'data'          => [
        'type'          => 'text',
        'size'          => 'big',
        'not null'      => FALSE,
        'description'   => 'Export',
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'uid'           => ['uid'],
    ],
  ];
  $schema['basket_terms'] = [
    'fields'        => [
      'id'            => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'type'          => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => TRUE,
      ],
      'name'          => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => TRUE,
      ],
      'color'         => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => FALSE,
      ],
      'default'       => [
        'type'          => 'int',
        'not null'      => FALSE,
      ],
      'weight'        => [
        'type'          => 'int',
        'not null'      => FALSE,
      ],
      'delivery_sum'  => [
        'type'          => 'numeric',
        'precision'     => 10,
        'scale'         => 2,
        'not null'      => FALSE,
        'description'   => 'Delivery sum',
      ],
      'delivery_currency' => [
        'type'          => 'int',
        'not null'      => FALSE,
        'description'   => 'Delivery currency',
      ],
      'description'   => [
        'type'          => 'blob',
        'size'          => 'big',
        'not null'      => FALSE,
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'type'          => ['type'],
      'name'          => ['name'],
      'default'       => ['default'],
      'weight'        => ['weight'],
    ],
  ];
  $schema['basket_currency'] = [
    'fields'        => [
      'id'            => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'name'          => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => TRUE,
      ],
      'name_prefix'   => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => FALSE,
      ],
      'iso'           => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => TRUE,
      ],
      'rate'          => [
        'type'          => 'numeric',
        'precision'     => 10,
        'scale'         => 5,
        'not null'      => FALSE,
      ],
      'locked'        => [
        'type'          => 'int',
        'not null'      => FALSE,
      ],
      'default'       => [
        'type'          => 'int',
        'not null'      => FALSE,
      ],
      'weight'        => [
        'type'          => 'int',
        'not null'      => FALSE,
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'name'          => ['name'],
      'rate'          => ['rate'],
      'weight'        => ['weight'],
    ],
  ];
  $schema['basket_node_types'] = [
    'fields'        => [
      'id'            => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'type'          => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => TRUE,
      ],
      'image_field'   => [
        'type'          => 'varchar',
        'length'        => 512,
        'not null'      => FALSE,
      ],
      'price_field'   => [
        'type'          => 'varchar',
        'length'        => 512,
        'not null'      => FALSE,
      ],
      'count_field'   => [
        'type'          => 'varchar',
        'length'        => 512,
        'not null'      => FALSE,
      ],
      'extra_fields'  => [
        'type'          => 'blob',
        'size'          => 'big',
        'not null'      => FALSE,
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'type'          => ['type'],
    ],
  ];
  $schema['basket_user_percent'] = [
    'fields'        => [
      'id'            => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'uid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => TRUE,
        'description'   => 'User ID',
      ],
      'percent'       => [
        'type'          => 'int',
        'not null'      => FALSE,
        'description'   => 'User percent',
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'uid'           => ['uid'],
      'percent'       => ['percent'],
    ],
  ];
  $schema['basket_node_delete'] = [
    'fields'        => [
      'id'            => [
        'type'          => 'serial',
        'not null'      => TRUE,
      ],
      'nid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => TRUE,
        'description'   => 'Product ID',
      ],
      'uid'           => [
        'type'          => 'int',
        'size'          => 'big',
        'not null'      => TRUE,
        'description'   => 'User ID',
      ],
      'delete_time'   => [
        'type'          => 'varchar',
        'length'        => 255,
        'not null'      => FALSE,
      ],
    ],
    'primary key'   => ['id'],
    'indexes'       => [
      'nid'           => ['nid'],
      'uid'           => ['uid'],
    ],
  ];
  return $schema;
}

/**
 * Table "basket_currency" add column "name_prefix".
 */
function basket_update_8001() {
  $schema = Database::getConnection()->schema();
  $schema->addField('basket_currency', 'name_prefix', [
    'type'          => 'varchar',
    'length'        => 255,
    'not null'      => FALSE,
  ]);
}

/**
 * Table "basket_terms" add columns "delivery_sum" and "delivery_currency".
 */
function basket_update_8002() {
  $schema = Database::getConnection()->schema();
  $schema->addField('basket_terms', 'delivery_sum', [
    'type'          => 'numeric',
    'precision'     => 10,
    'scale'         => 2,
    'not null'      => FALSE,
    'description'   => 'Delivery sum',
  ]);
  $schema->addField('basket_terms', 'delivery_currency', [
    'type'          => 'int',
    'not null'      => FALSE,
    'description'   => 'Delivery currency',
  ]);
}

/**
 * Table "basket_orders" add columns "delivery_sum".
 */
function basket_update_8003() {
  $schema = Database::getConnection()->schema();
  $schema->addField('basket_orders', 'delivery_price', [
    'type'          => 'numeric',
    'precision'     => 10,
    'scale'         => 2,
    'not null'      => FALSE,
  ]);
}

/**
 * Table "basket_orders_item" add columns "params_html".
 */
function basket_update_8004() {
  $schema = Database::getConnection()->schema();
  $schema->addField('basket_orders_item', 'params_html', [
    'type'          => 'text',
    'size'          => 'big',
    'not null'      => FALSE,
  ]);
}

/**
 * Table "basket_orders" add columns "pay_price" && "pay_currency".
 */
function basket_update_8005() {
  $schema = Database::getConnection()->schema();
  $schema->addField('basket_orders', 'pay_price', [
    'type'          => 'numeric',
    'precision'     => 10,
    'scale'         => 2,
    'not null'      => FALSE,
  ]);
  $schema->addField('basket_orders', 'pay_currency', [
    'type'          => 'int',
    'size'          => 'big',
  ]);
}

/**
 * Table "basket_currency" change column "rate".
 */
function basket_update_8006() {
  $schema = Database::getConnection()->schema();
  $schema->changeField('basket_currency', 'rate', 'rate', [
    'type'          => 'numeric',
    'precision'     => 10,
    'scale'         => 5,
    'not null'      => FALSE,
  ], []);
}

/**
 * Table "basket_terms" add column "description".
 */
function basket_update_8007() {
  $schema = Database::getConnection()->schema();
  $schema->addField('basket_terms', 'description', [
    'type'          => 'blob',
    'size'          => 'big',
    'not null'      => FALSE,
  ]);
}

/**
 * Changing the settings.
 */
function basket_update_8008() {
  $config = \Drupal::configFactory()->getEditable('views.view.cart_goods');
  if (!empty($config)) {
    $displays = $config->get('display');
    if (!empty($displays)) {
      foreach ($displays as &$display) {
        $display['display_options']['rendering_language'] = '***LANGUAGE_language_interface***';
      }
    }
    $config->set('display', $displays);
    $config->save();
  }
}

/**
 * Changing template settings.
 */
function basket_update_8009() {
  if (empty(\Drupal::service('Basket')->getSettings('templates', 'order_view_info'))) {
    $ymlFile = drupal_get_path('module', 'basket') . '/config/install/basket.setting.templates.yml';
    if (file_exists($ymlFile)) {
      $ymlFile = Yaml::decode(file_get_contents($ymlFile));
      if (!empty($ymlFile['order_view_info'])) {
        \Drupal::service('Basket')->setSettings('templates', 'order_view_info', $ymlFile['order_view_info']);
        drupal_flush_all_caches();
      }
    }
  }
}

/**
 * Changing type of count field in database.
 */
function basket_update_8010() {
  $schema = Database::getConnection()->schema();
  $schema->changeField('basket', 'count', 'count', [
    'type'          => 'numeric',
    'precision'     => 22,
    'scale'         => 2,
    'not null'      => TRUE,
    'description'   => 'Quantity.',
  ]);
  $schema->changeField('basket_orders_item', 'count', 'count', [
    'type'          => 'numeric',
    'precision'     => 22,
    'scale'         => 2,
    'description'   => 'Product count',
  ]);
}

/**
 * Create table "basket_node_delete".
 */
function basket_update_8011() {
  $schema = Database::getConnection()->schema();
  if (!$schema->tableExists('basket_node_delete')) {
    $specs = basket_schema();
    $schema->createTable('basket_node_delete', $specs['basket_node_delete']);
  }
}

/**
 * Changing type of count field in database.
 */
function basket_update_8012() {
  $schema = Database::getConnection()->schema();
  $schema->changeField('basket', 'count', 'count', [
    'type'          => 'numeric',
    'precision'     => 22,
    'scale'         => 6,
    'not null'      => TRUE,
    'description'   => 'Quantity.',
  ]);
  $schema->changeField('basket_orders_item', 'count', 'count', [
    'type'          => 'numeric',
    'precision'     => 22,
    'scale'         => 6,
    'description'   => 'Product count',
  ]);
}

/**
 * Changing type of goods field in database.
 */
function basket_update_8013() {
  $schema = Database::getConnection()->schema();
  $schema->changeField('basket_orders', 'goods', 'goods', [
    'type'          => 'numeric',
    'precision'     => 22,
    'scale'         => 6,
  ]);
}

/**
 * Changing the currency column for fields "basket_price_field"
 */
function basket_update_8014() {
  $manager = \Drupal::entityDefinitionUpdateManager();
  $fieldMap = \Drupal::service('entity_field.manager')->getFieldMapByFieldType('basket_price_field');
  $schema = Database::getConnection()->schema();
  foreach ($fieldMap as $entityTypeId => $fields) {
    foreach (array_keys($fields) as $fieldName) {
      $fieldStorageDefinition = $manager->getFieldStorageDefinition($fieldName, $entityTypeId);
      $storage = \Drupal::entityTypeManager()->getStorage($entityTypeId);
      if ($storage instanceof SqlContentEntityStorage) {
        $tableMapping = $storage->getTableMapping([
          $fieldName => $fieldStorageDefinition,
        ]);
        $tableNames = $tableMapping->getDedicatedTableNames();
        $columns = $tableMapping->getColumnNames($fieldName);
        foreach ($tableNames as $tableName) {
          $fieldSchema = $fieldStorageDefinition->getSchema();
          if($schema->tableExists($tableName) && $schema->fieldExists($tableName, $columns['currency'])) {
            $schema->changeField($tableName, $columns['currency'], $columns['currency'], [
              'type'      => 'int',
              'size'      => 'normal',
              'not null'  => FALSE,
            ]);
          }
        }
      }
    }
  }
}

/**
 * Adding a new twig template.
 */
function basket_update_8015() {
  drupal_flush_all_caches();
}
