<?php
session_start();
require_once '../config/db.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Admin-Token');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }

define('ADMIN_SECRET_TOKEN', 'leoexx_admin_2025_secure_token');

$rawBody = file_get_contents('php://input');
$input   = json_decode($rawBody, true);

$sessionOk = isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true;
$headerTok = $_SERVER['HTTP_X_ADMIN_TOKEN'] ?? '';
$bodyTok   = $input['_token'] ?? '';
$tokenOk   = ($headerTok === ADMIN_SECRET_TOKEN) || ($bodyTok === ADMIN_SECRET_TOKEN);

if (!$sessionOk && !$tokenOk) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit();
}
if (!$input) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
    exit();
}

function ensureCol($conn, $table, $col, $def) {
    $c = mysqli_query($conn, "SHOW COLUMNS FROM `$table` LIKE '$col'");
    if ($c && mysqli_num_rows($c) === 0) {
        mysqli_query($conn, "ALTER TABLE `$table` ADD COLUMN `$col` $def");
    }
}

ensureCol($conn, 'users', 'stop_roi',        'TINYINT(1) NOT NULL DEFAULT 0');
ensureCol($conn, 'users', 'stop_level',      'TINYINT(1) NOT NULL DEFAULT 0');
ensureCol($conn, 'users', 'stop_all',        'TINYINT(1) NOT NULL DEFAULT 0');
ensureCol($conn, 'users', 'admin_inactive',  'TINYINT(1) NOT NULL DEFAULT 0');
ensureCol($conn, 'users', 'activation_date', 'DATETIME NULL DEFAULT NULL');
ensureCol($conn, 'users', 'is_blocked',      'TINYINT(1) NOT NULL DEFAULT 0');
ensureCol($conn, 'users', 'is_active',       'TINYINT(1) NOT NULL DEFAULT 0');
ensureCol($conn, 'users', 'blocked_reason',  'VARCHAR(255) NULL DEFAULT NULL');
ensureCol($conn, 'users', 'blocked_at',      'DATETIME NULL DEFAULT NULL');
ensureCol($conn, 'users', 'reward_tier_1',   'TINYINT(1) NOT NULL DEFAULT 0');
ensureCol($conn, 'users', 'reward_tier_2',   'TINYINT(1) NOT NULL DEFAULT 0');
ensureCol($conn, 'users', 'reward_tier_3',   'TINYINT(1) NOT NULL DEFAULT 0');

$wallet = trim($input['old_wallet'] ?? $input['wallet'] ?? '');
if (empty($wallet)) {
    echo json_encode(['status' => 'error', 'message' => 'Missing wallet']);
    exit();
}
$w = mysqli_real_escape_string($conn, $wallet);

$existCheck = mysqli_fetch_assoc(mysqli_query($conn, "SELECT wallet FROM users WHERE wallet='$w' LIMIT 1"));
if (!$existCheck) {
    echo json_encode(['status' => 'error', 'message' => 'User not found: ' . $wallet]);
    exit();
}

// ══ STOP PAYMENT ══
if (isset($input['stop_roi']) || isset($input['stop_level']) || isset($input['stop_all'])) {
    $stop_roi   = intval($input['stop_roi']   ?? 0);
    $stop_level = intval($input['stop_level'] ?? 0);
    $stop_all   = intval($input['stop_all']   ?? 0);
    if ($stop_all === 1) { $stop_roi = 1; $stop_level = 1; }
    $res = mysqli_query($conn, "UPDATE users SET stop_roi=$stop_roi, stop_level=$stop_level, stop_all=$stop_all WHERE wallet='$w'");
    echo json_encode(['status' => $res ? 'success' : 'error', 'message' => $res ? 'Payment settings saved' : mysqli_error($conn)]);
    exit();
}

// ══ REWARD TIERS ══
if (isset($input['reward_tier_1']) || isset($input['reward_tier_2']) || isset($input['reward_tier_3'])) {
    $t1 = intval($input['reward_tier_1'] ?? 0);
    $t2 = intval($input['reward_tier_2'] ?? 0);
    $t3 = intval($input['reward_tier_3'] ?? 0);
    if ($t3) { $t1 = 1; $t2 = 1; }
    if ($t2) { $t1 = 1; }
    $res = mysqli_query($conn, "UPDATE users SET reward_tier_1=$t1, reward_tier_2=$t2, reward_tier_3=$t3 WHERE wallet='$w'");
    $rate = $t3 ? 7 : ($t2 ? 6 : ($t1 ? 5 : 4));
    echo json_encode(['status' => $res ? 'success' : 'error', 'message' => "Reward tiers saved. Rate: {$rate}%", 'affected' => mysqli_affected_rows($conn)]);
    exit();
}

