<?php
// use Drupal\Core\Form\FormBuilder;
// use Drupal\Core\Url;
use \Drupal\Core\Link;
// use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityFormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\EntityOwnerInterface;


function materio_commerce_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_checkout_flow_multistep_default') {
      if ($form["#step_id"] == "review") {
        // $form['buttons']['continue']['#value'] = t('Desired Custom Text Here');
        $form['actions']['next']['#value'] = t('Place your order');
      }
  }
}

function materio_commerce_form_commerce_order_add_form_alter(&$form, &$form_state, $form_id) {
  $currentUser = \Drupal::currentUser();
  $roles = $currentUser->getRoles();
  if (in_array("admin", $roles)){
    $form['type']['#default_value'] = 'materio_order_type';
    $form['type']['#disabled'] = true;

    $form['customer']['uid']['#selection_handler'] = 'default:user_by_email';
  }
}

function materio_commerce_form_role_delegation_role_assign_form_alter(&$form, &$form_state, $form_id) {

  // /** @var \Drupal\Core\Entity\EntityFormInterface $form_object */
  // $form_object = $form_state->getFormObject();
  // if (!($form_object instanceof EntityFormInterface)) {
  //   // We're only interested in forms for an entity.
  //   return;
  // }
  // $entity = $form_object->getEntity();
  // $entity_type_id = $entity->getEntityTypeId();
  // if (!($entity instanceof EntityOwnerInterface) && $entity_type_id != 'user') {
  //   // We only act on entities that have an owner, and user entities.
  //   return;
  // }

  /** @var \Drupal\user\UserInterface $account */
  $account = $form_state->getBuildInfo()['args'][0];

  $license_storage = \Drupal::entityTypeManager()->getStorage('commerce_license');
  $licenses = $license_storage->loadByProperties(['uid' => $account->id()]);
  
  if ($licenses) {
    // reorganise licenses by role
    // and record by role if a license is active
    $licenses_by_role = [];
    foreach ($licenses as $lid => $license) {
      $licensed_role_id = $license->license_role->target_id;
      $licenses_by_role[$licensed_role_id]['licenses'][] = $license;
      $license_state = $license->getState()->getValue()['value'];
      if($license_state === 'active') {
        $licenses_by_role[$licensed_role_id]['license_active'] = true;
      }
    }
    // loop throught roles then licenses by role
    foreach ($licenses_by_role as $rid => $role_licenses) {
      $license_active = isset($role_licenses['license_active']) ? true : false;
      $description = "";
      if($license_active) {
        $form["account"]["role_change"][$rid]['#disabled'] = TRUE;
        $form["account"]["role_change"][$rid]['#default_value'] = TRUE;

        $description = t("This role is granted by a license. It cannot be removed manually.<br/>");
      }
      // reverse the licenses to display the last first
      $reversed_licenses = array_reverse($role_licenses['licenses']);
      foreach ($reversed_licenses as $license) {
        $license_state = $license->getState()->getValue()['value'];

        $product_variation = $license->getPurchasedEntity();
        $product = null;
        if ($product_variation){
          $product = $product_variation->getProduct();
        }

        $granted = $license->getGrantedTime();
        $expires = $license->getExpiresTime();

        $license_edit_url = $license->toUrl();
        $license_link = Link::fromTextAndUrl(t('edit license'), $license_edit_url);

        $order = $license->getOriginatingOrder();
        if ($order) {
          $order_url = $order->toUrl();
          $order_state = $order->get('state')->first()->getValue()['value'];
          $order_number = $order->get('order_number')->first()->getValue()['value'];
          $order_link = Link::fromTextAndUrl(t("order @num (@state)", array(
            '@num' => $order_number,
            '@state' => $order_state
          )), $order_url);

        }

        $description .= t("-- @product: @variation | license state: <b>@license_state</b> | granted: @granted | expires: @expires | @license_link | @order_link<br/>", array(
          '@product' => $product ? $product->getTitle() : t('no product'),
          '@variation' => $product_variation ? $product_variation->getTitle() : t('no variation'),
          '@license_state' => $license_state,
          '@granted' => date('d-m-Y', $granted),
          '@expires' => $expires === "0" ? 'never' : date('d-m-Y', $expires),
          '@license_link' => $license_link->toString(),
          '@order_link' => $order ? $order_link->toString() : t('no order')
        ));

      }
      $form["account"]["role_change"][$rid]['#description'] = $description;
    }
  }

}

