<?php
include_once("utilities/na_utils.php");
include_once("utilities/utilities.php");
include_once("utilities/sql_utilies.php");

require_once '../allInOneWeb/demosettings.php';
require_once '../allInOneWeb/sqlUtils.php';

class AnalyseWLClass{
    private $mysqli = null;
    private $data = array();
    private $ivEntityMatcherService = "";
    private $resultsCols = [];
    private $mappedCols = [];
    private $mappedColsView = [];
    private $accumColToSingle = [];
    
    private $metadata = []; //metadata from file (type, size etc)
    private $input_fields = []; //
    private $allowed_ext = []; //allowed ext (in config.php)
    
    private $names_upload = []; //array for names fetched from csv to upload as WL
    private $csv_seperator = ""; //in config.php - for csv parsing
    private $name_index; //index of name column in csv - could be array of few columns
    private $sqlValues = [];
    private $bulk_limit;
    private $wl_table;
    private $rules_json;
    private $rules_relation_json;
    private $columns_metadata;
    private $reverseOrder;
    
    function __construct($mysqli, $action, $inputData = null){
        session_write_close();
        
        global $ivProjectName;
        require('..'.DIRECTORY_SEPARATOR.'iventitymatcherhtm'.DIRECTORY_SEPARATOR .'config.php');
        
        $this->mysqli = $mysqli;
        if($action =="name"){
            $formvalue = $inputData;
            $text = $inputData["content"] ?? $inputData["fileContent"] ?? $inputData[0] ?? null; //fetch teh text data from the file (base64)
        }
        else{
            $formvalue = $inputData['formvalue'];
            $data = $inputData['data'];
            $text = $inputData["content"] ?? $inputData["fileContent"] ?? $inputData[0] ?? null; //fetch teh text data from the file (base64)
            
        }
        //to assure it is delcared
        if(empty($csv_seperator)){
            global $csv_seperator;
        }
        if(empty($allowed_ext)){
            global $allowed_ext;
        }
        
        if(empty($ivEntityMatcherService)){
            global $ivEntityMatcherService;
        }
        
        if(empty(($bulk_limit))){
            global $bulk_limit;
        }
        
        $this->data = $text ?? $data["content"] ?? $data ?? null;
        $this->metadata = $data["fileData"] ?? null;
        
        $this->ivEntityMatcherService = getSystemSettingsProp($this->mysqli, "ivEntityMatcherService");
        
        $this->csv_seperator =  getSystemSettingsProp($this->mysqli, "csv_seperator");
        $this->allowed_ext = $allowed_ext;
        
        $this->bulk_limit = getSystemSettingsProp($this->mysqli, "bulk_limit");
        
        $this->wl_table = $data[0]["table_name"] ?? $data["table_name"] ?? null;
        
        $possible_same_person_rules = json_decode(file_get_contents('../iventitymatcherhtm/jsons/possible_same_person_rules.json',true));
        $relations_rules = json_decode(file_get_contents('../iventitymatcherhtm/jsons/relations_rules.json',true));
        
        $this->rules_json = json_decode(json_encode($possible_same_person_rules), TRUE);
        $this->rules_relation_json = json_decode(json_encode($relations_rules), TRUE);
        
        $this->rules_json =
        !empty($formvalue[0]["relationMatching"]) || $_REQUEST["Action"] == "uploadWL" || ($_REQUEST["relationMatching"] ?? null) ?
        array_merge($this->rules_json, $this->rules_relation_json) :
        $this->rules_json;
        
        $columns_json = json_decode(file_get_contents('../iventitymatcherhtm/jsons/columns.json',true));
        $columns_arr = json_decode(json_encode($columns_json), TRUE);
        $this->resultsCols = $columns_arr["resultsCols"];
        $this->mappedCols = $columns_arr["mappedCols"];
        $this->mappedColsView = $columns_arr["mappedColsView"];
        
        $this->accumColToSingle = $columns_arr["accumColToSingle"];
        
        $this->columns_metadata = ["mappedCols" => $this->mappedCols, "accumColToSingle" => $this->accumColToSingle, "mappedColsView" => $this->mappedColsView];
        
        $this->reverseOrder = $formvalue['reverseOrder'];
        
        
    }
    
