<?php

namespace Drupal\azure_ad\Form;

use Drupal\azure_ad\Helper\moAzureADHelper;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user_provisioning\Form\MoAuditsAndLogs;
use Drupal\user_provisioning\Helpers\moUserProvisioningAudits;

/**
 * Form for displaying and managing Azure audit logs.
 */
class MoAzureAuditLogs extends FormBase {
  /**
   * User provisioning audits.
   *
   * @var \Drupal\user_provisioning\Helpers\moUserProvisioningAudits
   */
  private moUserProvisioningAudits $audits;

  /**
   * Constructor for MoAzureAuditLogs.
   */
  public function __construct() {
    $this->audits = new moUserProvisioningAudits();
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'azure_ad_audit_logs_form';
  }

  /**
   * Get the form ID.
   *
   * @return array
   *   The form ID.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['azure_audits_header_style'] = [
      '#markup' => $this->t('<div class="mo_azure_header_container_step1">'),
    ];

    $form['azure_audit_logs_clear_logs'] = [
      '#type' => 'submit',
      '#value' => $this->t('Clear logs'),
      '#limit_validation_errors' => [],
      '#submit' => ['::clearLogs'],
      '#attributes' => ['class' => ['button--danger']],
      '#prefix' => '<div class="azure_ad_audit_clear_logs">',
      '#suffix' => '</div>',
    ];

    $form['mo_azure_ad_audits_logs'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Audits and Logs') . '<hr>',
    ];

    $user_prov_audit = new MoAuditsAndLogs();
    $row = $user_prov_audit->getCurrentLogs(NULL);

    $rows = [];
    foreach ($row as $index => $value) {
      $value = (array) $value;
      $rows[$index + 1] = [
        'User ID' => $value['uid'],
        'Username' => $value['name'],
        'Date' => date("F j, Y, g:i a", $value['created']),
        'Operation' => $value['operation'],
        'Status' => $value['status'],
      ];
    }

    $form['mo_azure_ad_audits_logs']['table'] = [
      '#type' => 'table',
      '#header' => ['User ID', 'Username', 'Date', 'Operation', 'Status'],
      '#rows' => $rows,
      '#empty' => $this->t('No record found.'),
      '#attributes' => ['class' => ['mo_azure_audits']],
    ];

    $form['mo_azure_ad_audits_logs']['pager'] = [
      '#type' => 'pager',
    ];

    $form['azure_audits_header_end'] = [
      '#markup' => $this->t('</div>'),
    ];

    (new moAzureADHelper())->moAzureShowCustomerSupportIcon($form, $form_state);
    return $form;
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // @todo Implement submitForm() method.
  }

  /**
   * Clear the audit logs.
   */
  public function clearLogs() {
    // @todo Future scope: Give an option to filter any specific type of log.
    $this->audits->clearTable();
    $this->messenger()->addMessage($this->t('Logs has been cleared successfully.'));
  }

}
