<?php include('../include/headscript.php'); ?>
<?php
require '../../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\IReader;

if(isset($_FILES['f_csv'])) {
    $file = $_FILES['f_csv']['tmp_name'];
    $template_id = $_POST['template_id'];

    //get template associate data
    $arr_associate_data = new WA_MySQLi_RS("rsl", $repnew, 0);
    $arr_associate_data->setQuery("SELECT * FROM template_associate where template_importify_id=$template_id");
    $arr_associate_data->execute();
    $arr_associate = $arr_associate_data->Results;

    if(count($arr_associate) > 0) { //check define columns
        $spreadsheet = IOFactory::load($file);
        $worksheet = $spreadsheet->getActiveSheet();
        $arr_info = $worksheet->toArray(); 

        // remove empty rows
        $arr_info = array_filter($arr_info, function($row) {
            return count(array_filter($row)) > 0;
        });  

        $productsRefNumber_excelName = '';
        $reportsNumberLab_excelName = '';
        $partsCode_excelName = '';
        
        if(count($arr_info) > 1) {  //check excel rows
            $arr_excel_columns = $arr_info[0];
            $arr_need_columns = array(); 

            foreach ($arr_associate as $item){
                if($item['column_name'] == 'products_refnumber'){
                    $productsRefNumber_excelName = $item['headerfile'];
                }
                if($item['column_name'] == 'reportsNumberLab'){
                    $reportsNumberLab_excelName = $item['headerfile'];
                }
                if($item['column_name'] == 'partsCode'){
                    $partsCode_excelName = $item['headerfile'];
                } 
            }  
            array_push($arr_need_columns, $productsRefNumber_excelName);
            array_push($arr_need_columns, $reportsNumberLab_excelName);
            array_push($arr_need_columns, $partsCode_excelName);

            $result_groupNameHeaderFile = "";    //for analysisgroupcode
            $result_testNameHeaderFile = "";    //for analysisvocabulary
            $result_CasNameHeaderFile = "";    //for compundsvocabulary
            $result_AnalytsNameHeaderFile = "";    //for compundsvocabulary


            foreach($arr_associate as $item) {
                array_push($arr_need_columns, $item['headerfile']);

                if($item['column_name'] == 'analysisgroupcode'){
                    $result_groupNameHeaderFile = $item['headerfile'];
                }

                if($item['column_name'] == 'result_TestName') {
                    $result_testNameHeaderFile = $item['headerfile'];
                }

                
                if($item['column_name'] == 'cas'){
                    $result_CasNameHeaderFile = $item['headerfile'];
                }

                if($item['column_name'] == 'result_AnalytsName') {
                    $result_AnalytsNameHeaderFile = $item['headerfile'];
                }
            }

            //check excel data column with template associate data
            $verify_flag = true;
            for($i=0; $i<count($arr_need_columns); $i++) {
                if(!in_array($arr_need_columns[$i], $arr_excel_columns)) {
                    $verify_flag = false;
                    break;
                }
            } 

            if($verify_flag) {
                //check result_TestName field
                $arr_anaysisvoc_words = array();
                if($result_testNameHeaderFile != "") {
                    $arr_diff_anaysisvoc_words = array();
                    $idx_resultTestName_po = array_search($result_testNameHeaderFile, $arr_excel_columns);
                    $idx_groupCodeHeaderFile = array_search($result_groupNameHeaderFile, $arr_excel_columns);

                    $arr_unique_words = []; // Array to track unique words

                    for ($i = 1; $i < count($arr_info); $i++) {
                        $word = $arr_info[$i][$idx_resultTestName_po];
                        
                        // Check if the word is not already in the unique words array
                        if (!in_array($word, $arr_unique_words)) {
                            $arr_unique_words[] = $word; // Add the word to the unique words array

                            // Now push to the output array
                            array_push($arr_diff_anaysisvoc_words, array(
                                "word" => $word,
                                "groupcode" => $arr_info[$i][$idx_groupCodeHeaderFile],
                            ));
                        }
                    }


                    foreach($arr_diff_anaysisvoc_words as $item) {
                        $arr_analysis_refdata = new WA_MySQLi_RS("rsl", $repnew, 0);
                        $trim_item = str_replace("\n", "", str_replace("'", "\'", $item['word']));
                        $groupcodeTrimmed = str_replace("\n", "", str_replace("'", "\'", $item['groupcode']));
                        if($groupcodeTrimmed == "" || $groupcodeTrimmed == "-" || $groupcodeTrimmed == " "){
                            $quantity = 0;
                        }else{
                            $arr_analysis_refdata->setQuery("SELECT * FROM analysisvocabulary where analysiscode like '$groupcodeTrimmed'");
                            $arr_analysis_refdata->execute();
                            $arr_analysis_ref = $arr_analysis_refdata->Results;
                            $quantity = count($arr_analysis_ref);
                        } 
                        if($quantity == 0){
                            $arr_analysis_refdata = new WA_MySQLi_RS("rsl", $repnew, 0);
                            $arr_analysis_refdata->setQuery("SELECT * FROM analysisvocabulary where nameanalysisvoc like '$trim_item'");
                            $arr_analysis_refdata->execute();
                            $arr_analysis_ref = $arr_analysis_refdata->Results; 
                        }


                        if(count($arr_analysis_ref) == 0) {
                            //check kind
                            $arr_analysiskind_refdata = new WA_MySQLi_RS("rsl", $repnew, 0);
                            $arr_analysiskind_refdata->setQuery("SELECT * FROM analysisvocabulary where preferred like 'Y'");
                            $arr_analysiskind_refdata->execute();
                            $arr_analysiskind_ref = $arr_analysiskind_refdata->Results;
                            array_push($arr_anaysisvoc_words, array(
                                'word' => $item['word'],
                                'arr_similary' => $arr_analysiskind_ref
                            ));
                        }
                    }
                }

                //check result_AnalytsName field
                $arr_compundsvoc_words = array();
                if($result_AnalytsNameHeaderFile != "") {
                    $arr_diff_compundsvoc_words = array();
                    $arr_tmp_diff_compundsvoc_words = array();
                    $idx_resultAnalytsName_po = array_search($result_AnalytsNameHeaderFile, $arr_excel_columns);
                    $idx_resultAnalytsName_cas = array_search($result_CasNameHeaderFile, $arr_excel_columns);
                    $idx_resultTestName_po = $result_testNameHeaderFile != "" ? array_search($result_testNameHeaderFile, $arr_excel_columns) : 0;
                    
                    for($i=1; $i<count($arr_info); $i++) {
                        if(!in_array($arr_info[$i][$idx_resultAnalytsName_po], $arr_tmp_diff_compundsvoc_words)) {
                            array_push($arr_tmp_diff_compundsvoc_words, $arr_info[$i][$idx_resultAnalytsName_po]);
                            array_push($arr_diff_compundsvoc_words, array(
                                'word' => $arr_info[$i][$idx_resultAnalytsName_po],
                                'cas' => $arr_info[$i][$idx_resultAnalytsName_cas],
                                'analysis_word' => $result_testNameHeaderFile != "" ? $arr_info[$i][$idx_resultTestName_po] : ""
                            ));                        
                        }
                    }

                    foreach($arr_diff_compundsvoc_words as $item) { 
                        $arr_compunds_refdata = new WA_MySQLi_RS("rsl", $repnew, 0);
                        $compund_word = $item['word'];
                        $compund_cas = $item['cas'];
                        $trimmed_cas = str_replace("\n", "", str_replace("'", "\'", $compund_cas));
                        $trimmed_cas = str_replace(" ", "", $trimmed_cas);
                        $trim_item = str_replace("\n", "", str_replace("'", "\'", $compund_word));
                        if($trimmed_cas == "" || $trimmed_cas == "-" || $trimmed_cas == " "){
                            $quantity = 0;
                        }else{
                            $arr_compunds_refdata->setQuery("SELECT * FROM compundsvocabulary where cascompoundvocabulary like '%$trimmed_cas%'");
                            $arr_compunds_refdata->execute();
                            $arr_compunds_ref = $arr_compunds_refdata->Results;
                            $quantity = count($arr_compunds_ref);
                        }
                        
                        if($quantity == 0 ){
                            $arr_compunds_refdata = new WA_MySQLi_RS("rsl", $repnew, 0);
                            $arr_compunds_refdata->setQuery("SELECT * FROM compundsvocabulary where namecompoundsvocabulary like '$trim_item'");
                            $arr_compunds_refdata->execute();
                            $arr_compunds_ref = $arr_compunds_refdata->Results;
                        }


                        if(count($arr_compunds_ref) == 0) {
                            //check kind
                            $arr_compundskind_refdata = new WA_MySQLi_RS("rsl", $repnew, 0);
                            $arr_compundskind_refdata->setQuery(statement: "SELECT * FROM compundsvocabulary where preferred like 'Y'");
                            $arr_compundskind_refdata->execute();
                            $arr_compundskind_ref = $arr_compundskind_refdata->Results;
                            array_push($arr_compundsvoc_words, array(
                                'word' => $compund_word,
                                'anaysis_word' => $item['analysis_word'],
                                'arr_similary' => $arr_compundskind_ref
                            ));
                        }
                    } 
                }

                die(json_encode(array(
                    'code' => "success",
                    'arr_analysis_data' => $arr_anaysisvoc_words,
                    'arr_compunds_data' => $arr_compundsvoc_words,
                )));
            } else {
                die("invalid_excel_data_format_error");
            }
        } else {
            die("invalid_excel_data_format_error");
        }
    } else {
        die("none_define_column_error");
    }
} else {
    die("file_empty_error");
}