<?php
namespace App\Controllers;
use Config\Services;

class Geteditablerows extends BaseController{
    private $dbHandle;

    public function index(){
        $this->dbHandle = \Config\Database::connect();
        $dataToReturn = [];

        $source = $this->request->getVar('source');
        $parnames_raw = $this->request->getVar('parnames');
        $parnames = explode('|', $parnames_raw);
        $parvalues = explode('|', $this->request->getVar('parvalues'));
        
        $limit = $this->request->getVar('limit');
		$offset = $this->request->getVar('offset');
        
        $whereclause = '';
        
        if($parnames_raw != ''){
            $whereclause = " where (".$this->andCondition($parnames, $parvalues).")";
        }
        $qry = "select SQL_CALC_FOUND_ROWS * from `{$source}`{$whereclause} limit {$limit} offset {$offset}";
        
        $R = $this->dbHandle->query($qry);
        if( $R->getNumRows()>0 ){
            //get total existential rows
            $dataToReturn['total'] = $this->dbHandle->query("select found_rows() as totalrows")->getResultArray()[0]['totalrows'];
			
            $A = $R->getResultArray();

            $dataToReturn['status'] = 0;
            $dataToReturn['load'] = $A;
        }else{
            $dataToReturn['status'] = 1;
        }

        return json_encode($dataToReturn, JSON_HEX_APOS | JSON_HEX_QUOT);
    }
    
    private function andCondition($names, $values){
    	$cond = "";
    	for($i=0; $i<sizeof($names); $i++){
    		$cond .= " and `{$names[$i]}`='".$this->dbEscape($values[$i])."'";
    	}
    	return substr($cond, 5);
    }
    
    private function toCSL($arr){
    	$ret = "";
    	foreach($arr as $a){ $ret .= ",`".$this->dbEscape($a)."`"; }
    	$ret = substr($ret,1);
    	return $ret;
    }
    
    private function dbEscape($str){
        return $str;
    }
    
    // private function holePegStr($holes, $pegs){
    // 	global $DB;
    // 	$hpstr = "";
    // 	for($i=0; $i<sizeof($holes); $i++){
    // 		$hpstr .= ",`{$holes[$i]}`='".$DB->escape_string($pegs[$i])."'";
    // 	}
    // 	$hpstr = substr($hpstr,1);
    // 	return $hpstr;
    // }
    
    // private function andCondition($names, $values){
    // 	global $DB;
    // 	$cond = "";
    // 	for($i=0; $i<sizeof($names); $i++){
    // 		$cond .= " and `{$names[$i]}`='".$DB->escape_string($values[$i])."'";
    // 	}
    // 	$cond = substr($cond, 5);
    // 	return $cond;
    // }

    // private function toCSL($arr){
    // 	global $DB;
    // 	$ret = "";
    // 	foreach($arr as $a){ $ret .= ",`".$DB->escape_string($a)."`"; }
    // 	$ret = substr($ret,1);
    // 	return $ret;
    // }
}