<?php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\Response;

class AdminDownloadSubscribers extends CDController{

  public function __construct() {

    $this->view = 'admin/download-subscribers.twig';

  }

  public function get_context(){
    
    if(isset($_GET['p']) && (int) $_GET['p'] > 1){
      $paged = $_GET['p'];
    }else{
      $paged = 1;
    }

    $users_per_page = 40;

    $user_args = array (
      'role'      => 'subscriber',
      'order'     => 'DESC',
      'orderby'   => 'registered',
      'number'    => $users_per_page,
      'fields'    => 'ID',
      'paged'     => $paged
    );

    $user_query = new WP_User_Query( $user_args );

    $total_users = $user_query ->get_total();
    $total_pages = ceil($total_users / $users_per_page);

    $query_string = $_SERVER['QUERY_STRING'];

    $base = admin_url() . '?' . remove_query_arg('p', $query_string).'&p=';
    
    $this->data['pagination']['current_page'] = $paged;
    $this->data['pagination']['total_pages'] = $total_pages;
    $this->data['pagination']['base_url'] = $base;

    $subscribers = $user_query->get_results();
    
    $subscriber_array = array();
    
    foreach ($subscribers as $subscriber_id) {
      $subscriber_data = get_field('user_data','user_'.$subscriber_id);
      $user_data = get_userdata( $subscriber_id );
      $registered = $user_data ->user_registered;
      $subscriber_data['subscription_date'] = date( "d-m-Y", strtotime( $registered ) );
      $subscriber_array[] = $subscriber_data;
    }

    $country_field = get_field_object('field_5cd1e112c2eb9');
    $country_choices = $country_field['choices'];

    $this->data['country_choices'] = $country_choices;

    $company_area_field = get_field_object('field_5cd1e450ac3dc');
    $company_area_choices = $company_area_field['choices'];

    $this->data['company_area_choices'] = $company_area_choices;

    $this->data['subscribers'] = $subscriber_array;

    $query_string = $this->remove_url_query($query_string, 'download_from');

    $query_string = $this->remove_url_query($query_string, 'download_to');

    $this->data['download_link'] = $base = admin_url() . '?page=download-subscribers';

  }

  protected function remove_url_query($url, $key) {
    $url = preg_replace('/(?:&|(\?))' . $key . '=[^&]*(?(1)&|)?/i', "$1", $url);
    $url = rtrim($url, '?');
    $url = rtrim($url, '&');
    return $url;
  }

  public function download_xlsx(){
    
    $streamedResponse = new StreamedResponse();
    $streamedResponse->setCallback(function () {
      $spreadsheet = $this->generate_spreadsheet();
      $writer =  new Xlsx($spreadsheet);
      $writer->save('php://output');
      exit();
    });
    $streamedResponse->setStatusCode(Response::HTTP_OK);
    $streamedResponse->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    $streamedResponse->headers->set('Content-Disposition', 'attachment; filename="suscriptores-'.date('d-m-Y').'.xlsx"');
    return $streamedResponse->send();
  }