// ══ LEVELS ══
if (isset($input['levels']) && is_array($input['levels'])) {
    $levelsClean = [];
    for ($i = 1; $i <= 10; $i++) {
        $val = $input['levels'][$i] ?? $input['levels'][(string)$i] ?? false;
        $levelsClean[$i] = (bool)$val;
    }
    $levelsJson = mysqli_real_escape_string($conn, json_encode($levelsClean));
    $res = mysqli_query($conn, "UPDATE users SET levels='$levelsJson' WHERE wallet='$w'");
    echo json_encode(['status' => $res ? 'success' : 'error', 'message' => $res ? 'Levels saved' : mysqli_error($conn)]);
    exit();
}

// ══════════════════════════════════════════════════════
// MAIN EDIT — name, email, mobile, password, wallet,
//             referral_id, status — SATH MEIN UPDATE
// ══════════════════════════════════════════════════════
$parts = [];

if (!empty($input['name']))
    $parts[] = "`name`='"     . mysqli_real_escape_string($conn, trim($input['name']))     . "'";
if (!empty($input['email']))
    $parts[] = "`email`='"    . mysqli_real_escape_string($conn, trim($input['email']))    . "'";
if (!empty($input['mobile']))
    $parts[] = "`mobile`='"   . mysqli_real_escape_string($conn, trim($input['mobile']))   . "'";
if (!empty($input['password']))
    $parts[] = "`password`='" . mysqli_real_escape_string($conn, trim($input['password'])) . "'";
if (isset($input['referral_id']))
    $parts[] = "`referral_id`='" . mysqli_real_escape_string($conn, trim($input['referral_id'])) . "'";

// ✅ Status bhi saath update hoga
if (isset($input['status']) && in_array($input['status'], ['blocked','active','inactive'])) {
    $newStatus = $input['status'];
    if ($newStatus === 'blocked') {
        $parts[] = "`status`='blocked'";
        $parts[] = "`is_blocked`=1";
        $parts[] = "`is_active`=0";
        $parts[] = "`admin_inactive`=0";
        $parts[] = "`blocked_reason`='Admin manually blocked'";
        $parts[] = "`blocked_at`=NOW()";
    } elseif ($newStatus === 'active') {
        $checkAct = mysqli_fetch_assoc(mysqli_query($conn, "SELECT activation_date FROM users WHERE wallet='$w'"));
        if (empty($checkAct['activation_date'])) {
            mysqli_query($conn, "UPDATE users SET activation_date=NOW() WHERE wallet='$w'");
        }
        $parts[] = "`status`='active'";
        $parts[] = "`is_blocked`=0";
        $parts[] = "`is_active`=1";
        $parts[] = "`admin_inactive`=0";
        $parts[] = "`blocked_reason`=NULL";
        $parts[] = "`blocked_at`=NULL";
    } else {
        $parts[] = "`status`='inactive'";
        $parts[] = "`is_blocked`=0";
        $parts[] = "`is_active`=0";
        $parts[] = "`admin_inactive`=1";
    }
}

// ✅ Wallet change
if (isset($input['new_wallet']) && trim($input['new_wallet']) !== '' && trim($input['new_wallet']) !== $wallet) {
    $newW = mysqli_real_escape_string($conn, trim($input['new_wallet']));
    $dupCheck = mysqli_fetch_assoc(mysqli_query($conn, "SELECT wallet FROM users WHERE wallet='$newW' LIMIT 1"));
    if ($dupCheck) {
        echo json_encode(['status' => 'error', 'message' => 'Wallet already in use']);
        exit();
    }
    $parts[] = "`wallet`='$newW'";
}

if (empty($parts)) {
    echo json_encode(['status' => 'error', 'message' => 'No fields to update']);
    exit();
}

$sql = "UPDATE users SET " . implode(', ', $parts) . " WHERE wallet='$w'";
$res = mysqli_query($conn, $sql);

if (!$res) {
    echo json_encode(['status' => 'error', 'message' => 'SQL Error: ' . mysqli_error($conn), 'sql' => $sql]);
} else {
    echo json_encode([
        'status'   => 'success',
        'message'  => 'User updated successfully',
        'affected' => mysqli_affected_rows($conn)
    ]);
}
?>