function materio_commerce_form_user_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id !== 'user_form') return;

  // WE USE FORM OBJECT TO GET THE ENTITY instead of followings
  // $mail = $form['account']['mail']['#default_value'];
  // $user_storage = \Drupal::entityTypeManager()->getStorage('user');
  // $users = $user_storage->loadByProperties(['mail' => $mail]);
  // $user = reset($users);
  // $roles = $user->getRoles();


  /** @var \Drupal\Core\Entity\EntityFormInterface $form_object */
  $form_object = $form_state->getFormObject();
  if (!($form_object instanceof EntityFormInterface)) {
    // We're only interested in forms for an entity.
    return;
  }

  $entity = $form_object->getEntity();
  $entity_type_id = $entity->getEntityTypeId();
  if (!($entity instanceof EntityOwnerInterface) && $entity_type_id != 'user') {
    // We only act on entities that have an owner, and user entities.
    return;
  }

  $license_storage = \Drupal::entityTypeManager()->getStorage('commerce_license');
  $licenses = $license_storage->loadByProperties(['uid' => $entity->id()]);
  
  if ($licenses) {
    // reorganise licenses by role
    // and record by role if a license is active
    $licenses_by_role = [];
    foreach ($licenses as $lid => $license) {
      $licensed_role_id = $license->license_role->target_id;
      $licenses_by_role[$licensed_role_id]['licenses'][] = $license;
      $license_state = $license->getState()->getValue()['value'];
      if($license_state === 'active') {
        $licenses_by_role[$licensed_role_id]['license_active'] = true;
      }
    }
    
    // we need to validate the form as disabled cekbox are not sent on submit
    // as it remove the disabled roles
    $form["#validate"][] = 'materio_commerce_form_user_form_validate';
    // hidden licensed role will be re-injected in 'role_change' field values during our validate
    $form['licensed_roles'] = array(
      '#type'=>"container",
      '#tree' => true
    );
    // loop throught roles then licenses by role
    $form["role_change"]["widget"]['#options_attributes'] = [];
    foreach ($licenses_by_role as $rid => $role_licenses) {
      $license_active = isset($role_licenses['license_active']) ? true : false;
      $description = "";
      if($license_active) {
        $form["role_change"]["widget"][$rid]['#disabled'] = TRUE;
        // $form["role_change"][$rid]['#default_value'] = TRUE;

        $description = t("This role is granted by a license. It cannot be removed manually.<br/>");

        // record the role in hidden element, as disabled checkboxes are not posted
        // we'll re-establish the right values in validate function
        $form['licensed_roles'][$rid] = array(
          '#type' => 'hidden',
          '#value' => $rid
        );
      }
      // reverse the licenses to display the last first
      $reversed_licenses = array_reverse($role_licenses['licenses']);
      foreach ($reversed_licenses as $license) {
        $license_state = $license->getState()->getValue()['value'];

        $product_variation = $license->getPurchasedEntity();
        $product = null;
        if ($product_variation){
          $product = $product_variation->getProduct();
        }

        $granted = $license->getGrantedTime();
        $expires = $license->getExpiresTime();

        $license_edit_url = $license->toUrl();
        $license_link = Link::fromTextAndUrl(t('edit license'), $license_edit_url);

        $order = $license->getOriginatingOrder();
        if ($order) {
          // payments
          $payment_storage = \Drupal::entityTypeManager()->getStorage('commerce_payment');
          $payments = $payment_storage->loadByProperties(['order_id' => $order->id()]);
          if (!empty($payments)) {
            $first_payment = array_shift($payments);
            $gateway = $first_payment->get('payment_gateway')->first()->getValue()['target_id'];
          }

          // order info and link
          $order_url = $order->toUrl();
          $order_state = $order->get('state')->first()->getValue()['value'];
          // $order_number = $order->get('order_number')->first()->getValue()['value'];
          $order_link = Link::fromTextAndUrl(t("order (@gateway @state)", array(
            // '@num' => $order_number,
            '@state' => $order_state,
            '@gateway' => isset($gateway) ? $gateway : ''
          )), $order_url);
          
          // susbcriptions
          $susbcription_storage = \Drupal::entityTypeManager()->getStorage('commerce_subscription');
          $subsriptions = $susbcription_storage->loadByProperties(['initial_order' => $order->id()]);
          if (!empty($subsriptions)) {
            $first_subscription = array_shift($subsriptions);
            $subscription_url = $first_subscription->toUrl();
            $subscription_title = $first_subscription->getTitle();
            $subscription_state = $first_subscription->get('state')->first()->getValue()['value'];
            $subscription_payment_method_label = "none";
            if ( $subscription_payment_method = $first_subscription->getPaymentMethod() ){
              $subscription_payment_method_label = $subscription_payment_method->label()->render();
            }
            $subscription_link = Link::fromTextAndUrl(t("subscription @title @state [@pm_label]", array(
              '@title' => $subscription_title,
              '@state' => $subscription_state,
              '@pm_label' => $subscription_payment_method_label
            )), $subscription_url);          
          }
        }

        $description .= t("-- @product: @variation | license state: <b>@license_state</b> | granted: @granted | expires: @expires | @license_link | @subscription_link | @order_link<br/>", array(
          '@product' => $product ? $product->getTitle() : t('no product'),
          '@variation' => $product_variation ? $product_variation->getTitle() : t('no variation'),
          '@license_state' => $license_state,
          '@granted' => date('d-m-Y', $granted),
          '@expires' => $expires === "0" ? 'never' : date('d-m-Y', $expires),
          '@license_link' => $license_link->toString(),
          '@subscription_link' => isset($subscription_link) ? $subscription_link->toString() : t('no subscription'),
          '@order_link' => isset($order) ? $order_link->toString() : t('no order')
        ));

      }
      $form["role_change"]["widget"][$rid]['#description'] = $description;
    }
  }

}

function materio_commerce_form_user_form_validate($form, FormStateInterface &$form_state) {
  $values = $form_state->getValues();
  if (!empty($values['licensed_roles'])) {
    foreach ($values['licensed_roles'] as $rid => $value) {
      $values['role_change'][] = array("target_id"=>$value);
    }
    $form_state->setValues($values);
  }
}