<?php
// MJ Marketplace existing-site updater v3.0.4.2.14
@ini_set('display_errors','0'); @ini_set('log_errors','1'); @set_time_limit(60);
function h($v){return htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');}
$root=dirname(__DIR__); $cfgFile=$root.'/includes/config.php'; $msg=[]; $err=[];
function mj_pdo_opts(){ $o=[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,PDO::ATTR_EMULATE_PREPARES=>false]; if(defined('PDO::MYSQL_ATTR_USE_BUFFERED_QUERY')){$o[PDO::MYSQL_ATTR_USE_BUFFERED_QUERY]=true;} return $o; }
function mj_close_stmt($st){ if($st instanceof PDOStatement){ try{ if($st->columnCount()>0){$st->fetchAll(PDO::FETCH_NUM);} }catch(Exception $e){} while(true){ try{ if(!$st->nextRowset()) break; if($st->columnCount()>0){$st->fetchAll(PDO::FETCH_NUM);} }catch(Exception $e){break;} } try{$st->closeCursor();}catch(Exception $e){} } }
function mj_exec_sql($pdo,$sql){ $sql=trim((string)$sql); if($sql==='') return 0; $st=null; try{ $st=$pdo->query($sql); $n=($st instanceof PDOStatement)?$st->rowCount():0; mj_close_stmt($st); return $n; }catch(Exception $e){ mj_close_stmt($st); throw $e; } }
function split_sql_simple($sql){$out=[];$buf='';$inStr=false;$quote='';$len=strlen($sql);for($i=0;$i<$len;$i++){ $ch=$sql[$i]; $next=$i+1<$len?$sql[$i+1]:''; if(!$inStr && $ch==='-' && $next==='-'){ while($i<$len && $sql[$i]!=="\n") $i++; continue; } if(!$inStr && $ch==='#'){ while($i<$len && $sql[$i]!=="\n") $i++; continue; } if(($ch==="'"||$ch==='"') && ($i==0||$sql[$i-1] !== '\\')){ if(!$inStr){$inStr=true;$quote=$ch;} elseif($quote===$ch){$inStr=false;$quote='';} } if($ch===';' && !$inStr){$s=trim($buf); if($s!=='') $out[]=$s; $buf='';} else $buf.=$ch; } $s=trim($buf); if($s!=='') $out[]=$s; return $out;}
if($_SERVER['REQUEST_METHOD']==='POST'){
  try{
    if(file_exists($cfgFile)){ $cfg=include $cfgFile; }
    else { $cfg=['db_host'=>$_POST['db_host']??'localhost','db_name'=>$_POST['db_name']??'','db_user'=>$_POST['db_user']??'','db_pass'=>$_POST['db_pass']??'']; }
    $pdo=new PDO('mysql:host='.$cfg['db_host'].';dbname='.$cfg['db_name'].';charset=utf8mb4',$cfg['db_user'],$cfg['db_pass'],mj_pdo_opts());
    $sqlFile=__DIR__.'/update_to_v3.0.4.2.9.sql'; if(!file_exists($sqlFile)) throw new Exception('Update SQL file missing.');
    $stmts=split_sql_simple(file_get_contents($sqlFile)); $ok=0; $skip=0;
    foreach($stmts as $s){ if(trim($s)==='') continue; try { mj_exec_sql($pdo,$s); $ok++; } catch(Exception $ex){ $m=$ex->getMessage(); if(stripos($m,'Duplicate column')!==false || stripos($m,'Duplicate key name')!==false || stripos($m,'already exists')!==false){ $skip++; continue; } throw $ex; } }
    $msg[]='Update completed successfully. Statements run: '.$ok.'; safe skipped: '.$skip;
  } catch(Exception $e){ $err[]=$e->getMessage(); }
}
?><!doctype html><html><head><meta charset="utf-8"><title>MJ Marketplace Updater</title><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{font-family:Arial;background:#f6f8fb;margin:0}.box{max-width:760px;margin:40px auto;background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:24px}.ok{color:#047857}.bad{color:#b91c1c}input{width:100%;padding:10px;margin:5px 0 12px;border:1px solid #ddd;border-radius:8px}button,.btn{background:#111827;color:#fff;border:0;border-radius:8px;padding:10px 14px;text-decoration:none;display:inline-block}</style></head><body><div class="box"><h1>MJ Marketplace Updater</h1><p>Safe update to v3.0.4.2.14. It creates missing tables/columns only and does not delete data.</p><?php foreach($msg as $m) echo '<p class="ok">'.h($m).'</p>'; foreach($err as $e) echo '<p class="bad">'.h($e).'</p>'; ?><form method="post"><?php if(!file_exists($cfgFile)): ?><label>DB Host</label><input name="db_host" value="localhost"><label>DB Name</label><input name="db_name"><label>DB User</label><input name="db_user"><label>DB Password</label><input name="db_pass" type="password"><?php else: ?><p class="ok">Using existing includes/config.php database connection.</p><?php endif; ?><button type="submit">Run Safe Update Now</button> <a class="btn" href="../admin/system-test.php">Open System Test</a></form></div></body></html>
