<?php
/*------------------------------------------------------------------------------
   
   * * * ----------------------------------------------------------------- * * *
   * * * DIESES SCRIPT IST PRIVAT UND DARF NICHT OHNE DIE AUSDRUECKLICHE   * * *
   * * * GENEHMIGUNG DES AUTORS, WEDER FUER PRIVATE NOCH FUER KOMMERZIELLE * * *
   * * * ZWECKE, VERWENDET WERDEN.                                         * * *
   * * * ----------------------------------------------------------------- * * *
   
                                              Author M. ASPELEITER <dazze@gmx.de
                                             Copyright (c) 2004 mario aspeleiter
					     
   ---------------------------------------------------------------------------*/

include('includes/application_top.php');
include('admin/includes/classes/class.ebay.php');

function _xtc_get_ebay_users(){
        $env = (defined('EBAY_TESTMODE') and constant('EBAY_TESTMODE') == '1') ? 'sandbox' : 'production';
        $user_array = array();
        $user_query = xtc_db_query("SELECT user FROM ebay_auth WHERE environment='".$env."'");
        while($user = xtc_db_fetch_array($user_query)){
                $user_array[] = array('id'=>$user['user'],'text'=>$user['user']);
        }
        return $user_array;
}

$EBAYAPI = new ebayAPI();
define('TABLE_EBAY_FEEDBACK','ebay_feedback');
define('TABLE_EBAY_CALLS','ebay_calls');

// forget about any script timeouts
set_time_limit(0);

$ebay_user_array = _xtc_get_ebay_users();
$output = [
    'total'=>0,
    'saved'=>0,
];
for($i=0;$i<sizeOf($ebay_user_array);$i++){
	$ebay_user = $ebay_user_array[$i]['id'];
        if(ebayApi::oauth2_refreshtoken_exists($ebay_user)){
                if(!ebayApi::oauth2_usertoken_exists($ebay_user) or ebayApi::get_oauth2_usertoken_lifetime($ebay_user) < 1){
                        try{
                                ebayApi::refresh_oauth2_usertoken($ebay_user);
                        }catch(Exception $e){
                                $api_error = 'refresh_oauth2_usertoken() for seller '.$ebay_user.'  '.$e->getMessage();
                        }
                }
        }

        $ebaycalls = new \YES4Trade\Model\ebaycalls();
        $res = $ebaycalls->tradingQuery($ebay_user,
                'GetFeedback',
                $EBAYAPI->get_site_id_from_name(constant('EBAY_SITE')),
                [
                        'DetailLevel' => 'ReturnAll',
                        'Pagination' => [
                                'EntriesPerPage' => 200,
                                'PageNumber' => 1
                        ]
                ]
        );

	$counter = 0;
	if ($EBAYAPI->isGood($res)) {
            $output['total'] += $res->PaginationResult->TotalNumberOfEntries;
	} else {
            echo implode("\n",$EBAYAPI->getResponseErrors($res));
            $resultList = array();
            continue;
	}
        if($res->PaginationResult->TotalNumberOfEntries < 1){
            continue;
        }
        $resultList_array = $res->FeedbackDetailArray->FeedbackDetail ?? [];
        if(!is_array($resultList_array)){
            $resultList_array = [$resultList_array];
        }
        foreach ($resultList_array as $feedback){
            $check_query = xtc_db_query(sprintf("SELECT id FROM ebay_feedback WHERE ItemNumber='%s' AND TransactionId='%s'",
                    $feedback->ItemID,$feedback->TransactionID
            ));
            if( xtc_db_num_rows($check_query) ){
                continue;
            }
            $output['saved']++;
            $time_obj = new \DateTime($feedback->CommentTime);
            $sql_insert_array = array(
                    'CommentText'=>xtc_db_input( $feedback->CommentText ),
                    'FeedbackRole'=>xtc_db_input( $feedback->Role ),
                    'FeedbackId'=>xtc_db_input( $feedback->FeedbackID ),
                    'TransactionId'=>xtc_db_input( $feedback->TransactionID ),
                    'CommentingUser'=>xtc_db_input( $feedback->CommentingUser ),
                    'CommentingUserScore'=>xtc_db_input( $feedback->CommentingUserScore ),
                    'TimeOfComment'=>$time_obj->format('Y-m-d H:i:s'),
                    'ItemNumber'=>xtc_db_input( $feedback->ItemID ),
                    'CommentType'=>xtc_db_input( $feedback->CommentType ),
                    'Response'=>xtc_db_input( $feedback->FeedbackResponse ),
                    'Followup'=>xtc_db_input($feedback->Followup),
                    'status'=>'0',
                    'ebay_user'=>$ebay_user
            );
            xtc_db_perform('ebay_feedback', $sql_insert_array);

            // AUS DER FEEDBACK-REMINDER TABLE RAUSNEHMEN
            $delete_feedback_reminder_query = sprintf("DELETE FROM feedback_reminder WHERE ebay_user_id='%s' and ebay_id='%s'",
                    xtc_db_input( $feedback->CommentingUser ), 
                    xtc_db_input( $feedback->ItemID 
            ));
            xtc_db_query($delete_feedback_reminder_query);

            $counter++;
            $check_array[ $feedback->ItemID ][ $feedback->TransactionID ] = true;
    }
} // end foreach ebayuser
die($output['total'].' Bewertungen durchlaufen, '.$output['saved'].' gespeichert.');