<?php
require_once("_guard.php");
$conn->query("CREATE TABLE IF NOT EXISTS copy_trading_settings (id TINYINT PRIMARY KEY, enabled TINYINT(1) NOT NULL DEFAULT 1)");$conn->query("INSERT IGNORE INTO copy_trading_settings (id,enabled) VALUES (1,1)");$columns=$conn->query("SHOW COLUMNS FROM users LIKE 'copy_trading_enabled'");if($columns&&$columns->num_rows===0)$conn->query("ALTER TABLE users ADD COLUMN copy_trading_enabled TINYINT(1) NOT NULL DEFAULT 1");$provider=$conn->query("SHOW COLUMNS FROM users LIKE 'copy_provider_enabled'");if($provider&&$provider->num_rows===0)$conn->query("ALTER TABLE users ADD COLUMN copy_provider_enabled TINYINT(1) NOT NULL DEFAULT 0");$approval=$conn->query("SHOW COLUMNS FROM users LIKE 'copy_provider_admin_approved'");if($approval&&$approval->num_rows===0)$conn->query("ALTER TABLE users ADD COLUMN copy_provider_admin_approved TINYINT(1) NOT NULL DEFAULT 0");
if($_SERVER['REQUEST_METHOD']==='POST'){$data=json_decode(file_get_contents('php://input'),true)?:[];$action=$data['action']??'';if($action==='global'){$enabled=!empty($data['enabled'])?1:0;$conn->query("UPDATE copy_trading_settings SET enabled=$enabled WHERE id=1");}if($action==='user'){$id=(int)($data['user_id']??0);$enabled=!empty($data['enabled'])?1:0;if($id)$conn->query("UPDATE users SET copy_trading_enabled=$enabled WHERE id=$id");}if($action==='provider'){$id=(int)($data['user_id']??0);$enabled=!empty($data['enabled'])?1:0;if($id)$conn->query("UPDATE users SET copy_provider_enabled=$enabled,copy_provider_admin_approved=$enabled WHERE id=$id");}echo json_encode(["success"=>true]);exit;}
$setting=$conn->query("SELECT enabled FROM copy_trading_settings WHERE id=1")->fetch_assoc();$rows=[];$r=$conn->query("SELECT u.id,u.full_name,u.email,u.copy_trading_enabled,u.copy_provider_enabled,u.copy_provider_admin_approved,COUNT(s.id) followers FROM users u LEFT JOIN copy_subscriptions s ON s.leader_id=u.id AND s.active=1 WHERE u.role='user' GROUP BY u.id ORDER BY followers DESC,u.full_name LIMIT 100");while($r&&($row=$r->fetch_assoc()))$rows[]=$row;echo json_encode(["success"=>true,"enabled"=>(bool)$setting['enabled'],"users"=>$rows]);
?>
