<?php
require_once("_bootstrap.php");
$id=(int)$_SESSION['user_id'];$data=input_json();$enable=!empty($data['enabled']);
if($enable){$metrics=$conn->query("SELECT COUNT(*) trades,COALESCE(SUM(net_pl),0) profit,COALESCE(AVG(net_pl>0)*100,0) win_rate FROM trade_sessions WHERE user_id=$id AND created_at>=DATE_SUB(NOW(),INTERVAL 30 DAY)")->fetch_assoc();$account=$conn->query("SELECT copy_trading_enabled,copy_provider_admin_approved FROM users WHERE id=$id")->fetch_assoc();$automatic=(int)$metrics['trades']>=20&&(float)$metrics['profit']>0&&(float)$metrics['win_rate']>=55;if(!$account||!$account['copy_trading_enabled']||(!$automatic&&!$account['copy_provider_admin_approved'])){http_response_code(422);echo json_encode(["success"=>false,"message"=>"Complete all provider eligibility requirements first."]);exit;}}
$stmt=$conn->prepare("UPDATE users SET copy_provider_enabled=? WHERE id=?");$value=$enable?1:0;$stmt->bind_param("ii",$value,$id);$stmt->execute();echo json_encode(["success"=>true,"enabled"=>$enable]);
?>
