<?php
defined( 'ABSPATH' ) or exit;   // show a blank page if try to access this file directly
require_once( EWZ_PLUGIN_DIR . "classes/ewz-permission.php");

class Ewz_User
{
   /**
    * Return the array of users for use in an option list
    *
    * @param  boolean $with_info
    * @return array<array<string,int|string >>
    */
    public static function get_user_opt_array( $with_info = true )
    {

        if( !Ewz_Permission::can_see_users() ){
            return array();
        }
        $users = get_users( );
        usort($users, function($a, $b) {
            return strnatcmp($a->last_name . ', ' . $a->first_name, $b->last_name . ', ' . $b->first_name);
        });
        $options = array();
        foreach ( $users as $user ) {
            $display =  $user->last_name . ', ' . $user->first_name;
            $info =  $user->user_login . ', ' .  $user->user_email;
            if( $with_info ){
                $display .= " ( $info )";
            }
            array_push( $options, array(  'value' => $user->ID, 'display' => $display ) );
        }
        return $options;
    }

   /**
    * Return the array of users for use in an option list
    *
    * @param  WP_User $admin_user
    * @param  array<int>   $userids   of ints
    * @return void
    */
    public static function warn_deleting_items( $admin_user, $userids ){
        global $wpdb;

        $usrlist = join(',', $userids);
        $sql =  'SELECT concat(  u.user_login, " has ", count(*), " items uploaded to ", w.webform_title ) ' .
                               '  FROM ' .  EWZ_ITEM_TABLE . ' i, ' . EWZ_WEBFORM_TABLE . ' w, ' . EWZ_WP_USER_TABLE . ' u' .
                               ' WHERE i.webform_id = w.webform_id ' .
                               "   AND i.user_id in ( $usrlist )  " .
                               '   AND u.ID = i.user_id ' .
                               ' GROUP BY w.webform_title, u.user_login ';

        $data = $wpdb->get_col( $sql ); // is ordered   no tainted data
        if( $data ){
            echo "<b>EWZ Warning:</b> Deleting these users will also delete the following items they uploaded via EntryWizard:<br> ";
            foreach ( $data as $msg ){
                echo "$msg<br>";
            }
        }
    }

   /**
    * @param  string  $email
    * @return array<string,mixed>
    */
    public static function get_user_item_data( $email ){
        global $wpdb;

        $user_id = get_user_by( 'email', $email )->ID;
        $fields =  $wpdb->get_results(  'SELECT field_id, field_header FROM ' . EWZ_FIELD_TABLE . ' ORDER BY field_header', ARRAY_A  );   //  no tainted data
        $hdrs = array();
        foreach( $fields as $field ){
            $hdrs[$field['field_id']] = $field['field_header'];
        }
        $user_data = $wpdb->get_results( $wpdb->prepare( 'SELECT item_id, item_data, item_files, webform_id, upload_date FROM ' . EWZ_ITEM_TABLE .
                                                         " WHERE user_id = %d ORDER BY item_id",
                                                          $user_id ),  ARRAY_A );
        $group_id = 'EntryWizard';
        $group_label = 'EntryWizard';
        $export_items = array();
        foreach( $user_data as $rownum => $row ){
            $item_db_data = Ewz_Base::check_unserial_arr( $row['item_data'] );
            $item_db_files = Ewz_Base::check_unserial_arr( $row['item_files'] );

            $fnames = array();
            foreach( $item_db_files as $field_id => $files ){
                $ewzurl = wp_upload_dir()['baseurl'] . '/ewz_img_uploads/';
                $fnames[$field_id] = '<a href="' . $ewzurl . esc_attr($files['fname']) . '">' . esc_attr($ewzurl . $files['fname']) . '</a>';
            }
            $export=array();
            foreach( $item_db_data as $field_key => $idata ){
                if( is_int($field_key ) ){
                    // $field_key is field_id, $idata['value'] is the field value
                    if( $idata['value'] === 'ewz_img_upload' ){
                        $export[] = array(
                            'name' => $hdrs[$field_key],
                            'value' => $fnames[$field_key]
                        );
                    } else {
                        $export[] = array(
                            'name' => $hdrs[$field_key],
                            'value' => $idata['value']
                        );
                    }
                    unset($idata['field_id']);
                    unset($idata['value']);
                    // per-image data batch-uploaded by admin: pcontent,ptitle,pexcerpt
                    if( count($idata) > 0){
                        foreach( $idata as $key => $item_val ){
                            $export[] = array(
                                'name' =>  $key,
                                'value' => strval($item_val )
                            );
                        }
                    }

                } else {
                    $export[] = array(
                        'name' => "$field_key",
                        'value' => strval($idata)
                        );
                }
            }
            $export[] = array(
                        'name' => "Upload Date",
                        'value' => $row['upload_date']
                        );
            $export1 = apply_filters( 'ewz_user_item_data', $export, $row['item_id'] ); /** @phpstan-ignore-line */
            $export_items[] = array(
                'group_id' => $group_id,
                'group_label' => $group_label,
                'item_id' => "Item " . $row['item_id'],
                'data' => $export1,
            );
        }

        return array(
            'data' => $export_items,
            'done' => true,
        );
    }
}
