<?php
/**
 * classes/Investment.php
 * Motor completo de Investimentos com rendimento progressivo
 */
class Investment extends DBConnection
{
    private $settings;

    public function __construct() {
        global $_settings;
        $this->settings = $_settings;
        parent::__construct();
    }

    // ══════════════════════════════════════════════════════
    // ── SEÇÃO 1: ATIVAR PLANO ─────────────────────────────
    // ══════════════════════════════════════════════════════

    /**
     * Ativa um plano de investimento para o usuário.
     * Debita da carteira e cria o registro de investimento.
     */
    public function activate_plan($customer_id, $plan_id, $custom_amount = null) {
        $cid    = (int) $customer_id;
        $pid    = (int) $plan_id;

        require_once BASE_APP . 'includes/wallet-functions.php';

        // 1. Busca o plano
        $plan = $this->conn->query(
            "SELECT * FROM investment_plans WHERE id=$pid AND is_active=1"
        )->fetch_assoc();

        if (!$plan) {
            return ['status' => 'failed', 'msg' => 'Plano não encontrado ou inativo.'];
        }

        // 2. Define o valor de investimento
        $amount = $custom_amount ? (float)$custom_amount : (float)$plan['min_amount'];

        if ($amount < (float)$plan['min_amount']) {
            return ['status' => 'failed', 'msg' => 'Valor abaixo do mínimo do plano (R$ '.number_format($plan['min_amount'],2,',','.').')'];
        }
        if ($plan['max_amount'] > 0 && $amount > (float)$plan['max_amount']) {
            return ['status' => 'failed', 'msg' => 'Valor acima do máximo do plano (R$ '.number_format($plan['max_amount'],2,',','.').')'];
        }

        // 3. Verifica se já tem plano ativo (uma instância a mais por plano é permitida?)
        $active_same = $this->conn->query(
            "SELECT id FROM investments WHERE customer_id=$cid AND plan_id=$pid AND status=1"
        )->num_rows;
        if ($active_same > 0 && !$plan['allow_multiple']) {
            return ['status' => 'failed', 'msg' => 'Você já tem este plano ativo.'];
        }

        // 4. Verifica saldo
        $wallet = wallet_get($cid);
        if ((float)$wallet['balance_available'] < $amount) {
            return [
                'status' => 'no_balance',
                'msg'    => 'Saldo insuficiente. Deposite mais para continuar.',
                'balance' => (float)$wallet['balance_available'],
                'needed'  => $amount,
            ];
        }

        // 5. Calcula teto máximo (cap)
        $cap_limit = round($amount * ((float)$plan['cap_percent'] / 100), 2);

        // 6. Debita da carteira
        $debited = wallet_debit($cid, $amount, 'investment',
                                "Investimento — " . $plan['name'], null, 'investment');
        if (!$debited) {
            return ['status' => 'failed', 'msg' => 'Erro ao debitar saldo. Tente novamente.'];
        }

        // 7. Cria o investimento
        $this->conn->query("INSERT INTO investments SET
            customer_id     = $cid,
            plan_id         = $pid,
            amount_invested = $amount,
            daily_rate      = {$plan['daily_rate']},
            cap_percent     = {$plan['cap_percent']},
            cap_limit       = $cap_limit,
            last_yield_at   = CURDATE()");   // Yield começa amanhã

        $inv_id = $this->conn->insert_id;

        // 8. Atualiza volume binário
        require_once BASE_APP . 'classes/MLM.php';
        $mlm = new MLM();
        $mlm->update_binary_volumes($cid, $amount);

        // 9. WhatsApp de confirmação
        enqueue_whatsapp($cid, 'investment_activated', $amount);

        return [
            'status'    => 'success',
            'inv_id'    => $inv_id,
            'amount'    => $amount,
            'cap'       => $cap_limit,
            'daily_rate' => $plan['daily_rate'],
            'msg'       => 'Plano ativado com sucesso! Seu primeiro rendimento chegará amanhã.',
        ];
    }

    // ══════════════════════════════════════════════════════
    // ── SEÇÃO 2: UPGRADE DE PLANO ─────────────────────────
    // ══════════════════════════════════════════════════════

    /**
     * Faz upgrade de um investimento existente para um plano superior.
     * Cobra apenas a diferença de valor.
     */
    public function upgrade_plan($investment_id, $customer_id, $new_plan_id) {
        $inv_id = (int) $investment_id;
        $cid    = (int) $customer_id;
        $npid   = (int) $new_plan_id;

        require_once BASE_APP . 'includes/wallet-functions.php';

        $inv = $this->conn->query(
            "SELECT i.*, p.name as plan_name FROM investments i
             JOIN investment_plans p ON i.plan_id=p.id
             WHERE i.id=$inv_id AND i.customer_id=$cid AND i.status=1"
        )->fetch_assoc();

        if (!$inv) return ['status' => 'failed', 'msg' => 'Investimento não encontrado.'];

        $new_plan = $this->conn->query(
            "SELECT * FROM investment_plans WHERE id=$npid AND is_active=1"
        )->fetch_assoc();

        if (!$new_plan) return ['status' => 'failed', 'msg' => 'Plano destino inválido.'];

        $old_amount = (float)$inv['amount_invested'];
        $new_min    = (float)$new_plan['min_amount'];

        if ($new_min <= $old_amount) {
            return ['status' => 'failed', 'msg' => 'Faça upgrade para um plano superior.'];
        }

        $diff = round($new_min - $old_amount, 2);

        $wallet = wallet_get($cid);
        if ((float)$wallet['balance_available'] < $diff) {
            return ['status' => 'no_balance',
                    'msg'    => "Saldo insuficiente. Você precisa de mais R$ ".number_format($diff,2,',','.')];
        }

        // Debita a diferença
        wallet_debit($cid, $diff, 'upgrade',
                     "Upgrade para " . $new_plan['name'], $inv_id, 'investment');

        $new_amount    = $old_amount + $diff;
        $new_cap_limit = round($new_amount * ((float)$new_plan['cap_percent'] / 100), 2);

        // Atualiza o investimento
        $this->conn->query("UPDATE investments SET
            plan_id         = $npid,
            amount_invested = $new_amount,
            daily_rate      = {$new_plan['daily_rate']},
            cap_percent     = {$new_plan['cap_percent']},
            cap_limit       = $new_cap_limit
            WHERE id=$inv_id");

        enqueue_whatsapp($cid, 'investment_upgraded', $new_amount);

        return [
            'status'    => 'success',
            'diff_paid' => $diff,
            'new_amount' => $new_amount,
            'msg'       => "Upgrade feito com sucesso!",
        ];
    }

    // ══════════════════════════════════════════════════════
    // ── SEÇÃO 3: PROCESSAR YIELDS (CRON) ──────────────────
    // ══════════════════════════════════════════════════════

    /**
     * Processa rendimentos diários de todos os investimentos ativos.
     * Inclui comissões unilevel e atualização de volumes binários.
     */
    public function process_daily_yields() {
        require_once BASE_APP . 'includes/wallet-functions.php';
        require_once BASE_APP . 'classes/MLM.php';

        $mlm = new MLM();
        $log = [];

        $investments = $this->conn->query(
            "SELECT i.*, p.name as plan_name, c.phone, c.firstname
             FROM investments i
             JOIN investment_plans p ON i.plan_id = p.id
             JOIN customer_list c ON i.customer_id = c.id
             WHERE i.status = 1
             AND (i.last_yield_at IS NULL OR DATE(i.last_yield_at) < CURDATE())"
        );

        while ($inv = $investments->fetch_assoc()) {
            $cid    = (int)   $inv['customer_id'];
            $inv_id = (int)   $inv['id'];
            $rate   = (float) $inv['daily_rate'];
            $amount = (float) $inv['amount_invested'];
            $earned = (float) $inv['amount_earned'];
            $cap    = (float) $inv['cap_limit'];

            // Calcula yield do dia
            $yield = round($amount * ($rate / 100), 2);
            if ($yield < 0.01) continue;

            // Ajusta se ultrapassaria o teto
            $will_complete = false;
            if (($earned + $yield) >= $cap) {
                $yield         = max(0, round($cap - $earned, 2));
                $will_complete = true;
            }

            if ($yield < 0.01 && $will_complete) {
                // Apenas encerra
                $this->conn->query("UPDATE investments SET
                    status=2, ended_at=NOW() WHERE id=$inv_id");
                enqueue_whatsapp($cid, 'investment_completed', $amount);
                $log[] = "🎉 Inv #$inv_id ({$inv['firstname']}) atingiu teto — encerrado.";
                continue;
            }

            // Registra yield
            $day_num = (int)$this->conn->query(
                "SELECT COUNT(*)+1 as d FROM investment_yields WHERE investment_id=$inv_id"
            )->fetch_assoc()['d'];

            $this->conn->query("INSERT INTO investment_yields SET
                investment_id=$inv_id, customer_id=$cid,
                amount=$yield, day_number=$day_num");

            // Credita na carteira
            wallet_credit($cid, $yield, 'yield',
                          "Rendimento dia $day_num — {$inv['plan_name']}",
                          $inv_id, 'investment');

            // Atualiza investimento
            $new_earned = round($earned + $yield, 2);
            if ($will_complete) {
                $this->conn->query("UPDATE investments SET
                    amount_earned=$new_earned, status=2, ended_at=NOW(), last_yield_at=NOW()
                    WHERE id=$inv_id");
                enqueue_whatsapp($cid, 'investment_completed', $amount);
            } else {
                $this->conn->query("UPDATE investments SET
                    amount_earned=$new_earned, last_yield_at=NOW()
                    WHERE id=$inv_id");
                enqueue_whatsapp($cid, 'yield_received', $yield);
            }

            // Comissões unilevel
            $mlm->process_unilevel_commissions($cid, $yield, $inv_id);

            // Volumes binários
            $mlm->update_binary_volumes($cid, $yield);

            $pct = $cap > 0 ? round(($new_earned / $cap) * 100, 1) : 0;
            $log[] = ($will_complete ? '🎉' : '📈')
                     . " Inv #$inv_id ({$inv['firstname']}): +R$"
                     . number_format($yield,2,',','.')
                     . " | Total: {$pct}% do teto";
        }

        return $log;
    }

    // ══════════════════════════════════════════════════════
    // ── SEÇÃO 4: CRUD DE PLANOS (ADMIN) ───────────────────
    // ══════════════════════════════════════════════════════

    public function save_plan() {
        $id          = (int)($_POST['id'] ?? 0);
        $name        = $this->conn->real_escape_string($_POST['name']);
        $description = $this->conn->real_escape_string($_POST['description'] ?? '');
        $min_amount  = (float)str_replace(['.', ','], ['', '.'], $_POST['min_amount']);
        $max_amount  = (float)str_replace(['.', ','], ['', '.'], ($_POST['max_amount'] ?? 0));
        $daily_rate  = (float)str_replace([','], ['.'], $_POST['daily_rate']);
        $cap_percent = (float)str_replace([','], ['.'], $_POST['cap_percent']);
        $icon        = $this->conn->real_escape_string($_POST['icon'] ?? '💎');
        $color       = $this->conn->real_escape_string($_POST['color'] ?? '#6c5ce7');
        $sort_order  = (int)($_POST['sort_order'] ?? 0);
        $allow_multi = isset($_POST['allow_multiple']) ? 1 : 0;
        $featured    = isset($_POST['featured']) ? 1 : 0;
        $is_active   = (int)($_POST['is_active'] ?? 1);

        if (empty($id)) {
            $this->conn->query("INSERT INTO investment_plans SET
                name='$name', description='$description',
                min_amount=$min_amount, max_amount=$max_amount,
                daily_rate=$daily_rate, cap_percent=$cap_percent,
                icon='$icon', color='$color',
                sort_order=$sort_order,
                allow_multiple=$allow_multi,
                featured=$featured, is_active=$is_active");
            $pid = $this->conn->insert_id;
        } else {
            $this->conn->query("UPDATE investment_plans SET
                name='$name', description='$description',
                min_amount=$min_amount, max_amount=$max_amount,
                daily_rate=$daily_rate, cap_percent=$cap_percent,
                icon='$icon', color='$color',
                sort_order=$sort_order,
                allow_multiple=$allow_multi,
                featured=$featured, is_active=$is_active
                WHERE id=$id");
            $pid = $id;
        }

        return $this->conn->error
            ? ['status' => 'failed', 'msg' => $this->conn->error]
            : ['status' => 'success', 'pid' => $pid];
    }

    // ══════════════════════════════════════════════════════
    // ── SEÇÃO 5: DADOS PARA DASHBOARD ─────────────────────
    // ══════════════════════════════════════════════════════

    public function get_user_investments($customer_id) {
        $cid = (int) $customer_id;
        return $this->conn->query(
            "SELECT i.*, p.name as plan_name, p.color, p.icon, p.daily_rate as plan_rate
             FROM investments i
             JOIN investment_plans p ON i.plan_id = p.id
             WHERE i.customer_id = $cid
             ORDER BY i.status ASC, i.created_at DESC"
        );
    }

    public function get_yield_history($customer_id, $limit = 30) {
        $cid = (int) $customer_id;
        return $this->conn->query(
            "SELECT iy.*, p.name as plan_name, p.icon
             FROM investment_yields iy
             JOIN investments i ON iy.investment_id = i.id
             JOIN investment_plans p ON i.plan_id = p.id
             WHERE iy.customer_id = $cid
             ORDER BY iy.created_at DESC LIMIT $limit"
        );
    }
}

// ── Roteador ─────────────────────────────────────────────
require_once '../settings.php';
$inv_class = new Investment();
$action    = strtolower($_GET['f'] ?? '');

switch ($action) {
    case 'activate':
        header('Content-Type: application/json');
        $cid = (int)($_settings->userdata('id') ?? 0);
        if (!$cid) { echo json_encode(['status'=>'failed','msg'=>'Não autorizado.']); exit(); }
        $pid    = (int)($_POST['plan_id'] ?? 0);
        $custom = !empty($_POST['custom_amount'])
                  ? (float)str_replace(['.', ','], ['', '.'], $_POST['custom_amount'])
                  : null;
        echo json_encode($inv_class->activate_plan($cid, $pid, $custom));
        break;

    case 'upgrade':
        header('Content-Type: application/json');
        $cid    = (int)($_settings->userdata('id') ?? 0);
        if (!$cid) { echo json_encode(['status'=>'failed','msg'=>'Não autorizado.']); exit(); }
        $inv_id = (int)($_POST['investment_id'] ?? 0);
        $npid   = (int)($_POST['new_plan_id']   ?? 0);
        echo json_encode($inv_class->upgrade_plan($inv_id, $cid, $npid));
        break;

    case 'save_plan':
        header('Content-Type: application/json');
        if (($_settings->userdata('type') ?? 0) != 1) { http_response_code(403); exit(); }
        echo json_encode($inv_class->save_plan());
        break;

    case 'process_yields':
        $secret = $_GET['secret'] ?? '';
        if ($secret === $_settings->info('cron_secret') || php_sapi_name()==='cli') {
            $log = $inv_class->process_daily_yields();
            header('Content-Type: application/json');
            echo json_encode(['status'=>'ok','processed'=>count($log),'log'=>$log]);
        } else { http_response_code(403); }
        break;

    default: break;
}
