<?php
require_once("_bootstrap.php");
$data=input_json(); $follower=(int)$_SESSION['user_id']; $leader=(int)($data['leader_id']??0); $fee=10.00;
$setting=$conn->query("SELECT enabled FROM copy_trading_settings WHERE id=1")->fetch_assoc();
if(empty($setting['enabled'])){http_response_code(403);echo json_encode(["success"=>false,"message"=>"Copy trading is currently disabled."]);exit;}
if($leader===$follower || !$leader){http_response_code(422);echo json_encode(["success"=>false,"message"=>"Choose a different trader to copy."]);exit;}
$leaderRow=$conn->query("SELECT id FROM users WHERE id=$leader AND role='user' AND copy_trading_enabled=1 LIMIT 1");
if(!$leaderRow||!$leaderRow->num_rows){http_response_code(404);echo json_encode(["success"=>false,"message"=>"This trader is unavailable."]);exit;}

$conn->begin_transaction();
try {
  $user=$conn->query("SELECT balance,copy_trading_enabled FROM users WHERE id=$follower FOR UPDATE")->fetch_assoc();
  if(!$user||!$user['copy_trading_enabled']) throw new Exception("Copy trading is not enabled for this account.");
  $existing=$conn->query("SELECT activation_fee_paid FROM copy_subscriptions WHERE follower_id=$follower FOR UPDATE")->fetch_assoc();
  $alreadyPaid=(bool)($existing['activation_fee_paid']??false);
  if(!$alreadyPaid){
    if((float)$user['balance']<$fee) throw new Exception("A $10.00 real balance is required for copy-trading activation.");
    $stmt=$conn->prepare("UPDATE users SET balance=balance-? WHERE id=? AND balance>=?");$stmt->bind_param("did",$fee,$follower,$fee);$stmt->execute();
    if($stmt->affected_rows!==1) throw new Exception("Your real balance changed. Please try again.");
    $stmt=$conn->prepare("INSERT INTO copy_trading_activation_fees (user_id,amount) VALUES (?,?)");$stmt->bind_param("id",$follower,$fee);$stmt->execute();
  }
  $stmt=$conn->prepare("INSERT INTO copy_subscriptions (follower_id,leader_id,active,activation_fee_paid,activation_paid_at) VALUES (?,?,1,1,NOW()) ON DUPLICATE KEY UPDATE leader_id=VALUES(leader_id),active=1,activation_fee_paid=1,activation_paid_at=COALESCE(activation_paid_at,NOW())");$stmt->bind_param("ii",$follower,$leader);$stmt->execute();
  $balance=$conn->query("SELECT balance FROM users WHERE id=$follower")->fetch_assoc();
  $conn->commit();
  echo json_encode(["success"=>true,"activation_fee_charged"=>!$alreadyPaid,"balance"=>(float)$balance['balance']]);
} catch(Throwable $error) {
  $conn->rollback(); http_response_code(403); echo json_encode(["success"=>false,"message"=>$error->getMessage()]);
}
?>