  private function generate_spreadsheet(){
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet
      ->setCellValue('A1', 'Fecha de suscripción')
      ->setCellValue('B1', 'Nombre')
      ->setCellValue('C1', 'Apellido')
      ->setCellValue('D1', 'Profesión')
      ->setCellValue('E1', 'Empresa')
      ->setCellValue('F1', 'Cargo')
      ->setCellValue('G1', 'Teléfono')
      ->setCellValue('H1', 'E-Mail')
      ->setCellValue('I1', 'Domicilio')
      ->setCellValue('J1', 'CP')
      ->setCellValue('K1', 'Ciudad')
      ->setCellValue('L1', 'Región')
      ->setCellValue('M1', 'País')
      ->setCellValue('N1', 'Domicilio Laboral')
      ->setCellValue('O1', 'Rubro')
      ->setCellValue('P1', 'Otro Rubro')
      ->setCellValue('Q1', 'Producto o Servicio')
      ->setCellValue('R1', 'Empleados')
      ->setCellValue('S1', 'Part. en la empresa');

      $country_field = get_field_object('field_5cd1e112c2eb9');
      $country_choices = $country_field['choices'];

      $company_area_field = get_field_object('field_5cd1e450ac3dc');
      $company_area_choices = $company_area_field['choices'];

      $user_args = array (
        'role'      => 'subscriber',
        'order'     => 'DESC',
        'orderby'   => 'registered',
        'number'    => -1,
        'fields'    => 'ID',
      );

      $date_query = array(
        'inclusive'     => true
      );
      
      if( (isset($_POST['download_from']) && $_POST['download_from']) ){
        $date_query['after'] = $_POST['download_from'];
        $use_date = true;
      }

      if( (isset($_POST['download_to']) && $_POST['download_to']) ){
        $date_query['before'] = $_POST['download_to'];
        $use_date = true;
      }
  
      if($use_date){
        $user_args['date_query'] = array( $date_query );
      }

      $user_query = new WP_User_Query( $user_args );

      $subscribers = $user_query->get_results();
  
      foreach ($subscribers as $index => $subscriber_id) {
        $subscriber_data = get_field('user_data','user_'.$subscriber_id);
        $user_data = get_userdata( $subscriber_id );
        $registered = $user_data ->user_registered;
        $subscriber_data['subscription_date'] = date( "d-m-Y", strtotime( $registered ) );
        
        if( $subscriber_data['country'] ){
          $subscriber_data['country'] = $country_choices[$subscriber_data['country']];
        }else{
          $subscriber_data['country'] = 'No actualizado';
        }

        if( $subscriber_data['is_working_address'] ){
          $subscriber_data['is_working_address'] = 'Si';
        }else{
          $subscriber_data['is_working_address'] = 'No';
        }

        if( $subscriber_data['company_area'] ){
          $subscriber_data['company_area'] = $company_area_choices[$subscriber_data['company_area']];
        }else{
          $subscriber_data['company_area'] = 'No actualizado';
        }

        if( $subscriber_data['company_participation'] ){
          $subscriber_data['company_participation'] = 'Si';
        }else{
          $subscriber_data['company_participation'] = 'No';
        }

        $sheet
          ->setCellValue('A'.($index + 2), $subscriber_data['subscription_date'])
          ->setCellValue('B'.($index + 2), $subscriber_data['first_name'])
          ->setCellValue('C'.($index + 2), $subscriber_data['last_name'])
          ->setCellValue('D'.($index + 2), $subscriber_data['profession'])
          ->setCellValue('E'.($index + 2), $subscriber_data['company'])
          ->setCellValue('F'.($index + 2), $subscriber_data['position'])
          ->setCellValue('G'.($index + 2), $subscriber_data['phone'])
          ->setCellValue('H'.($index + 2), $subscriber_data['email'])
          ->setCellValue('I'.($index + 2), $subscriber_data['address'])
          ->setCellValue('J'.($index + 2), $subscriber_data['postal_code'])
          ->setCellValue('K'.($index + 2), $subscriber_data['city'])
          ->setCellValue('L'.($index + 2), $subscriber_data['region'])
          ->setCellValue('M'.($index + 2), $subscriber_data['country'])
          ->setCellValue('N'.($index + 2), $subscriber_data['is_working_address'])
          ->setCellValue('O'.($index + 2), $subscriber_data['company_area'])
          ->setCellValue('P'.($index + 2), $subscriber_data['company_area_other'])
          ->setCellValue('Q'.($index + 2), $subscriber_data['main_product'])
          ->setCellValue('R'.($index + 2), $subscriber_data['employees_quantity'])
          ->setCellValue('S'.($index + 2), $subscriber_data['company_participation']);

      }

      return $spreadsheet;
  }
}