<?php

namespace Drupal\materio_migrate\Plugin\migrate\source;

use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\d7\FieldableEntity;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\Core\State\StateInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Locale\CountryManagerInterface;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberUtil;
use libphonenumber\PhoneNumberFormat;
/**
 * Drupal 7 node source from database.
 *
 * @MigrateSource(
 *   id = "d7_user_profile_customer",
 *   source_module = "profile2"
 * )
 */
class D7UserProfileCustomer extends FieldableEntity {

  /**
   * Phone Number util.
   *
   * @var \libphonenumber\PhoneNumberUtil
   */
  public $phoneUtils;

  /**
   * Country Manager service.
   *
   * @var \Drupal\Core\Locale\CountryManagerInterface
   */
  public $countryManager;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, StateInterface $state, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, CountryManagerInterface $country_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration, $state, $entity_manager);
    $this->moduleHandler = $module_handler;
    $this->phoneUtils = PhoneNumberUtil::getInstance();
    $this->countryManager = $country_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $migration,
      $container->get('state'),
      $container->get('entity.manager'),
      $container->get('module_handler'),
      $container->get('country_manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    // Select node in its last revision.
    $query = $this->select('uc_orders', 'uco')
      ->fields('uco', [
        'uid',
        // 'order_id',
        // 'billing_first_name',
        // 'billing_last_name',
        // 'billing_phone',
        // 'billing_company',
        // 'billing_street1',
        // 'billing_street2',
        // 'billing_city',
        // 'billing_zone',
        // 'billing_postal_code',
        // 'billing_country'
      ])
      ->groupBy('uco.uid')
      // ->groupBy('uco.order_id')
      // ->groupBy('uco.billing_first_name')
      // ->groupBy('uco.billing_last_name')
      // ->groupBy('uco.billing_phone')
      // ->groupBy('uco.billing_company')
      // ->groupBy('uco.billing_street1')
      // ->groupBy('uco.billing_street2')
      // ->groupBy('uco.billing_city')
      // ->groupBy('uco.billing_zone')
      // ->groupBy('uco.billing_postal_code')
      // ->groupBy('uco.billing_country')
      ->condition('order_status', 'completed')
      ->orderBy('modified', 'DESC');
    $query->innerJoin('users', 'u', 'uco.uid = u.uid');
    
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    // $order_id = $row->getSourceProperty('order_id');
    $uid = $row->getSourceProperty('uid');
    drush_print("\n".'-- '.$uid);
    $query = $this->select('uc_orders', 'uco')
      ->fields('uco', [
        'uid',
        'order_id',
        'billing_first_name',
        'billing_last_name',
        'billing_phone',
        'billing_company',
        'billing_street1',
        'billing_street2',
        'billing_city',
        'billing_zone',
        'billing_postal_code',
        'billing_country',
        'modified'
      ])
      ->condition('order_status', 'completed')
      ->condition('uco.uid', $uid)
      ->orderBy('modified', 'ASC');
    $query->innerJoin('users', 'u', 'uco.uid = u.uid');
    $query->fields('u',['mail']);
  
      // TODO filter by user active
    $user_orders = $query->execute()->fetchAll();

    $fields = [];
    foreach ($user_orders as $order) {
      foreach ($order as $field_name => $field){
        if ($field !== '') {
          $fields[$field_name] = $field;
        }
      }
    }

    if (count($user_orders) > 1){
      drush_print(print_r($user_orders, true));
      drush_print(print_r($fields, true));
    }

    foreach ($fields as $field_name => $field){
      $row->setSourceProperty($field_name, $field);
    }
    // // convert phone field with libphonenumber
    // $phone = $row->getSourceProperty('billing_phone');
    // if(isset($phone[0]['number']) && !empty($phone[0]['number'])){
    //   $national_number = $phone[0]['number'];
    //   $region = strtoupper($phone[0]['country_codes']);
    //   // isValidRegionCode($regionCode)
    //   if($this->phoneUtils->isPossibleNumber($national_number, $region)){
    //     $number = $this->phoneUtils->parse($national_number, $region);
    //     $row->setSourceProperty('billing_phone', $this->phoneUtils->format($number, PhoneNumberFormat::E164));
    //   }else{
    //     // add bad phone number to memo field
    //     $memo .= "#migration : invalid phone number: ".$national_number.' region: '.$region."\n";
    //     drush_print('WARNING: phone number invalide; number: '.$national_number.' region: '.$region);
    //   }
    // }

    // country_zone
    $query = $this->select('uc_countries', 'ucc')
      ->condition('ucc.country_id', $row->getSourceProperty('billing_country'))
      ->fields('ucc', [
        'country_id',
        'country_name',
        'country_iso_code_2',
        'country_iso_code_3',]);
    $country = array_shift($query->execute()->fetchAll());
    drush_print(print_r($country, true));
    $row->setSourceProperty('billing_country', $country['country_iso_code_2']);
    

    // billing_zone
    $query = $this->select('uc_zones', 'ucz')
      ->condition('ucz.zone_id', $row->getSourceProperty('billing_zone'))
      ->fields('ucz', [
        'zone_code',
        'zone_name',
      ]);
    $zone = array_shift($query->execute()->fetchAll());
    drush_print(print_r($zone, true));
    $row->setSourceProperty('billing_zone', $zone['zone_code']);
    
    

    // get TVA from old adhérent profil
    $query = $this->select('profile', 'p')
      ->fields('p', [
        'pid',
        'type',
        'uid',
        'label',
        'created',
        'changed',
      ])
      ->condition('uid', $uid)
      ->condition('type', 'adherent')
      ->orderBy('changed');
    $profils = $query->execute()->fetchAll();

    if(count($profils)){
      $profil = array_shift($profils);
      // Get Field API field values.
      // foreach ($this->getFields('profile2', $profil['type']) as $field_name => $field) {
      //   // drush_print($field_name);
      //   $value = $this->getFieldValues('profile2', $field_name, $profil['pid']);
      //   $row->setSourceProperty($field_name, $value);
      // }
      $vat = $this->getFieldValues('profile2', 'field_vat_number_intra_ce', $profil['pid']);
      $row->setSourceProperty('field_vat_number_intra_ce', $vat);
    }


    // record migration errors in field_memo
    if(isset($memo)){
      $field_memo = $row->getSourceProperty('field_memo');
      $field_memo[0]['value'] .= "\n".$memo;
      $row->setSourceProperty('field_memo', $field_memo);
    }

    return parent::prepareRow($row);
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'order_id' => $this->t('Order ID'),
      'uid' => $this->t('User id'),
      'billing_first_name' => $this->t('First name'),
      'billing_last_name' => $this->t('Last name'),
      'billing_phone' => $this->t('Phone'),
      'billing_company' => $this->t('Company'),
      'billing_street1' => $this->t('Street 1'),
      'billing_street2' => $this->t('Street 2'),
      'billing_city' => $this->t('City'),
      'billing_zone' => $this->t('Zone'),
      'billing_postal_code' => $this->t('Postal code'),
      'billing_country' => $this->t('Country'),
    ];
    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['uid']['type'] = 'integer';
    $ids['uid']['alias'] = 'p';
    return $ids;
  }

}
