<?php
class MiniPDO {
    public $file;
    public $data = [];
    public $lastId = 0;
    public function __construct($file) {
        $this->file = $file;
        if (is_file($file)) {
            $d = json_decode(@file_get_contents($file), true);
            $this->data = is_array($d) ? $d : [];
        }
        if (!$this->data) {
            $seed = __DIR__ . '/default-data.php';
            if (is_file($seed)) {
                $this->data = require $seed;
            }
        }
        if (!$this->data) $this->data = [];
    }
    public function setAttribute($k, $v) {}
    public function exec($sql) { $this->prepare($sql)->execute(); return 1; }
    public function quote($s) { return "'" . str_replace("'", "''", (string)$s) . "'"; }
    public function lastInsertId() { return (string)$this->lastId; }
    public function prepare($sql) { return new MiniStmt($this, $sql); }
    public function query($sql) { $st = $this->prepare($sql); $st->execute(); return $st; }
    public function load($table) { return $this->data[$table] ?? []; }
    public function save($table, $rows) {
        $this->data[$table] = array_values($rows);
        $dir = dirname($this->file);
        if (!is_dir($dir)) @mkdir($dir, 0777, true);
        $json = json_encode($this->data, JSON_UNESCAPED_UNICODE);
        $ok = @file_put_contents($this->file, $json);
        if ($ok === false) {
            $this->file = '/tmp/mango-db.json';
            @file_put_contents($this->file, $json);
        }
    }
}
class MiniStmt {
    public $db; public $sql; public $rows = []; public $pos = 0;
    public function __construct($db, $sql) { $this->db = $db; $this->sql = trim($sql); }
    public function execute($params = []) {
        $sql = preg_replace('/\s+/', ' ', $this->sql);
        $params = array_values($params);
        if (preg_match('/^PRAGMA|^CREATE TABLE/i', $sql)) { $this->rows=[]; return true; }
        if (preg_match('/^INSERT\s+(OR REPLACE\s+)?INTO\s+([a-z_]+)\s*\(([^)]+)\)\s*VALUES\s*\((.+)\)/is', $sql, $m)) {
            $table=$m[2]; $cols=array_map('trim', explode(',', $m[3]));
            $values = substr_count($m[4], '?') ? $params : $this->splitValues($m[4]);
            $row=[]; foreach ($cols as $i=>$c) $row[$c]=$values[$i]??null;
            $rows=$this->db->load($table);
            $upsert = stripos($this->sql,'OR REPLACE')!==false || stripos($this->sql,'ON CONFLICT')!==false;
            if ($upsert && isset($row['key_name'])) {
                $found=false;
                foreach ($rows as &$r) { if (($r['key_name']??'')===$row['key_name']) { $r['value']=$row['value']??''; $found=true; break; } }
                unset($r);
                if (!$found) $rows[]=$row;
                $this->db->save($table,$rows); $this->rows=[]; return true;
            }
            $max=0; foreach ($rows as $r) $max=max($max,(int)($r['id']??0));
            if (!isset($row['id']) || $row['id']==='' || $row['id']===null) $row['id']=$max+1;
            if (!isset($row['created_at'])) $row['created_at']=date('Y-m-d H:i:s');
            $this->db->lastId=(int)$row['id']; $rows[]=$row; $this->db->save($table,$rows); $this->rows=[]; return true;
        }
        if (preg_match('/^DELETE FROM\s+([a-z_]+)(.*)$/is', $sql, $m)) {
            $rows=$this->db->load($m[1]);
            if (preg_match('/WHERE\s+(.+)/i', $m[2], $w)) {
                $where=$this->bindInline($w[1],$params);
                $rows=array_values(array_filter($rows, fn($r)=>!$this->matchWhere($r,$where)));
            } else $rows=[];
            $this->db->save($m[1],$rows); $this->rows=[]; return true;
        }
        if (preg_match('/^UPDATE\s+([a-z_]+)\s+SET\s+(.+?)(?:\s+WHERE\s+(.+))?$/is', $sql, $m)) {
            $rows=$this->db->load($m[1]); $setParts=array_map('trim', explode(',', $m[2]));
            $idx=0; $updates=[];
            foreach ($setParts as $sp) if (preg_match('/^([a-z_]+)\s*=\s*(.+)$/i',$sp,$sm)) {
                $updates[$sm[1]] = trim($sm[2])==='?' ? ($params[$idx++]??null) : $this->unquote($sm[2]);
            }
            $where=$this->bindInline($m[3]??'', array_slice($params,$idx));
            foreach ($rows as &$r) if (($m[3]??'')==='' || $this->matchWhere($r,$where)) foreach ($updates as $k=>$v) $r[$k]=$v;
            unset($r); $this->db->save($m[1],$rows); $this->rows=[]; return true;
        }
        if (preg_match('/^SELECT\s+/i', $sql)) { $this->rows=$this->runSelect($sql,$params); $this->pos=0; return true; }
        $this->rows=[]; return true;
    }
    private function runSelect($sql,$params) {
        if (preg_match('/SELECT\s+COUNT\(\*\)\s+FROM\s+([a-z_]+)(.*)$/i',$sql,$m)) {
            $rows=$this->db->load($m[1]);
            if (preg_match('/WHERE\s+(.+)/i',$m[2]??'',$w)) {
                $where=$this->bindInline($w[1],$params);
                $rows=array_values(array_filter($rows, fn($r)=>$this->matchWhere($r,$where)));
            }
            $n=count($rows); return [['COUNT(*)'=>$n,0=>$n]];
        }
        if (preg_match('/SELECT\s+COALESCE\(SUM\(([a-z_]+)\),0\)\s+FROM\s+([a-z_]+)(.*)$/i',$sql,$m)) {
            $rows=$this->db->load($m[2]);
            if (preg_match('/WHERE\s+(.+)/i',$m[3]??'',$w)) {
                $where=$this->bindInline($w[1],$params);
                $rows=array_values(array_filter($rows, fn($r)=>$this->matchWhere($r,$where)));
            }
            $sum=0; foreach ($rows as $r) $sum+=(float)($r[$m[1]]??0);
            return [['s'=>$sum,0=>$sum]];
        }
        if (!preg_match('/FROM\s+([a-z_]+)/i',$sql,$fm)) return [];
        $rows=$this->db->load($fm[1]);
        if (preg_match_all('/(?:LEFT\s+)?JOIN\s+([a-z_]+)\s+([a-z_]+)\s+ON\s+([a-z_]+)\.([a-z_]+)\s*=\s*([a-z_]+)\.([a-z_]+)/i',$sql,$joins,PREG_SET_ORDER)) {
            foreach ($joins as $j) {
                $jrows=$this->db->load($j[1]); $index=[];
                foreach ($jrows as $jr) $index[(string)($jr[$j[6]]??'')]=$jr;
                $new=[];
                foreach ($rows as $r) {
                    $match=$index[(string)($r[$j[4]]??'')]??[];
                    $merged=$r;
                    if ($j[1]==='users'||$j[2]==='u'){ $merged['user_name']=$match['name']??''; $merged['user_phone']=$match['phone']??''; }
                    if ($j[1]==='games'||$j[2]==='g'){ $merged['game_name']=$match['name']??''; }
                    if ($j[1]==='packages'||$j[2]==='p'){ $merged['package_name']=$match['name']??''; }
                    if ($j[1]==='admins'||$j[2]==='a'){ $merged['name']=$match['name']??($r['name']??''); }
                    $new[]=$merged;
                }
                $rows=$new;
            }
        }
        if (preg_match('/WHERE\s+(.+?)(?:\s+ORDER BY|\s+LIMIT|$)/i',$sql,$w)) {
            $where=$this->bindInline($w[1],$params);
            $rows=array_values(array_filter($rows, fn($r)=>$this->matchWhere($r,$where)));
        }
        if (preg_match('/ORDER BY\s+([a-z_\.]+)\s+(ASC|DESC)?/i',$sql,$o)) {
            $col=preg_replace('/^[a-z_]+\./','',$o[1]); $dir=strtoupper($o[2]??'ASC');
            usort($rows, function($a,$b) use($col,$dir){
                $va=$a[$col]??0; $vb=$b[$col]??0;
                $cmp=(is_numeric($va)&&is_numeric($vb))?($va<=>$vb):strcmp((string)$va,(string)$vb);
                return $dir==='DESC'?-$cmp:$cmp;
            });
        }
        if (preg_match('/LIMIT\s+(\d+)/i',$sql,$l)) $rows=array_slice($rows,0,(int)$l[1]);
        return array_values($rows);
    }
    public function fetch($mode=PDO::FETCH_ASSOC){ if(!isset($this->rows[$this->pos])) return false; return $this->rows[$this->pos++]; }
    public function fetchAll($mode=PDO::FETCH_ASSOC){
        if ($mode===PDO::FETCH_KEY_PAIR){ $out=[]; foreach($this->rows as $r){ $out[$r['key_name']??array_values($r)[0]]=$r['value']??(array_values($r)[1]??''); } return $out; }
        if ($mode===PDO::FETCH_COLUMN){ $out=[]; foreach($this->rows as $r) $out[]=array_values($r)[0]; return $out; }
        return $this->rows;
    }
    public function fetchColumn($i=0){ if(!isset($this->rows[0])) return false; return array_values($this->rows[0])[$i]??false; }
    private function splitValues($raw){ $out=[]; $cur=''; $q=false; for($i=0;$i<strlen($raw);$i++){ $ch=$raw[$i]; if($ch==="'"&&!$q){$q=true;continue;} if($ch==="'"&&$q){$q=false;continue;} if($ch===','&&!$q){$out[]=trim($cur);$cur='';continue;} $cur.=$ch; } if($cur!=='') $out[]=trim($cur); return $out; }
    private function unquote($v){ $v=trim($v); if(strlen($v)>=2 && (($v[0]==="'" && substr($v,-1)==="'") || ($v[0]==='"' && substr($v,-1)==='"'))) return substr($v,1,-1); return $v; }
    private function bindInline($expr,$params){ $i=0; return preg_replace_callback('/\?/', function() use(&$i,$params){ $v=$params[$i++]??''; return "'".str_replace("'","''",(string)$v)."'"; }, $expr); }
    public function matchWhere($row,$where){
        $where=trim($where); if($where==='') return true;
        foreach (preg_split('/\s+AND\s+/i',$where) as $p){
            $p=trim($p);
            if (preg_match('/(?:[a-z_]+\.)?([a-z_]+)\s*=\s*(.+)$/i',$p,$m)){ if((string)($row[$m[1]]??'')!==(string)$this->unquote(trim($m[2]))) return false; }
            elseif (preg_match('/(?:[a-z_]+\.)?([a-z_]+)\s+LIKE\s+(.+)$/i',$p,$m)){ $val=$this->unquote(trim($m[2])); $rx='/'.str_replace('%','.*',preg_quote($val,'/')).'/i'; if(!preg_match($rx,(string)($row[$m[1]]??''))) return false; }
        }
        return true;
    }
}
