<?php
  
  function console_log($data){
    echo '<script>';
    echo 'console.log('.json_encode($data).')';
    echo '</script>';
  }
  
  require_once('../../postgreSQL/config.php');
  require_once('../../postgreSQL/functions.php');
  
  require_once "vendor/autoload.php";
  
  use PhpOffice\PhpSpreadsheet\Spreadsheet;
  use PhpOffice\PhpSpreadsheet\Reader\Csv;
  use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  
  // ファイル名を取得して、ユニークなファイル名に変更
  $file_name = $_FILES['upfile']['name'];
  //console_log($file_name);
  
  $uniq_file_name = date("YmdHis") . "_" . $file_name;
  
  // 仮にファイルがアップロードされている場所のパスを取得
  $tmp_path = $_FILES['upfile']['tmp_name'];
  
  // 保存先のパスを設定
  $upload_path = '';
  
  if (is_uploaded_file($tmp_path)) {
    
    $dbh = connectDb();
    
    // 仮のアップロード場所から保存先にファイルを移動
    if (move_uploaded_file($tmp_path, $upload_path . $uniq_file_name)) {
      // ファイルが読出可能になるようにアクセス権限を変更
      chmod($upload_path . $uniq_file_name, 0644);
      
      $objReader = new Csv();
      $objReader->setInputEncoding('SJIS');
      $objReader->setDelimiter(',');
      $objReader->setEnclosure('"');
      $objReader->setSheetIndex(0);
      
      $spreadsheet = $objReader->load($upload_path.$uniq_file_name);
      $sheet       = $spreadsheet->getActiveSheet();
      
      $lastrow = $sheet->getHighestRow(); //200などの数字
      $lastcolname = $sheet->getHighestColumn(); //AZなどの文字列
      $lastcol = PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($lastcolname); //これで数字になる
      $strRange = $sheet->calculateWorksheetDimension();
      
      $datas = $sheet->rangeToArray(
        $strRange,
        NULL, //空セル時の値
        TRUE, //TRUE式が使われていたら計算される
        FALSE, //TRUE書式設定されたもの
        TRUE  //TRUE 連想配列 {A:val, B:val..}　FALSEインデックス配列[val,val..]
      );
      
      //pqGridが受け付ける形式に変換
      $array = array();
      for($i=1; $i<=$lastrow; $i++) {
        $array[$i-1] = $datas[$i];
        console.log($array[i-1].A);
        $sth = $dbh->prepare("SELECT inventory " .
                             "  FROM t_items  " .
                             " where customer = '" . $customerCode . "' " .
                             "   and code = '" . $itemCode . "' ");
        $sth->execute();
        
        $userData = array();
        while($row = $sth->fetch(PDO::FETCH_ASSOC)){
          $array[i-1].A = $row['inventory'];
        }
        
      }
      
      unlink($upload_path . $uniq_file_name);
      
      //jsonとして出力
      header('Content-type: application/json');
      echo json_encode($array);
      
    } else {
      echo "Error:アップロードに失敗しました。";
    }
    $sth = null;
    $dbh = null;
    
  } else {
    echo "Error:CSVファイルが見つかりません。";
  }
  
?>