<?php
/***** FETCH COURSE_DETAILS FROM COURSE_LOG *****/
// already available → don't reload!
// see inc_sbook/sbook_session_from_xml.inc
// $clog_course_details=simplexml_load_string(${'clog_course_details_'.$member}); // or die("Error: Cannot create object $ xml course details");

//echo $clog_course_details->clog_list_of_students->clog_student->account_number01;

// :%s/clog_xml_course_details/clog_course_details/g


// clean up previous files
// shell_exec("rm tmp_files/*".$member."*"); 

//if (trim(empty($clog_xml->clog_course_details->clog_list_of_students->clog_student->account_number01))) {
//if (trim(empty($clog_course_details->clog_list_of_students->clog_student->account_number01))) {
if (trim(empty($clog_course_details->clog_list_of_students->clog_student->account_number01))) {
// do nothing
  // debug
  //echo "is empty (2)";
}
else
{
/***** TODO AFTER EACH UPDATE
 
1) download account statement manually from on-line bank 
    История операций > Выписки по продуктам > Счет > За период > inc_payments/account_statements/account_statement_*csv 

2) remove deprecated locally
    after each download:
cd tmp_files/
rm payment_*
rm attendance_history_*

3) remove deprecated on-line
lftp
tmp_files/
mrm payment_*
mrm attendance_history_

4) upload latest
(still using lftp)
cd ../inc_payments/account_statements/
mrm account_statement_01.01.20-*
lcd ../inc_payments/account_statements/
mput account_statement_01.01.20-*

****/

  // debug
  //echo "is not empty";
// echo $clog_xml->clog_course_details->clog_list_of_students->clog_student->account_number01;

/***** get list of account statements *****/
$account_statements = "tmp_files/list_of_account_statements.txt";
$fh_acc_list = fopen($account_statements, 'w') or die("can't open file $account_statements");
$pattern_file_name ="inc_payments/account_statements/account_statement_*csv";
$list_of_account_statements = shell_exec("ls $pattern_file_name | grep -v 'utf8' | sed 's/inc_payments\/account_statements\///'"); 
//echo "PAYMENT DETAILS<br />\n";
//echo "(1) list of account statements: ".$list_of_account_statements."<br />\n"; 
fwrite($fh_acc_list, $list_of_account_statements) or die ("can't run fwrite list of account statements");
fclose($fh_acc_list) or die("can't fclose fh_acc_list");


/***** convert Russian account statement to utf8 *****/
if (file_exists($account_statements)) {
// to do - foreach account_statement in $list_of_account_statement convert and cat
shell_exec("iconv -c --from-code=WINDOWS-1251 --to-code=UTF-8 -o inc_payments/account_statements/account_statement_utf8.csv inc_payments/account_statements/$list_of_account_statements");
//include ('inc_payments/account_statements/account_statement_utf8.csv');
$account_statement_utf8 = file_get_contents('inc_payments/account_statements/account_statement_utf8.csv');
//echo "<br /><hr /><pre>".$account_statement_utf8."</pre>\n";
} // if file_exists
else {
  echo "$ file account_statements does not exist"; 
}


/***** FIND PAYMENT(S) BY MEMBER IN ACCOUNT STATEMENT(S) ****/
/*** fetch account details ***/
// account 01
if (trim(!empty($clog_course_details->clog_list_of_students->clog_student->account_number01))) {
$account_number01 = $clog_course_details->clog_list_of_students->clog_student->account_number01;
// echo "account number 01: ".$account_number01."<br />\n";
$reference_pattern = '/(^.*'.$account_number01.'.*$)/m'; 
}
else {
echo "No account number available\n";
}

// account 02
if (trim(!empty($clog_course_details->clog_list_of_students->clog_student->account_number02))) {
$account_number02 = $clog_course_details->clog_list_of_students->clog_student->account_number02;
//echo "account number 02: ".$account_number02."<br />\n";
$reference_pattern = '/(^.*'.$account_number01.'.*|^.*'.$account_number02.'.*)/m'; 
}
else {
echo "<!-- No account number 2 available -->\n";
}

// account 03
if (trim(!empty($clog_course_details->clog_list_of_students->clog_student->account_number03))) {
$account_number03 = $clog_course_details->clog_list_of_students->clog_student->account_number03;
//echo "account number 03: ".$account_number03."<br />\n";
$reference_pattern = '/(^.*'.$account_number01.'.*|^.*'.$account_number02.'.*|^.*'.$account_number03.'.*\$)/m'; 
}
else {
echo "<!-- No account number 3 available -->\n";
}

/**** create payment history cv ****/
$file_payment_history = "tmp_files/payment_history_$member.csv";
$fh_file_payment_history = fopen($file_payment_history, 'w') or die("can't open file $file_payment_history");

/*** find account(s) ***/
//$reference_pattern = '/(^.*'.$account_number01.'.*|^.*'.$account_number02.'.*|^.*'.$account_number03.'.*\$)/m';  // fails if only account number01 available
//$reference_pattern = '/(^.*'.$account_number01.'.*|^.*'.$account_number02.'.*|^.*'.$account_number03.'.*)/m';  // fails if only account number01 available

   if (preg_match_all($reference_pattern,$account_statement_utf8,$matches)) {
     foreach ($matches[0] as $matched_account_number) {
     //echo "matched account number: ".$matched_account_number."<br />\n";

// define columns in account statement
$columns_payment_history= preg_split ("/;/",$matched_account_number);
//echo $columns_payment_history[0]."<br />"; // date
//echo $columns_payment_history[1]."<br />"; // account holder & number
//echo $columns_payment_history[2]."<br />"; // RUB
//echo $columns_payment_history[3]."<br />"; // sum
//echo $columns_payment_history[4]."<br />"; // RUB
//echo $columns_payment_history[5]."<br />"; // sum

// format date in column date
$columns_payment_history[0] = str_replace(' 00:00','',$columns_payment_history[0]);
$date = preg_split("/\./",$columns_payment_history[0]);
//echo $date[2].$date[1].$date[0]."<br />";

// format account holder & number
/***/
$columns_payment_history[1] = str_replace('рублевый перевод,','',$columns_payment_history[1]);
$columns_payment_history[1] = str_replace('. НДС не облагается,номер счета отправителя-',' ',$columns_payment_history[1]);
$columns_payment_history[1] = str_replace('НДС не облагается',' ',$columns_payment_history[1]);
$columns_payment_history[1] = str_replace(',номер счета отправителя-',' ',$columns_payment_history[1]);
/***/
//echo $columns_payment_history[1]."<br />"; // account holder & number

// format sum
$columns_payment_history[3] = str_replace(' ','',$columns_payment_history[3]);
$columns_payment_history[3] = str_replace('.00','',$columns_payment_history[3]);
//echo $columns_payment_history[3]."<br />"; // sum


// create new columns for csv
$payment_history_6_columns = $date[2].$date[1].$date[0].";".$columns_payment_history[1].";;;;".$columns_payment_history[3].";\n";
// DEBUG
//echo "<pre>".$payment_history_6_columns."</pre>";

// finalise payment history
fwrite($fh_file_payment_history,$payment_history_6_columns) or die ('failed to write $ fh_file_payment_history, $ payment_history_6_columns');
     }
   } // if (preg_match_all($reference_pattern,$account_statement_utf8,$matches))

//fclose($fh_file_payment_history) or die("can't fclose fh_file_payment_history");


/**** CALCULATE ATTENDANCE COSTS ****/

/*** create attendance history ***/ 
$file_attendance_history = "tmp_files/attendance_history_$member.csv";
$fh_file_attendance_history = fopen($file_attendance_history, 'a') or die("can't open file $file_attendance_history");

// need to load the whole course log and not only the latest session
// start loop

//echo "<hr />ATTENDANCE COSTS<br />\n";
//echo "(2) clog ref is : ".$clog_ref."\n"; 

if (preg_match_all("#^<clog_session>$(.*?)^<\/clog_session>$#sim",$sessions_log,$matches)) {
      foreach ($matches[0] as $clog_xml_attendance_costs) {
// needed to rename to clog_xml_attendance_costs to avoid collision w/ clog_xml in sbook_session_from_xml.inc 
$clog_xml_attendance_costs=simplexml_load_string($clog_xml_attendance_costs); 


if (trim($clog_xml_attendance_costs->clog_session_status =='lc')) {
  // todo XXXXXXXXXXXXX
//$session_date_for_attendance_history = $clog_xml_attendance_costs->clog_session_date." (late cancellation)";
$session_date_for_attendance_history = $clog_xml_attendance_costs->clog_session_date;
// late cancellation → lesson charged
//echo "session date for attendance history: ".$session_date_for_attendance_history;
//fwrite($fh_file_attendance_history,$session_date_for_attendance_history);
}

if ((trim($clog_xml_attendance_costs->clog_session_status !='future')) && (trim($clog_xml_attendance_costs->clog_session_status !='lc')) && (!empty($clog_xml_attendance_costs->clog_session_date_cancelled) && !empty($clog_xml_attendance_costs->clog_session_date_rescheduled))) {
// lesson not charged     
//$session_date_for_attendance_history = $clog_xml_attendance_costs->clog_session_date;
//echo "session date for attendance costs: ".$session_date_for_attendance_history;
//fwrite($fh_file_attendance_history,$session_date_for_attendance_history);
}

if ((trim($clog_xml_attendance_costs->clog_session_status !='future')) && (trim($clog_xml_attendance_costs->clog_session_status !='lc')) && (trim(empty($clog_xml_attendance_costs->clog_session_date_cancelled))) && (!empty($clog_xml_attendance_costs->clog_session_date))) {
$session_date_for_attendance_history = $clog_xml_attendance_costs->clog_session_date;
//echo "session date for attendance: ".$session_date_for_attendance_history;
//fwrite($fh_file_attendance_history,$session_date_for_attendance_history);
}

if (!empty($clog_xml_attendance_costs->clog_session_credit)) {
//$session_credit_for_attendance_costs = $clog_xml_attendance_costs->clog_session_credit;
}


if (!empty($clog_xml_attendance_costs->clog_session_ach)) {
$session_ach_for_attendance_history = $clog_xml_attendance_costs->clog_session_ach;
//echo "session ach for attendance: ".$session_ach_for_attendance_history;
//fwrite($fh_file_attendance_history,$session_ach_for_attendance_history);
}


if (!empty($clog_xml_attendance_costs->clog_session_rate)) {
$session_rate_for_attendance_history = $clog_xml_attendance_costs->clog_session_rate;
//echo "session rate for attendance: ".$session_rate_for_attendance_history;
//fwrite($fh_file_attendance_history,$session_rate_for_attendance_history);
}

$cost = $session_rate_for_attendance_history * $session_ach_for_attendance_history;

/********** todo if time available current balance  *************/
//$previous_balance = "1450"; // not always!
//$previous_balance = 0; // depends on previous lesson...
//$current_balance = $cost - $previous_balance;
//$attendance_data = $session_date_for_attendance_history.";;".$session_ach_for_attendance_history.";".$session_rate_for_attendance_history.";-".$cost.";;;;".$current_balance."\n";
$attendance_data = $session_date_for_attendance_history.";lesson (ach X rate = cost);".$session_ach_for_attendance_history.";".$session_rate_for_attendance_history.";-".$cost.";;;;\n";
//echo "<pre>(3) attendance data from course log: ".$attendance_data."</pre>\n"; 
fwrite($fh_file_attendance_history,$attendance_data);
// fclose($fh_file_attendance_history) or die("can't fclose fh_file_attendance_history"); // 20210311-1157

// end loop
      } //      foreach ($matches[0] as $clog_xml_attendance_costs)
} // if (preg_match_all("#^<clog_session>$(.*?)^<\/clog_session>$#sim",$sessions_log,$matches))


/**** FINALISE PAYMENT AND ATTENDANCE COSTS ******/
// create final file
$file_payment_and_attendance_costs = "tmp_files/payment_and_attendance_costs_$member.csv";
$fh_file_payment_and_attendance_costs = fopen($file_payment_and_attendance_costs , "w") or die("could not open file for fh_file_payment_and_attendance_costs");


// make attendance costs unique and copy contents into new file
// fails
//$file_attendance_history=file_get_contents($file_attendance_history);
// works
$file_attendance_history=file($file_attendance_history);
//echo $file_attendance_history; // array
$unique = array_unique($file_attendance_history);

foreach($unique as $line1)
{
//  echo "<pre>".$line1."</pre>\n";
  fwrite($fh_file_payment_and_attendance_costs, $line1) or die("could not write file for fh_file_payment_and_attendance_costs");
}


// copy contents into new file
$file_payment_history = "tmp_files/payment_history_$member.csv";
$file_payment_history = file($file_payment_history);
//  $unique2 = array_unique($file_payment_history); // doesn't actually need unique but just in case - NO! bc some payments could be made on the same day...
//$unique2 = array($file_payment_history);
$unique2 = $file_payment_history;
foreach($unique2 as $line2)
{
  // echo "<pre>".$line2."</pre>\n";
  fwrite($fh_file_payment_and_attendance_costs, $line2);
}
//fclose($fh_file_payment_and_attendance_costs);
// fclose($fh_file_payment_history) or die("can't fclose fh_file_payment_history"); // 20210311-1157

// create new file for rsort
$file_payment_and_attendance_costs2 = "tmp_files/payment_and_attendance_costs2_$member.csv";

// failed
// file_get_contents reads file into a string
//$file_payment_and_attendance_costs2 = file_get_contents($file_payment_and_attendance_costs); 
//$file_payment_and_attendance_costs2 = explode ("\n", file_get_contents($file_payment_and_attendance_costs)); 
//$file_payment_and_attendance_costs2 = array($file_payment_and_attendance_costs2);  
//$file_payment_and_attendance_costs2 = rsort($file_payment_and_attendance_costs2) or die ('failed to sort'); 

// failed
// file reads into an array
//$file_payment_and_attendance_costs2 = file($file_payment_and_attendance_costs); 
//$file_payment_and_attendance_costs2 = rsort($file_payment_and_attendance_costs2) or die ('failed to sort'); 

// workaround
//$file_payment_and_attendance_costs2 = shell_exec("sort -ru $file_payment_and_attendance_costs"); // unique reverse
//shell_exec("sort -ru $file_payment_and_attendance_costs | cat > $file_payment_and_attendance_costs2 "); // sort -ru unique reverse

//shell_exec("sort -r $file_payment_and_attendance_costs | cat > $file_payment_and_attendance_costs2 "); // was before 20210311-1208

/**************** TODO ****************/
// check if doesn't delete payments made on same day!
// not needed bc already using uniq earlier on both attendance & payment files
//shell_exec("sort -ru $file_payment_and_attendance_costs | cat > $file_payment_and_attendance_costs2 "); // sort -ru unique reverse

shell_exec("sort -r $file_payment_and_attendance_costs | cat > $file_payment_and_attendance_costs2 "); // sort -u reverse

// alternative
$file_payment_and_attendance_costs3 = file($file_payment_and_attendance_costs);
$file_payment_and_attendance_costs3 = array_unique($file_payment_and_attendance_costs3);
rsort($file_payment_and_attendance_costs3); // sort in revert order
foreach($file_payment_and_attendance_costs3 as $line3)
{
  echo "<pre>".$line3."</pre>\n";
  //fwrite($fh_file_payment_and_attendance_costs3, $line3) or die("could not write file for fh_file_payment_and_attendance_costs3");
}



/**** SUM PAYMENTS ****/
// now included in payment_history_generated_from_xml_clog_sbook.inc 

fclose($fh_file_payment_and_attendance_costs);
fclose($fh_file_attendance_history) or die("can't fclose fh_file_attendance_history"); 
fclose($fh_file_payment_history) or die("can't fclose fh_file_payment_history"); 

} // else if (trim(empty($clog_course_details->clog_list_of_students->clog_student->account_number01)))
?>