    /**
     * for direct action call - calls the function from utilities
     * @param unknown $name
     * @return array
     */
    function analyseNameFunc($name){
        $analysedData = analyseName($name,$this->ivEntityMatcherService, $this->columns_metadata, $this->resultsCols, $this->reverseOrder);
        return $analysedData;
    }
    /**
     * analyseWL - analyse a chosen WL and return the matches
     * @param unknown $sourcefile
     */
    function analyseWL(){
        set_time_limit(0);
        write_to_log("INFO", "analyseWL process");
        $wlSelected = $this->metadata["name"];
        $first_row = true;
        $dbWlName = "";
        
        $ext = pathinfo($this->metadata["name"], PATHINFO_EXTENSION);
        if(!in_array(strtolower(trim($ext)), $this->allowed_ext)){
            return array("Error" => "extenstion <$ext> not allowed");
        }
        $curr_id = 0;
        
        $sql_count = 0;
        $results = array();
        $decoded_data = base64_decode($this->data);
        
        $lines = preg_split("/\\r\\n|\\r|\\n/", $decoded_data);
        $totalNames = count($lines);
        $first = true;
        $input_fields = [];
        $name_index = [];
        foreach ($lines as $name) {
            if($ext == 'csv'){
                $input_data = handleCSV($name, $this->csv_seperator, $first, $input_fields, $name_index, $curr_id);
                $name = $input_data["name"] ?? "";
                $name = preg_replace('!\s+!', ' ', $name); //replace multiple spaces with single in name
                $name = ucwords(strtolower($name));
                $name = str_replace('.', '', $name);
                
                $extra_input = $input_data["extra_input"] ?? null;
                if(empty($name)){
                    continue;
                }
            }
            
            $curr_id++;
            
            $analysis = fetchPersonData($this->ivEntityMatcherService, $name, $this->reverseOrder);
            $eth = $analysis["ethnicity"] ?? null;
            
            if(!empty($analysis["Name Alternatives"])){
                $index = 0;
                foreach($analysis["Name Alternatives"] as $na){
                    $index_str = (count($analysis["Name Alternatives"]) > 1) ? $index_str = ' ('.++$index.')' : "";
                    
                    //creates empty curr_res array - than initialize it with curr_id and searched values
                    $cur_res = array_combine($this->resultsCols, array_fill(0, count($this->resultsCols), ''));
                    $cur_res["id"] = $curr_id;
                    $cur_res["input"] = $name;
                    
                    /**
                     * loop over the results cols and look in thre results for values
                     */
                    foreach($cur_res as $col=>$val){
                        if(array_key_exists($col, $na)){
                            if(is_array($na[$col])){
                                $na[$col] = !empty($_REQUEST["instances"]) ? $na[$col]["instance"] : $na[$col]["caption"];
                            }
                            //A - checking for orthography names
                            if(strpos(strtolower($col), "name") !== false && strpos(strtolower($col), "chinese") === false && strpos(($na[$col]), '(') !== false){
                                $name_exp = explode('(', $na[$col]);
                                $cur_res[$col] = $name_exp[0];
                                $cur_res["orthography"] .= " " .rtrim($name_exp[1],')');
                                continue;
                            }
                            
                            //B - check for mapped columns
                            if(array_key_exists($col, $this->columns_metadata["mappedColsView"])){
                                $new_col = $this->columns_metadata["mappedColsView"][$col];
                                
                                if(!empty($cur_res[$new_col])){
                                    $cur_res[$new_col] .= $na[$col];
                                }
                                else{
                                    $cur_res[$new_col] = $na[$col];
                                }
                                
                                continue;
                            }
                            
                            $cur_res[$col] = $na[$col];
                            
                        }
                    }
                    if((!array_key_exists('ethnicity', $cur_res) || empty($cur_res['ethnicity'])) && !empty($eth)){
                        $cur_res['ethnicity'] = $eth;
                    }
                    
                    //merge the current results with the extra_input (from csv - if exists)
                    $cur_res = array_merge($cur_res,$extra_input ?? []);
                    
                    //patch - extra initials check
                    extraChecks($cur_res, $curr_id, $extra_input ?? null);
                    
                    //insert row to DB
                    $sql_count++;
                    addValuesDB($this->mysqli, $cur_res, $this->sqlValues);
                    
                    
                    if(count($this->sqlValues) % $this->bulk_limit == 0 && count($this->sqlValues) > 0){
                        write_to_log("INFO", "$curr_id/$totalNames analysed");
                        $columns = array_keys($cur_res);
                        insertBulkDB($this->mysqli, $this->sqlValues, $this->wl_table, $columns, $first_row,$wlSelected);
                        $this->sqlValues = [];
                    }
                }
                
            }
            elseif(!empty($analysis["error"])){
                
                //creates empty curr_res array - than initialize it with curr_id and searched values
                $cur_res = array_combine($this->resultsCols, array_fill(0, count($this->resultsCols), ''));
                $cur_res["id"] = $curr_id;
                $cur_res["input"] = $name;
                $cur_res["warning"] = $analysis["error"];
                
                foreach($cur_res as $col=>$val){
                    
                    if(array_key_exists($col, $cur_res)){
                        continue;
                    }
                    $cur_res[$col] = "";
                }
                
                //merge with extraInput from csv if exists
                $cur_res = array_merge($cur_res,$extra_input ?? []);
                
                
                //insert row to DB
                $sql_count++;
                addValuesDB($this->mysqli, $cur_res, $this->sqlValues);
                
                if(count($this->sqlValues) % $this->bulk_limit == 0 && count($this->sqlValues) > 0){
                    write_to_log("INFO", "Finished: $curr_id/$totalNames analysed");
                    $columns = array_keys($cur_res);
                    
                    insertBulkDB($this->mysqli, $this->sqlValues, $this->wl_table, $columns, $first_row,$wlSelected);
                    $this->sqlValues = [];
                }
                
            }
            else{
                write_to_log("ERROR", "Name came up empty: $name");
                
            }
            
        }
        if(count($this->sqlValues) > 0){
            write_to_log("INFO", "$curr_id/$totalNames analysed");
            $columns = array_keys($cur_res);
            
            insertBulkDB($this->mysqli, $this->sqlValues, $this->wl_table,$columns, $first_row,$wlSelected);
            $this->sqlValues = [];
        }
        
        return $this->wl_table;
        
    } 
   
}