<?php
// api/resellers_api.php - CORREÇÃO: NOME DO CRIADOR (PARENT)
header('Content-Type: application/json');
session_start();
require_once '../includes/db.php';

if (!isset($_SESSION['logged_in_fxtream'])) { die(json_encode(['status'=>false, 'msg'=>'Acesso negado'])); }

$action = $_POST['action'] ?? '';
$my_id = $_SESSION['user_id'];
$is_admin = (($_SESSION['role'] ?? '') === 'admin');

// Busca URL do Painel
$painel_url = "https://" . $_SERVER['HTTP_HOST'];
try {
    $c = $pdo->query("SELECT dominio_url FROM configuracoes LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if($c && !empty($c['dominio_url'])) {
        $painel_url = rtrim($c['dominio_url'], '/');
        if (!preg_match("~^(?:f|ht)tps?://~i", $painel_url)) $painel_url = "http://" . $painel_url;
    }
} catch(Exception $e){}

switch($action) {
    case 'list':
        // === SQL ROBUSTO PARA PEGAR O NOME DO PAI ===
        // Seleciona tudo de 'r' (revendedor) e o 'username' de 'p' (pai) como 'parent_name'
        $sql = "SELECT r.id, r.username, r.email, r.credits, r.active, r.parent_id, 
                       p.username AS parent_name 
                FROM revendedores r 
                LEFT JOIN revendedores p ON r.parent_id = p.id ";
        
        if ($is_admin) {
            $sql .= "ORDER BY r.id DESC";
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
        } else {
            $sql .= "WHERE r.parent_id = ? ORDER BY r.id DESC";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$my_id]);
        }
        
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Debug caso venha vazio (opcional, mas bom pra garantir)
        // foreach($results as &$row) { if(empty($row['parent_name'])) $row['parent_name'] = null; }

        echo json_encode($results);
    break;

    case 'save':
        $id = $_POST['id'];
        $user = trim($_POST['username']);
        $pass = trim($_POST['password']);
        $email = trim($_POST['email']);
        $credits = intval($_POST['credits']);

        if(empty($user)) { echo json_encode(['status'=>false, 'msg'=>'Login obrigatório']); exit; }

        if(empty($id)) {
            // CRIAR
            if(empty($pass)) { echo json_encode(['status'=>false, 'msg'=>'Senha obrigatória']); exit; }
            
            $chk = $pdo->prepare("SELECT id FROM revendedores WHERE username = ?");
            $chk->execute([$user]);
            if($chk->rowCount() > 0) { echo json_encode(['status'=>false, 'msg'=>'Usuário já existe']); exit; }

            if(!$is_admin) {
                $stmtC = $pdo->prepare("SELECT credits FROM revendedores WHERE id = ?");
                $stmtC->execute([$my_id]);
                $myCreds = $stmtC->fetchColumn();

                if($myCreds < $credits) { echo json_encode(['status'=>false, 'msg'=>'Saldo insuficiente']); exit; }
                
                $pdo->prepare("UPDATE revendedores SET credits = credits - ? WHERE id = ?")->execute([$credits, $my_id]);
            }

            $sql = "INSERT INTO revendedores (username, password, email, credits, parent_id, active, created_at, role) VALUES (?, ?, ?, ?, ?, 1, NOW(), 'reseller')";
            
            if($pdo->prepare($sql)->execute([$user, $pass, $email, $credits, $my_id])) {
                echo json_encode([
                    'status'=>true, 
                    'msg'=>'Revendedor criado!',
                    'new_reseller' => [
                        'username' => $user,
                        'password' => $pass,
                        'url' => $painel_url,
                        'credits' => $credits
                    ]
                ]);
            } else {
                echo json_encode(['status'=>false, 'msg'=>'Erro ao gravar']);
            }
        } else {
            // EDITAR
            $sql = "UPDATE revendedores SET username = ?, email = ? WHERE id = ?";
            $params = [$user, $email, $id];
            
            if(!empty($pass)) {
                $sql = "UPDATE revendedores SET username = ?, email = ?, password = ? WHERE id = ?";
                $params = [$user, $email, $pass, $id];
            }
            
            if($pdo->prepare($sql)->execute($params)) {
                echo json_encode(['status'=>true, 'msg'=>'Atualizado!']);
            }
        }
    break;

    case 'manage_credits':
        $target_id = $_POST['id'];
        $type = $_POST['type']; 
        $amount = intval($_POST['amount']);

        if($amount < 1) { echo json_encode(['status'=>false, 'msg'=>'Valor inválido']); exit; }

        $targetName = $pdo->query("SELECT username FROM revendedores WHERE id = $target_id")->fetchColumn();

        if($type == 'add') {
            if(!$is_admin) {
                $stmtC = $pdo->prepare("SELECT credits FROM revendedores WHERE id = ?");
                $stmtC->execute([$my_id]);
                $myCreds = $stmtC->fetchColumn();

                if($myCreds < $amount) { echo json_encode(['status'=>false, 'msg'=>'Seu saldo é insuficiente']); exit; }
                
                $pdo->prepare("UPDATE revendedores SET credits = credits - ? WHERE id = ?")->execute([$amount, $my_id]);
            }
            $pdo->prepare("UPDATE revendedores SET credits = credits + ? WHERE id = ?")->execute([$amount, $target_id]);
            
            echo json_encode([
                'status'=>true, 
                'msg'=>'Créditos adicionados!',
                'credit_info' => [
                    'username' => $targetName,
                    'amount' => $amount
                ]
            ]);

        } else {
            $pdo->prepare("UPDATE revendedores SET credits = credits - ? WHERE id = ?")->execute([$amount, $target_id]);
            if(!$is_admin) {
                $pdo->prepare("UPDATE revendedores SET credits = credits + ? WHERE id = ?")->execute([$amount, $my_id]);
            }
            echo json_encode(['status'=>true, 'msg'=>'Créditos removidos!']);
        }
    break;

    case 'delete':
        $pdo->prepare("DELETE FROM revendedores WHERE id = ?")->execute([$_POST['id']]);
        echo json_encode(['status'=>true]);
    break;
}
?>